test.cc 535 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. TEST(ConnectionErrorTest, InvalidHost) {
  1273. auto host = "-abcde.com";
  1274. #ifdef CPPHTTPLIB_SSL_ENABLED
  1275. auto port = 443;
  1276. SSLClient cli(host, port);
  1277. #else
  1278. auto port = 80;
  1279. Client cli(host, port);
  1280. #endif
  1281. cli.set_connection_timeout(std::chrono::seconds(2));
  1282. auto res = cli.Get("/");
  1283. ASSERT_TRUE(!res);
  1284. EXPECT_EQ(Error::Connection, res.error());
  1285. }
  1286. TEST(ConnectionErrorTest, InvalidHost2) {
  1287. auto host = "httpcan.org/";
  1288. #ifdef CPPHTTPLIB_SSL_ENABLED
  1289. SSLClient cli(host);
  1290. #else
  1291. Client cli(host);
  1292. #endif
  1293. cli.set_connection_timeout(std::chrono::seconds(2));
  1294. auto res = cli.Get("/");
  1295. ASSERT_TRUE(!res);
  1296. EXPECT_EQ(Error::Connection, res.error());
  1297. }
  1298. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1299. auto host = "httpcan.org/";
  1300. #ifdef CPPHTTPLIB_SSL_ENABLED
  1301. SSLClient cli(host);
  1302. #else
  1303. Client cli(host);
  1304. #endif
  1305. cli.set_connection_timeout(std::chrono::seconds(2));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(!res);
  1308. stringstream s;
  1309. s << "error code: " << res.error();
  1310. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1311. }
  1312. TEST(ConnectionErrorTest, InvalidPort) {
  1313. auto host = "localhost";
  1314. auto port = 44380;
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. SSLClient cli(host, port);
  1317. #else
  1318. Client cli(host, port);
  1319. #endif
  1320. cli.set_connection_timeout(std::chrono::seconds(2));
  1321. auto res = cli.Get("/");
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_TRUE(Error::Connection == res.error() ||
  1324. Error::ConnectionTimeout == res.error());
  1325. }
  1326. TEST(ConnectionErrorTest, Timeout_Online) {
  1327. auto host = "google.com";
  1328. #ifdef CPPHTTPLIB_SSL_ENABLED
  1329. auto port = 44380;
  1330. SSLClient cli(host, port);
  1331. #else
  1332. auto port = 8080;
  1333. Client cli(host, port);
  1334. #endif
  1335. cli.set_connection_timeout(std::chrono::seconds(2));
  1336. // only probe one address type so that the error reason
  1337. // correlates to the timed-out IPv4, not the unsupported
  1338. // IPv6 connection attempt
  1339. cli.set_address_family(AF_INET);
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1343. }
  1344. TEST(CancelTest, NoCancel_Online) {
  1345. auto host = "httpbingo.org";
  1346. auto path = std::string{"/range/32"};
  1347. #ifdef CPPHTTPLIB_SSL_ENABLED
  1348. auto port = 443;
  1349. SSLClient cli(host, port);
  1350. #else
  1351. auto port = 80;
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(5));
  1355. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1356. ASSERT_TRUE(res);
  1357. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1361. // Use /bytes with a large payload so that the DownloadProgress callback
  1362. // (which only fires for Content-Length responses) is invoked before the
  1363. // entire body is received, giving cancellation a chance to fire.
  1364. auto host = "httpbingo.org";
  1365. auto path = std::string{"/bytes/524288"};
  1366. #ifdef CPPHTTPLIB_SSL_ENABLED
  1367. auto port = 443;
  1368. SSLClient cli(host, port);
  1369. #else
  1370. auto port = 80;
  1371. Client cli(host, port);
  1372. #endif
  1373. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1374. cli.set_connection_timeout(std::chrono::seconds(5));
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, WithCancelLargePayload_Online) {
  1379. auto host = "httpbingo.org";
  1380. auto path = std::string{"/bytes/524288"};
  1381. #ifdef CPPHTTPLIB_SSL_ENABLED
  1382. auto port = 443;
  1383. SSLClient cli(host, port);
  1384. #else
  1385. auto port = 80;
  1386. Client cli(host, port);
  1387. #endif
  1388. cli.set_connection_timeout(std::chrono::seconds(5));
  1389. uint32_t count = 0;
  1390. auto res =
  1391. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1392. ASSERT_TRUE(!res);
  1393. EXPECT_EQ(Error::Canceled, res.error());
  1394. }
  1395. TEST(CancelTest, NoCancelPost) {
  1396. Server svr;
  1397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1398. res.set_content("Hello World!", "text/plain");
  1399. });
  1400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1401. auto se = detail::scope_exit([&] {
  1402. svr.stop();
  1403. thread.join();
  1404. ASSERT_FALSE(svr.is_running());
  1405. });
  1406. svr.wait_until_ready();
  1407. Client cli(HOST, PORT);
  1408. cli.set_connection_timeout(std::chrono::seconds(5));
  1409. auto res =
  1410. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1411. "application/json", [](uint64_t, uint64_t) { return true; });
  1412. ASSERT_TRUE(res);
  1413. EXPECT_EQ("Hello World!", res->body);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. }
  1416. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1417. Server svr;
  1418. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1419. res.set_content("Hello World!", "text/plain");
  1420. });
  1421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1422. auto se = detail::scope_exit([&] {
  1423. svr.stop();
  1424. thread.join();
  1425. ASSERT_FALSE(svr.is_running());
  1426. });
  1427. svr.wait_until_ready();
  1428. Client cli(HOST, PORT);
  1429. cli.set_connection_timeout(std::chrono::seconds(5));
  1430. auto res =
  1431. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1432. "application/json", [](uint64_t, uint64_t) { return false; });
  1433. ASSERT_TRUE(!res);
  1434. EXPECT_EQ(Error::Canceled, res.error());
  1435. }
  1436. TEST(CancelTest, WithCancelLargePayloadPost) {
  1437. Server svr;
  1438. svr.set_payload_max_length(200 * 1024 * 1024);
  1439. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1440. res.set_content(LARGE_DATA, "text/plain");
  1441. });
  1442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. thread.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. Client cli(HOST, PORT);
  1450. cli.set_payload_max_length(200 * 1024 * 1024);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPut) {
  1459. Server svr;
  1460. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1480. Server svr;
  1481. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPut) {
  1500. Server svr;
  1501. svr.set_payload_max_length(200 * 1024 * 1024);
  1502. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1503. res.set_content(LARGE_DATA, "text/plain");
  1504. });
  1505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1506. auto se = detail::scope_exit([&] {
  1507. svr.stop();
  1508. thread.join();
  1509. ASSERT_FALSE(svr.is_running());
  1510. });
  1511. svr.wait_until_ready();
  1512. Client cli(HOST, PORT);
  1513. cli.set_payload_max_length(200 * 1024 * 1024);
  1514. cli.set_connection_timeout(std::chrono::seconds(5));
  1515. auto res =
  1516. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1517. "application/json", [](uint64_t, uint64_t) { return false; });
  1518. ASSERT_TRUE(!res);
  1519. EXPECT_EQ(Error::Canceled, res.error());
  1520. }
  1521. TEST(CancelTest, NoCancelPatch) {
  1522. Server svr;
  1523. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1524. res.set_content("Hello World!", "text/plain");
  1525. });
  1526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. thread.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. Client cli(HOST, PORT);
  1534. cli.set_connection_timeout(std::chrono::seconds(5));
  1535. auto res =
  1536. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1537. "application/json", [](uint64_t, uint64_t) { return true; });
  1538. ASSERT_TRUE(res);
  1539. EXPECT_EQ("Hello World!", res->body);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. }
  1542. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1543. Server svr;
  1544. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return false; });
  1559. ASSERT_TRUE(!res);
  1560. EXPECT_EQ(Error::Canceled, res.error());
  1561. }
  1562. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1563. Server svr;
  1564. svr.set_payload_max_length(200 * 1024 * 1024);
  1565. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content(LARGE_DATA, "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_payload_max_length(200 * 1024 * 1024);
  1577. cli.set_connection_timeout(std::chrono::seconds(5));
  1578. auto res =
  1579. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1580. "application/json", [](uint64_t, uint64_t) { return false; });
  1581. ASSERT_TRUE(!res);
  1582. EXPECT_EQ(Error::Canceled, res.error());
  1583. }
  1584. TEST(CancelTest, NoCancelDelete) {
  1585. Server svr;
  1586. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content("Hello World!", "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_connection_timeout(std::chrono::seconds(5));
  1598. auto res =
  1599. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1600. "application/json", [](uint64_t, uint64_t) { return true; });
  1601. ASSERT_TRUE(res);
  1602. EXPECT_EQ("Hello World!", res->body);
  1603. EXPECT_EQ(StatusCode::OK_200, res->status);
  1604. }
  1605. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1606. Server svr;
  1607. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return false; });
  1622. ASSERT_TRUE(!res);
  1623. EXPECT_EQ(Error::Canceled, res.error());
  1624. }
  1625. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1626. Server svr;
  1627. svr.set_payload_max_length(200 * 1024 * 1024);
  1628. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content(LARGE_DATA, "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_payload_max_length(200 * 1024 * 1024);
  1640. cli.set_connection_timeout(std::chrono::seconds(5));
  1641. auto res =
  1642. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1643. "application/json", [](uint64_t, uint64_t) { return false; });
  1644. ASSERT_TRUE(!res);
  1645. EXPECT_EQ(Error::Canceled, res.error());
  1646. }
  1647. static std::string remove_whitespace(const std::string &input) {
  1648. std::string output;
  1649. output.reserve(input.size());
  1650. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1651. [](unsigned char c) { return !std::isspace(c); });
  1652. return output;
  1653. }
  1654. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1655. auto host = "httpbingo.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #ifdef CPPHTTPLIB_SSL_ENABLED
  1658. auto port = 443;
  1659. SSLClient cli(host, port);
  1660. #else
  1661. auto port = 80;
  1662. Client cli(host, port);
  1663. #endif
  1664. {
  1665. auto res = cli.Get(path);
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1668. }
  1669. {
  1670. auto res =
  1671. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1672. ASSERT_TRUE(res);
  1673. auto body = remove_whitespace(res->body);
  1674. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1675. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. {
  1679. cli.set_basic_auth("hello", "world");
  1680. auto res = cli.Get(path);
  1681. ASSERT_TRUE(res);
  1682. auto body = remove_whitespace(res->body);
  1683. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1684. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1685. EXPECT_EQ(StatusCode::OK_200, res->status);
  1686. }
  1687. {
  1688. cli.set_basic_auth("hello", "bad");
  1689. auto res = cli.Get(path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_basic_auth("bad", "world");
  1695. auto res = cli.Get(path);
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1698. }
  1699. }
  1700. #ifdef CPPHTTPLIB_SSL_ENABLED
  1701. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1702. auto host = "httpbingo.org";
  1703. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1704. auto paths = std::vector<std::string>{
  1705. "/digest-auth/auth/hello/world/MD5",
  1706. "/digest-auth/auth/hello/world/SHA-256",
  1707. };
  1708. auto port = 443;
  1709. SSLClient cli(host, port);
  1710. {
  1711. auto res = cli.Get(unauth_path);
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1714. }
  1715. {
  1716. cli.set_digest_auth("hello", "world");
  1717. for (const auto &path : paths) {
  1718. auto res = cli.Get(path.c_str());
  1719. ASSERT_TRUE(res);
  1720. auto body = remove_whitespace(res->body);
  1721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. cli.set_digest_auth("hello", "bad");
  1726. for (const auto &path : paths) {
  1727. auto res = cli.Get(path.c_str());
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1730. }
  1731. }
  1732. }
  1733. #endif
  1734. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1735. auto host = "google.com";
  1736. auto another_host = "example.com";
  1737. auto wrong_ip = "0.0.0.0";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(res);
  1746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1747. }
  1748. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1749. auto host = "google.com";
  1750. auto wrong_ip = "0.0.0.0";
  1751. #ifdef CPPHTTPLIB_SSL_ENABLED
  1752. SSLClient cli(host);
  1753. #else
  1754. Client cli(host);
  1755. #endif
  1756. cli.set_hostname_addr_map({{host, wrong_ip}});
  1757. auto res = cli.Get("/");
  1758. ASSERT_TRUE(!res);
  1759. EXPECT_EQ(Error::Connection, res.error());
  1760. }
  1761. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1762. auto host = "httpbingo.org";
  1763. auto path = std::string{"/absolute-redirect/3"};
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get(path);
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(RedirectTest, Redirect_Online) {
  1775. auto host = "httpbingo.org";
  1776. auto path = std::string{"/redirect/3"};
  1777. #ifdef CPPHTTPLIB_SSL_ENABLED
  1778. SSLClient cli(host);
  1779. #else
  1780. Client cli(host);
  1781. #endif
  1782. cli.set_follow_location(true);
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::OK_200, res->status);
  1786. }
  1787. TEST(RelativeRedirectTest, Redirect_Online) {
  1788. auto host = "httpbingo.org";
  1789. auto path = std::string{"/relative-redirect/3"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. SSLClient cli(host);
  1792. #else
  1793. Client cli(host);
  1794. #endif
  1795. cli.set_follow_location(true);
  1796. auto res = cli.Get(path);
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::OK_200, res->status);
  1799. }
  1800. TEST(TooManyRedirectTest, Redirect_Online) {
  1801. auto host = "httpbingo.org";
  1802. auto path = std::string{"/redirect/21"};
  1803. #ifdef CPPHTTPLIB_SSL_ENABLED
  1804. SSLClient cli(host);
  1805. #else
  1806. Client cli(host);
  1807. #endif
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get(path);
  1810. ASSERT_TRUE(!res);
  1811. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1812. }
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. TEST(YahooRedirectTest, Redirect_Online) {
  1815. Client cli("yahoo.com");
  1816. auto res = cli.Get("/");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1819. cli.set_follow_location(true);
  1820. res = cli.Get("/");
  1821. ASSERT_TRUE(res);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1824. }
  1825. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1826. #define REDIR_HOST "httpbingo.org"
  1827. #define REDIR_PATH "/redirect-to"
  1828. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1829. SSLClient cli(REDIR_HOST);
  1830. cli.set_follow_location(true);
  1831. auto res =
  1832. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1833. ASSERT_TRUE(res);
  1834. EXPECT_EQ(StatusCode::OK_200, res->status);
  1835. }
  1836. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1837. SSLClient cli(REDIR_HOST);
  1838. cli.set_follow_location(true);
  1839. Params params;
  1840. params.emplace("url", "http://example.com");
  1841. params.emplace("status_code", "302");
  1842. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1847. SSLClient cli(REDIR_HOST);
  1848. cli.set_follow_location(true);
  1849. Params params;
  1850. params.emplace("url", "http://example.com");
  1851. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(UrlWithSpace, Redirect_Online) {
  1856. SSLClient cli("edge.forgecdn.net");
  1857. cli.set_follow_location(true);
  1858. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::OK_200, res->status);
  1861. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1862. }
  1863. #endif
  1864. #if !defined(_WIN32) && !defined(_WIN64)
  1865. TEST(ReceiveSignals, Signal) {
  1866. auto setupSignalHandlers = []() {
  1867. struct sigaction act;
  1868. sigemptyset(&act.sa_mask);
  1869. act.sa_flags = SA_SIGINFO;
  1870. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1871. switch (sig) {
  1872. case SIGINT:
  1873. default: break;
  1874. }
  1875. };
  1876. ::sigaction(SIGINT, &act, nullptr);
  1877. };
  1878. Server svr;
  1879. int port = 0;
  1880. auto thread = std::thread([&]() {
  1881. setupSignalHandlers();
  1882. port = svr.bind_to_any_port(HOST);
  1883. svr.listen_after_bind();
  1884. });
  1885. auto se = detail::scope_exit([&] {
  1886. svr.stop();
  1887. thread.join();
  1888. ASSERT_FALSE(svr.is_running());
  1889. });
  1890. svr.wait_until_ready();
  1891. ASSERT_TRUE(svr.is_running());
  1892. pthread_kill(thread.native_handle(), SIGINT);
  1893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1894. ASSERT_TRUE(svr.is_running());
  1895. }
  1896. #endif
  1897. TEST(RedirectToDifferentPort, Redirect) {
  1898. Server svr1;
  1899. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1900. res.set_content("Hello World!", "text/plain");
  1901. });
  1902. int svr1_port = 0;
  1903. auto thread1 = std::thread([&]() {
  1904. svr1_port = svr1.bind_to_any_port(HOST);
  1905. svr1.listen_after_bind();
  1906. });
  1907. Server svr2;
  1908. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1909. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1910. });
  1911. int svr2_port = 0;
  1912. auto thread2 = std::thread([&]() {
  1913. svr2_port = svr2.bind_to_any_port(HOST);
  1914. svr2.listen_after_bind();
  1915. });
  1916. auto se = detail::scope_exit([&] {
  1917. svr2.stop();
  1918. thread2.join();
  1919. svr1.stop();
  1920. thread1.join();
  1921. ASSERT_FALSE(svr2.is_running());
  1922. ASSERT_FALSE(svr1.is_running());
  1923. });
  1924. svr1.wait_until_ready();
  1925. svr2.wait_until_ready();
  1926. Client cli("localhost", svr2_port);
  1927. cli.set_follow_location(true);
  1928. auto res = cli.Get("/2");
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(StatusCode::OK_200, res->status);
  1931. EXPECT_EQ("Hello World!", res->body);
  1932. }
  1933. static void
  1934. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1935. Server svr1;
  1936. std::string captured_authorization;
  1937. svr1.Get("/target", [&](const Request &req, Response &res) {
  1938. captured_authorization = req.get_header_value("Authorization");
  1939. res.set_content("OK", "text/plain");
  1940. });
  1941. int svr1_port = 0;
  1942. auto thread1 = std::thread([&]() {
  1943. svr1_port = svr1.bind_to_any_port(HOST);
  1944. svr1.listen_after_bind();
  1945. });
  1946. Server svr2;
  1947. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1948. res.set_redirect(
  1949. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1950. });
  1951. int svr2_port = 0;
  1952. auto thread2 = std::thread([&]() {
  1953. svr2_port = svr2.bind_to_any_port(HOST);
  1954. svr2.listen_after_bind();
  1955. });
  1956. auto se = detail::scope_exit([&] {
  1957. svr2.stop();
  1958. thread2.join();
  1959. svr1.stop();
  1960. thread1.join();
  1961. ASSERT_FALSE(svr2.is_running());
  1962. ASSERT_FALSE(svr1.is_running());
  1963. });
  1964. svr1.wait_until_ready();
  1965. svr2.wait_until_ready();
  1966. Client cli("localhost", svr2_port);
  1967. cli.set_follow_location(true);
  1968. set_auth(cli);
  1969. auto res = cli.Get("/redir");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1973. EXPECT_TRUE(captured_authorization.empty());
  1974. }
  1975. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1976. TestDoNotForwardCredentialsOnRedirect(
  1977. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1978. }
  1979. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1980. TestDoNotForwardCredentialsOnRedirect(
  1981. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1982. }
  1983. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1984. Server svr;
  1985. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1986. // Port number that overflows int — should not crash
  1987. res.set_redirect("http://localhost:99999999999999999999/target");
  1988. });
  1989. auto port = svr.bind_to_any_port(HOST);
  1990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, port);
  1998. cli.set_follow_location(true);
  1999. auto res = cli.Get("/redir");
  2000. // Should fail gracefully, not crash (no valid response due to bad port)
  2001. EXPECT_FALSE(res);
  2002. }
  2003. TEST(RedirectFromPageWithContent, Redirect) {
  2004. Server svr;
  2005. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2006. res.set_content("___", "text/plain");
  2007. res.set_redirect("/2");
  2008. });
  2009. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli("localhost", PORT);
  2021. cli.set_follow_location(true);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. EXPECT_EQ("Hello World!", body);
  2030. }
  2031. {
  2032. Client cli("localhost", PORT);
  2033. std::string body;
  2034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2035. body.append(data, data_length);
  2036. return true;
  2037. });
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::Found_302, res->status);
  2040. EXPECT_EQ("___", body);
  2041. }
  2042. }
  2043. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2044. Server svr;
  2045. auto port_str = std::to_string(PORT);
  2046. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2047. auto expected_host = "[::1]:" + port_str;
  2048. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2049. res.set_content("___", "text/plain");
  2050. // res.set_redirect("/2");
  2051. res.set_redirect(redirect_url);
  2052. });
  2053. svr.Get("/2", [&](const Request &req, Response &res) {
  2054. auto host_header = req.headers.find("Host");
  2055. ASSERT_TRUE(host_header != req.headers.end());
  2056. EXPECT_EQ(expected_host, host_header->second);
  2057. res.set_content("Hello World!", "text/plain");
  2058. });
  2059. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2060. auto se = detail::scope_exit([&] {
  2061. svr.stop();
  2062. th.join();
  2063. ASSERT_FALSE(svr.is_running());
  2064. });
  2065. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2066. // actually starts anything, so the condition !svr.is_running() will
  2067. // always remain true, and the loop never stops.
  2068. // This basically counts how many milliseconds have passed since the
  2069. // call to svr.listen(), and if after 5 seconds nothing started yet
  2070. // aborts the test.
  2071. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2072. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2073. ASSERT_LT(milliseconds, 5000U);
  2074. }
  2075. {
  2076. Client cli("::1", PORT);
  2077. cli.set_follow_location(true);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::OK_200, res->status);
  2085. EXPECT_EQ("Hello World!", body);
  2086. }
  2087. {
  2088. Client cli("::1", PORT);
  2089. std::string body;
  2090. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2091. body.append(data, data_length);
  2092. return true;
  2093. });
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::Found_302, res->status);
  2096. EXPECT_EQ("___", body);
  2097. }
  2098. }
  2099. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2100. Server svr;
  2101. svr.Get("/foo", [](const Request &req, Response &res) {
  2102. auto a = req.params.find("a");
  2103. if (a != req.params.end()) {
  2104. res.set_content((*a).second, "text/plain");
  2105. res.status = StatusCode::OK_200;
  2106. } else {
  2107. res.status = StatusCode::BadRequest_400;
  2108. }
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. {
  2118. Client cli(HOST, PORT);
  2119. cli.set_path_encode(false);
  2120. auto res = cli.Get("/foo?a=explicitly+encoded");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(StatusCode::OK_200, res->status);
  2123. // This expects it back with a space, as the `+` won't have been
  2124. // url-encoded, and server-side the params get decoded turning `+`
  2125. // into spaces.
  2126. EXPECT_EQ("explicitly encoded", res->body);
  2127. }
  2128. }
  2129. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2130. Server svr;
  2131. svr.Get("/", [](const Request &req, Response &) {
  2132. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. {
  2142. Client cli(HOST, PORT);
  2143. cli.set_path_encode(false);
  2144. auto res = cli.Get("/?something=%0A");
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. }
  2148. }
  2149. TEST(BindServerTest, BindDualStack) {
  2150. Server svr;
  2151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2152. res.set_content("Hello World!", "text/plain");
  2153. });
  2154. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2155. auto se = detail::scope_exit([&] {
  2156. svr.stop();
  2157. thread.join();
  2158. ASSERT_FALSE(svr.is_running());
  2159. });
  2160. svr.wait_until_ready();
  2161. {
  2162. Client cli("127.0.0.1", PORT);
  2163. auto res = cli.Get("/1");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ("Hello World!", res->body);
  2167. }
  2168. {
  2169. Client cli("::1", PORT);
  2170. auto res = cli.Get("/1");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. EXPECT_EQ("Hello World!", res->body);
  2174. }
  2175. }
  2176. TEST(BindServerTest, BindAndListenSeparately) {
  2177. Server svr;
  2178. int port = svr.bind_to_any_port("0.0.0.0");
  2179. ASSERT_TRUE(svr.is_valid());
  2180. ASSERT_TRUE(port > 0);
  2181. svr.stop();
  2182. }
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2186. CLIENT_CA_CERT_DIR);
  2187. int port = svr.bind_to_any_port("0.0.0.0");
  2188. ASSERT_TRUE(svr.is_valid());
  2189. ASSERT_TRUE(port > 0);
  2190. svr.stop();
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2193. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2194. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2195. int port = svr.bind_to_any_port("0.0.0.0");
  2196. ASSERT_TRUE(svr.is_valid());
  2197. ASSERT_TRUE(port > 0);
  2198. svr.stop();
  2199. }
  2200. TEST(BindServerTest, UpdateCertsPem) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2202. int port = svr.bind_to_any_port("0.0.0.0");
  2203. ASSERT_TRUE(svr.is_valid());
  2204. ASSERT_TRUE(port > 0);
  2205. // Read PEM files
  2206. std::string cert_pem, key_pem, ca_pem;
  2207. read_file(SERVER_CERT_FILE, cert_pem);
  2208. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2209. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2210. // Update server certificates using PEM API
  2211. ASSERT_TRUE(
  2212. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2213. ASSERT_TRUE(svr.is_valid());
  2214. svr.stop();
  2215. }
  2216. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2217. // Start server with client CA (enables client auth)
  2218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2219. ASSERT_TRUE(svr.is_valid());
  2220. bool handler_called = false;
  2221. svr.Get("/test", [&](const Request &req, Response &res) {
  2222. handler_called = true;
  2223. // Verify client certificate is present
  2224. auto cert = req.peer_cert();
  2225. EXPECT_TRUE(static_cast<bool>(cert));
  2226. res.set_content("ok", "text/plain");
  2227. });
  2228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. t.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. // Read PEM files
  2236. std::string cert_pem, key_pem, ca_pem;
  2237. read_file(SERVER_CERT_FILE, cert_pem);
  2238. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2239. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2240. // Update server certificates and client CA using PEM API while server running
  2241. ASSERT_TRUE(
  2242. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2243. // Connect with client certificate
  2244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2245. cli.enable_server_certificate_verification(false);
  2246. cli.set_connection_timeout(30);
  2247. auto res = cli.Get("/test");
  2248. ASSERT_TRUE(res);
  2249. ASSERT_EQ(StatusCode::OK_200, res->status);
  2250. ASSERT_TRUE(handler_called);
  2251. EXPECT_EQ("ok", res->body);
  2252. }
  2253. #endif
  2254. TEST(ErrorHandlerTest, ContentLength) {
  2255. Server svr;
  2256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2257. res.status = StatusCode::OK_200;
  2258. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2259. "text/html"); // <= Content-Length still 13
  2260. });
  2261. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2262. res.set_content("Hello World!\n", "text/plain");
  2263. res.status = 524;
  2264. });
  2265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2266. auto se = detail::scope_exit([&] {
  2267. svr.stop();
  2268. thread.join();
  2269. ASSERT_FALSE(svr.is_running());
  2270. });
  2271. svr.wait_until_ready();
  2272. {
  2273. Client cli(HOST, PORT);
  2274. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2278. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2280. }
  2281. }
  2282. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2283. TEST(ExceptionTest, WithoutExceptionHandler) {
  2284. Server svr;
  2285. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2286. throw std::runtime_error("exception...");
  2287. });
  2288. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2289. throw std::runtime_error("exception\r\n...");
  2290. });
  2291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. listen_thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. Client cli("localhost", PORT);
  2299. {
  2300. auto res = cli.Get("/exception");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2303. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2304. }
  2305. {
  2306. auto res = cli.Get("/unknown");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2310. }
  2311. }
  2312. TEST(ExceptionTest, WithExceptionHandler) {
  2313. Server svr;
  2314. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2315. std::exception_ptr ep) {
  2316. EXPECT_FALSE(ep == nullptr);
  2317. try {
  2318. std::rethrow_exception(ep);
  2319. } catch (std::exception &e) {
  2320. EXPECT_EQ("abc", std::string(e.what()));
  2321. } catch (...) {}
  2322. res.status = StatusCode::InternalServerError_500;
  2323. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2324. "text/html"); // <= Content-Length still 13 at this point
  2325. });
  2326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2327. res.set_content("Hello World!\n", "text/plain");
  2328. throw std::runtime_error("abc");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. for (size_t i = 0; i < 10; i++) {
  2338. Client cli(HOST, PORT);
  2339. for (size_t j = 0; j < 100; j++) {
  2340. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2344. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2345. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2346. }
  2347. cli.set_keep_alive(true);
  2348. for (size_t j = 0; j < 100; j++) {
  2349. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2353. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2354. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2355. }
  2356. }
  2357. }
  2358. TEST(ExceptionTest, AndErrorHandler) {
  2359. Server svr;
  2360. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2361. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2362. });
  2363. svr.set_exception_handler(
  2364. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2365. EXPECT_FALSE(ep == nullptr);
  2366. try {
  2367. std::rethrow_exception(ep);
  2368. } catch (std::exception &e) {
  2369. res.set_content(e.what(), "text/html");
  2370. } catch (...) {}
  2371. res.status = StatusCode::InternalServerError_500;
  2372. });
  2373. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2374. throw std::runtime_error("EXCEPTION");
  2375. });
  2376. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2377. res.set_content("ERROR", "text/html");
  2378. res.status = StatusCode::InternalServerError_500;
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. {
  2389. auto res = cli.Get("/exception");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2392. EXPECT_EQ("EXCEPTION", res->body);
  2393. }
  2394. {
  2395. auto res = cli.Get("/error");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2398. EXPECT_EQ("ERROR", res->body);
  2399. }
  2400. {
  2401. auto res = cli.Get("/invalid");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("NOT_FOUND", res->body);
  2405. }
  2406. }
  2407. #endif
  2408. TEST(NoContentTest, ContentLength) {
  2409. Server svr;
  2410. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2411. res.status = StatusCode::NoContent_204;
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. {
  2421. Client cli(HOST, PORT);
  2422. auto res = cli.Get("/hi");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2425. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2426. }
  2427. }
  2428. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2429. #ifdef CPPHTTPLIB_SSL_ENABLED
  2430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2431. ASSERT_TRUE(svr.is_valid());
  2432. #else
  2433. Server svr;
  2434. #endif
  2435. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("PRE_ROUTING", "on");
  2438. res.set_content("Routing Handler", "text/plain");
  2439. return httplib::Server::HandlerResponse::Handled;
  2440. }
  2441. return httplib::Server::HandlerResponse::Unhandled;
  2442. });
  2443. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2444. res.set_content("Error", "text/html");
  2445. });
  2446. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2447. if (req.path == "/routing_handler") {
  2448. res.set_header("POST_ROUTING", "on");
  2449. }
  2450. });
  2451. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2452. res.set_content("Hello World!\n", "text/plain");
  2453. });
  2454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2455. auto se = detail::scope_exit([&] {
  2456. svr.stop();
  2457. thread.join();
  2458. ASSERT_FALSE(svr.is_running());
  2459. });
  2460. svr.wait_until_ready();
  2461. {
  2462. #ifdef CPPHTTPLIB_SSL_ENABLED
  2463. SSLClient cli(HOST, PORT);
  2464. cli.enable_server_certificate_verification(false);
  2465. #else
  2466. Client cli(HOST, PORT);
  2467. #endif
  2468. auto res = cli.Get("/routing_handler");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("Routing Handler", res->body);
  2472. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2473. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2474. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2475. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2476. }
  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("/hi");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Hello World!\n", res->body);
  2488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2490. }
  2491. {
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(HOST, PORT);
  2494. cli.enable_server_certificate_verification(false);
  2495. #else
  2496. Client cli(HOST, PORT);
  2497. #endif
  2498. auto res = cli.Get("/aaa");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2501. EXPECT_EQ("Error", res->body);
  2502. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2503. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2504. }
  2505. }
  2506. TEST(RequestHandlerTest, PreRequestHandler) {
  2507. auto route_path = "/user/:user";
  2508. Server svr;
  2509. svr.Get("/hi", [](const Request &, Response &res) {
  2510. res.set_content("hi", "text/plain");
  2511. });
  2512. svr.Get(route_path, [](const Request &req, Response &res) {
  2513. res.set_content(req.path_params.at("user"), "text/plain");
  2514. });
  2515. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2516. if (req.matched_route == route_path) {
  2517. auto user = req.path_params.at("user");
  2518. if (user != "john") {
  2519. res.status = StatusCode::Forbidden_403;
  2520. res.set_content("error", "text/html");
  2521. return Server::HandlerResponse::Handled;
  2522. }
  2523. }
  2524. return Server::HandlerResponse::Unhandled;
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. {
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. EXPECT_EQ("hi", res->body);
  2539. }
  2540. {
  2541. auto res = cli.Get("/user/john");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. EXPECT_EQ("john", res->body);
  2545. }
  2546. {
  2547. auto res = cli.Get("/user/invalid-user");
  2548. ASSERT_TRUE(res);
  2549. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2550. EXPECT_EQ("error", res->body);
  2551. }
  2552. }
  2553. TEST(AnyTest, BasicOperations) {
  2554. // Default construction
  2555. httplib::any a;
  2556. EXPECT_FALSE(a.has_value());
  2557. // Value construction and any_cast (pointer form, noexcept)
  2558. httplib::any b(42);
  2559. EXPECT_TRUE(b.has_value());
  2560. auto *p = httplib::any_cast<int>(&b);
  2561. ASSERT_NE(nullptr, p);
  2562. EXPECT_EQ(42, *p);
  2563. // Type mismatch → nullptr
  2564. auto *q = httplib::any_cast<std::string>(&b);
  2565. EXPECT_EQ(nullptr, q);
  2566. // any_cast (value form) succeeds
  2567. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2568. // any_cast (value form) throws on type mismatch
  2569. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2570. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2571. #endif
  2572. // Copy
  2573. httplib::any c = b;
  2574. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2575. // Move
  2576. httplib::any d = std::move(c);
  2577. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2578. // Assignment with different type
  2579. b = std::string("hello");
  2580. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2581. // Reset
  2582. b.reset();
  2583. EXPECT_FALSE(b.has_value());
  2584. }
  2585. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2586. struct AuthCtx {
  2587. std::string user_id;
  2588. };
  2589. Server svr;
  2590. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2591. res.user_data["auth"] = AuthCtx{"alice"};
  2592. return Server::HandlerResponse::Unhandled;
  2593. });
  2594. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2595. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2596. ASSERT_NE(nullptr, ctx);
  2597. res.set_content("Hello " + ctx->user_id, "text/plain");
  2598. });
  2599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2600. auto se = detail::scope_exit([&] {
  2601. svr.stop();
  2602. thread.join();
  2603. ASSERT_FALSE(svr.is_running());
  2604. });
  2605. svr.wait_until_ready();
  2606. Client cli(HOST, PORT);
  2607. auto res = cli.Get("/me");
  2608. ASSERT_TRUE(res);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. EXPECT_EQ("Hello alice", res->body);
  2611. }
  2612. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2613. struct RoleCtx {
  2614. std::string role;
  2615. };
  2616. Server svr;
  2617. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2618. res.user_data["role"] = RoleCtx{"admin"};
  2619. return Server::HandlerResponse::Unhandled;
  2620. });
  2621. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2622. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2623. ASSERT_NE(nullptr, ctx);
  2624. res.set_content(ctx->role, "text/plain");
  2625. });
  2626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2627. auto se = detail::scope_exit([&] {
  2628. svr.stop();
  2629. thread.join();
  2630. ASSERT_FALSE(svr.is_running());
  2631. });
  2632. svr.wait_until_ready();
  2633. Client cli(HOST, PORT);
  2634. auto res = cli.Get("/role");
  2635. ASSERT_TRUE(res);
  2636. EXPECT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ("admin", res->body);
  2638. }
  2639. TEST(InvalidFormatTest, StatusCode) {
  2640. Server svr;
  2641. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2642. res.set_content("Hello World!\n", "text/plain");
  2643. res.status = 9999; // Status should be a three-digit code...
  2644. });
  2645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2646. auto se = detail::scope_exit([&] {
  2647. svr.stop();
  2648. thread.join();
  2649. ASSERT_FALSE(svr.is_running());
  2650. });
  2651. svr.wait_until_ready();
  2652. {
  2653. Client cli(HOST, PORT);
  2654. auto res = cli.Get("/hi");
  2655. ASSERT_FALSE(res);
  2656. }
  2657. }
  2658. TEST(URLFragmentTest, WithFragment) {
  2659. Server svr;
  2660. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2661. EXPECT_TRUE(req.target == "/hi");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. {
  2671. Client cli(HOST, PORT);
  2672. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2673. EXPECT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::OK_200, res->status);
  2675. res = cli.Get("/hi%23key1=val1=key2=val2");
  2676. EXPECT_TRUE(res);
  2677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2678. }
  2679. }
  2680. TEST(HeaderWriter, SetHeaderWriter) {
  2681. Server svr;
  2682. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2683. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2684. return detail::write_headers(strm, hdrs);
  2685. });
  2686. svr.Get("/hi", [](const Request &req, Response &res) {
  2687. auto it = req.headers.find("CustomClientHeader");
  2688. EXPECT_TRUE(it != req.headers.end());
  2689. EXPECT_EQ(it->second, "CustomClientValue");
  2690. res.set_content("Hello World!\n", "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. {
  2700. Client cli(HOST, PORT);
  2701. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2702. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2703. return detail::write_headers(strm, hdrs);
  2704. });
  2705. auto res = cli.Get("/hi");
  2706. EXPECT_TRUE(res);
  2707. EXPECT_EQ(StatusCode::OK_200, res->status);
  2708. auto it = res->headers.find("CustomServerHeader");
  2709. EXPECT_TRUE(it != res->headers.end());
  2710. EXPECT_EQ(it->second, "CustomServerValue");
  2711. }
  2712. }
  2713. class ServerTest : public ::testing::Test {
  2714. protected:
  2715. ServerTest()
  2716. : cli_(HOST, PORT)
  2717. #ifdef CPPHTTPLIB_SSL_ENABLED
  2718. ,
  2719. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2720. #endif
  2721. {
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. cli_.enable_server_certificate_verification(false);
  2724. #endif
  2725. // Allow LARGE_DATA (100MB) responses
  2726. cli_.set_payload_max_length(200 * 1024 * 1024);
  2727. }
  2728. virtual void SetUp() {
  2729. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2730. svr_.set_payload_max_length(200 * 1024 * 1024);
  2731. svr_.set_mount_point("/", "./www");
  2732. svr_.set_mount_point("/mount", "./www2");
  2733. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2734. svr_.Get("/hi",
  2735. [&](const Request & /*req*/, Response &res) {
  2736. res.set_content("Hello World!", "text/plain");
  2737. })
  2738. .Get("/file_content",
  2739. [&](const Request & /*req*/, Response &res) {
  2740. res.set_file_content("./www/dir/test.html");
  2741. })
  2742. .Get("/file_content_with_content_type",
  2743. [&](const Request & /*req*/, Response &res) {
  2744. res.set_file_content("./www/file", "text/plain");
  2745. })
  2746. .Get("/invalid_file_content",
  2747. [&](const Request & /*req*/, Response &res) {
  2748. res.set_file_content("./www/dir/invalid_file_path");
  2749. })
  2750. .Get("/http_response_splitting",
  2751. [&](const Request & /*req*/, Response &res) {
  2752. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2753. EXPECT_EQ(0U, res.headers.size());
  2754. EXPECT_FALSE(res.has_header("a"));
  2755. res.set_header("a", "1\nSet-Cookie: a=1");
  2756. EXPECT_EQ(0U, res.headers.size());
  2757. EXPECT_FALSE(res.has_header("a"));
  2758. res.set_header("a", "1\rSet-Cookie: a=1");
  2759. EXPECT_EQ(0U, res.headers.size());
  2760. EXPECT_FALSE(res.has_header("a"));
  2761. res.set_header("a\r\nb", "0");
  2762. EXPECT_EQ(0U, res.headers.size());
  2763. EXPECT_FALSE(res.has_header("a"));
  2764. res.set_header("a\rb", "0");
  2765. EXPECT_EQ(0U, res.headers.size());
  2766. EXPECT_FALSE(res.has_header("a"));
  2767. res.set_header("a\nb", "0");
  2768. EXPECT_EQ(0U, res.headers.size());
  2769. EXPECT_FALSE(res.has_header("a"));
  2770. res.set_redirect("1\r\nSet-Cookie: a=1");
  2771. EXPECT_EQ(0U, res.headers.size());
  2772. EXPECT_FALSE(res.has_header("Location"));
  2773. })
  2774. .Get("/slow",
  2775. [&](const Request & /*req*/, Response &res) {
  2776. std::this_thread::sleep_for(std::chrono::seconds(2));
  2777. res.set_content("slow", "text/plain");
  2778. })
  2779. #if 0
  2780. .Post("/slowpost",
  2781. [&](const Request & /*req*/, Response &res) {
  2782. std::this_thread::sleep_for(std::chrono::seconds(2));
  2783. res.set_content("slow", "text/plain");
  2784. })
  2785. #endif
  2786. .Get("/remote_addr",
  2787. [&](const Request &req, Response &res) {
  2788. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2789. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2790. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2791. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2792. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2793. #endif
  2794. res.set_content(req.remote_addr, "text/plain");
  2795. })
  2796. .Get("/local_addr",
  2797. [&](const Request &req, Response &res) {
  2798. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2799. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2800. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2801. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2802. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2803. #endif
  2804. auto local_addr = req.local_addr;
  2805. auto local_port = std::to_string(req.local_port);
  2806. res.set_content(local_addr.append(":").append(local_port),
  2807. "text/plain");
  2808. })
  2809. .Get("/endwith%",
  2810. [&](const Request & /*req*/, Response &res) {
  2811. res.set_content("Hello World!", "text/plain");
  2812. })
  2813. .Get("/a\\+\\+b",
  2814. [&](const Request &req, Response &res) {
  2815. ASSERT_TRUE(req.has_param("a +b"));
  2816. auto val = req.get_param_value("a +b");
  2817. res.set_content(val, "text/plain");
  2818. })
  2819. .Get("/", [&](const Request & /*req*/,
  2820. Response &res) { res.set_redirect("/hi"); })
  2821. .Post("/1",
  2822. [](const Request & /*req*/, Response &res) {
  2823. res.set_redirect("/2", StatusCode::SeeOther_303);
  2824. })
  2825. .Get("/2",
  2826. [](const Request & /*req*/, Response &res) {
  2827. res.set_content("redirected.", "text/plain");
  2828. res.status = StatusCode::OK_200;
  2829. })
  2830. .Post("/person",
  2831. [&](const Request &req, Response &res) {
  2832. if (req.has_param("name") && req.has_param("note")) {
  2833. persons_[req.get_param_value("name")] =
  2834. req.get_param_value("note");
  2835. } else {
  2836. res.status = StatusCode::BadRequest_400;
  2837. }
  2838. })
  2839. .Put("/person",
  2840. [&](const Request &req, Response &res) {
  2841. if (req.has_param("name") && req.has_param("note")) {
  2842. persons_[req.get_param_value("name")] =
  2843. req.get_param_value("note");
  2844. } else {
  2845. res.status = StatusCode::BadRequest_400;
  2846. }
  2847. })
  2848. .Get("/person/(.*)",
  2849. [&](const Request &req, Response &res) {
  2850. string name = req.matches[1];
  2851. if (persons_.find(name) != persons_.end()) {
  2852. auto note = persons_[name];
  2853. res.set_content(note, "text/plain");
  2854. } else {
  2855. res.status = StatusCode::NotFound_404;
  2856. }
  2857. })
  2858. .Delete("/person",
  2859. [&](const Request &req, Response &res) {
  2860. if (req.has_param("name")) {
  2861. string name = req.get_param_value("name");
  2862. if (persons_.find(name) != persons_.end()) {
  2863. persons_.erase(name);
  2864. res.set_content("DELETED", "text/plain");
  2865. } else {
  2866. res.status = StatusCode::NotFound_404;
  2867. }
  2868. } else {
  2869. res.status = StatusCode::BadRequest_400;
  2870. }
  2871. })
  2872. .Post("/x-www-form-urlencoded-json",
  2873. [&](const Request &req, Response &res) {
  2874. auto json = req.get_param_value("json");
  2875. ASSERT_EQ(JSON_DATA, json);
  2876. res.set_content(json, "appliation/json");
  2877. res.status = StatusCode::OK_200;
  2878. })
  2879. .Get("/streamed-chunked",
  2880. [&](const Request & /*req*/, Response &res) {
  2881. res.set_chunked_content_provider(
  2882. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2883. sink.os << "123";
  2884. sink.os << "456";
  2885. sink.os << "789";
  2886. sink.done();
  2887. return true;
  2888. });
  2889. })
  2890. .Get("/streamed-chunked-with-prohibited-trailer",
  2891. [&](const Request & /*req*/, Response &res) {
  2892. auto i = new int(0);
  2893. // Declare both a prohibited trailer (Content-Length) and an
  2894. // allowed one
  2895. res.set_header("Trailer", "Content-Length, X-Allowed");
  2896. res.set_chunked_content_provider(
  2897. "text/plain",
  2898. [i](size_t /*offset*/, DataSink &sink) {
  2899. switch (*i) {
  2900. case 0: sink.os << "123"; break;
  2901. case 1: sink.os << "456"; break;
  2902. case 2: sink.os << "789"; break;
  2903. case 3: {
  2904. sink.done_with_trailer(
  2905. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2906. } break;
  2907. }
  2908. (*i)++;
  2909. return true;
  2910. },
  2911. [i](bool success) {
  2912. EXPECT_TRUE(success);
  2913. delete i;
  2914. });
  2915. })
  2916. .Get("/streamed-chunked2",
  2917. [&](const Request & /*req*/, Response &res) {
  2918. auto i = new int(0);
  2919. res.set_chunked_content_provider(
  2920. "text/plain",
  2921. [i](size_t /*offset*/, DataSink &sink) {
  2922. switch (*i) {
  2923. case 0: sink.os << "123"; break;
  2924. case 1: sink.os << "456"; break;
  2925. case 2: sink.os << "789"; break;
  2926. case 3: sink.done(); break;
  2927. }
  2928. (*i)++;
  2929. return true;
  2930. },
  2931. [i](bool success) {
  2932. EXPECT_TRUE(success);
  2933. delete i;
  2934. });
  2935. })
  2936. .Get("/streamed-chunked-with-trailer",
  2937. [&](const Request & /*req*/, Response &res) {
  2938. auto i = new int(0);
  2939. res.set_header("Trailer", "Dummy1, Dummy2");
  2940. res.set_chunked_content_provider(
  2941. "text/plain",
  2942. [i](size_t /*offset*/, DataSink &sink) {
  2943. switch (*i) {
  2944. case 0: sink.os << "123"; break;
  2945. case 1: sink.os << "456"; break;
  2946. case 2: sink.os << "789"; break;
  2947. case 3: {
  2948. sink.done_with_trailer(
  2949. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2950. } break;
  2951. }
  2952. (*i)++;
  2953. return true;
  2954. },
  2955. [i](bool success) {
  2956. EXPECT_TRUE(success);
  2957. delete i;
  2958. });
  2959. })
  2960. .Get("/streamed",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_content_provider(
  2963. 6, "text/plain",
  2964. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2965. sink.os << (offset < 3 ? "a" : "b");
  2966. return true;
  2967. });
  2968. })
  2969. .Get("/streamed-with-range",
  2970. [&](const Request &req, Response &res) {
  2971. auto data = new std::string("abcdefg");
  2972. res.set_content_provider(
  2973. data->size(), "text/plain",
  2974. [data](size_t offset, size_t length, DataSink &sink) {
  2975. size_t DATA_CHUNK_SIZE = 4;
  2976. const auto &d = *data;
  2977. auto out_len =
  2978. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2979. auto ret =
  2980. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2981. EXPECT_TRUE(ret);
  2982. return true;
  2983. },
  2984. [data, &req](bool success) {
  2985. EXPECT_EQ(success, !req.has_param("error"));
  2986. delete data;
  2987. });
  2988. })
  2989. .Get("/streamed-cancel",
  2990. [&](const Request & /*req*/, Response &res) {
  2991. res.set_content_provider(
  2992. size_t(-1), "text/plain",
  2993. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2994. sink.os << "data_chunk";
  2995. return true;
  2996. });
  2997. })
  2998. .Get("/regex-with-delimiter",
  2999. [&](const Request &req, Response & /*res*/) {
  3000. ASSERT_TRUE(req.has_param("key"));
  3001. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3002. })
  3003. .Get("/with-range",
  3004. [&](const Request & /*req*/, Response &res) {
  3005. res.set_content("abcdefg", "text/plain");
  3006. })
  3007. .Get("/test-start-time",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_NE(req.start_time_,
  3010. std::chrono::steady_clock::time_point::min());
  3011. })
  3012. .Get("/with-range-customized-response",
  3013. [&](const Request & /*req*/, Response &res) {
  3014. res.status = StatusCode::BadRequest_400;
  3015. res.set_content(JSON_DATA, "application/json");
  3016. })
  3017. .Post("/chunked",
  3018. [&](const Request &req, Response & /*res*/) {
  3019. EXPECT_EQ(req.body, "dechunked post body");
  3020. })
  3021. .Post("/large-chunked",
  3022. [&](const Request &req, Response & /*res*/) {
  3023. std::string expected(6 * 30 * 1024u, 'a');
  3024. EXPECT_EQ(req.body, expected);
  3025. })
  3026. .Post("/multipart",
  3027. [&](const Request &req, Response & /*res*/) {
  3028. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3029. req.form.get_field_count("text2") +
  3030. req.form.get_field_count("file3") +
  3031. req.form.get_field_count("file4"));
  3032. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3033. req.form.get_file_count("file2"));
  3034. ASSERT_TRUE(!req.form.has_file("???"));
  3035. ASSERT_TRUE(!req.form.has_field("???"));
  3036. ASSERT_TRUE(req.body.empty());
  3037. {
  3038. const auto &text = req.form.get_field("text1");
  3039. EXPECT_EQ("text default", text);
  3040. }
  3041. {
  3042. const auto &text = req.form.get_field("text2");
  3043. EXPECT_EQ("aωb", text);
  3044. }
  3045. {
  3046. const auto &file = req.form.get_file("file1");
  3047. EXPECT_EQ("hello.txt", file.filename);
  3048. EXPECT_EQ("text/plain", file.content_type);
  3049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3050. }
  3051. {
  3052. const auto &file = req.form.get_file("file2");
  3053. EXPECT_EQ("world.json", file.filename);
  3054. EXPECT_EQ("application/json", file.content_type);
  3055. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3056. }
  3057. {
  3058. const auto &text = req.form.get_field("file3");
  3059. EXPECT_EQ(0u, text.size());
  3060. }
  3061. {
  3062. const auto &text = req.form.get_field("file4");
  3063. EXPECT_EQ(0u, text.size());
  3064. }
  3065. })
  3066. .Post("/multipart/multi_file_values",
  3067. [&](const Request &req, Response & /*res*/) {
  3068. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3069. req.form.get_field_count("multi_text1"));
  3070. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3071. ASSERT_TRUE(!req.form.has_file("???"));
  3072. ASSERT_TRUE(!req.form.has_field("???"));
  3073. ASSERT_TRUE(req.body.empty());
  3074. {
  3075. const auto &text = req.form.get_field("text");
  3076. EXPECT_EQ("default text", text);
  3077. }
  3078. {
  3079. const auto &text1_values = req.form.get_fields("multi_text1");
  3080. EXPECT_EQ(2u, text1_values.size());
  3081. EXPECT_EQ("aaaaa", text1_values[0]);
  3082. EXPECT_EQ("bbbbb", text1_values[1]);
  3083. }
  3084. {
  3085. const auto &file1_values = req.form.get_files("multi_file1");
  3086. EXPECT_EQ(2u, file1_values.size());
  3087. auto file1 = file1_values[0];
  3088. EXPECT_EQ(file1.filename, "hello.txt");
  3089. EXPECT_EQ(file1.content_type, "text/plain");
  3090. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3091. auto file2 = file1_values[1];
  3092. EXPECT_EQ(file2.filename, "world.json");
  3093. EXPECT_EQ(file2.content_type, "application/json");
  3094. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3095. }
  3096. })
  3097. .Post("/empty",
  3098. [&](const Request &req, Response &res) {
  3099. EXPECT_EQ(req.body, "");
  3100. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3101. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3102. res.set_content("empty", "text/plain");
  3103. })
  3104. .Post("/empty-no-content-type",
  3105. [&](const Request &req, Response &res) {
  3106. EXPECT_EQ(req.body, "");
  3107. EXPECT_FALSE(req.has_header("Content-Type"));
  3108. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3109. res.set_content("empty-no-content-type", "text/plain");
  3110. })
  3111. .Post("/path-only",
  3112. [&](const Request &req, Response &res) {
  3113. EXPECT_EQ(req.body, "");
  3114. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3115. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3116. res.set_content("path-only", "text/plain");
  3117. })
  3118. .Post("/path-headers-only",
  3119. [&](const Request &req, Response &res) {
  3120. EXPECT_EQ(req.body, "");
  3121. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3122. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3123. EXPECT_EQ("world", req.get_header_value("hello"));
  3124. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3125. res.set_content("path-headers-only", "text/plain");
  3126. })
  3127. .Post("/post-large",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, LARGE_DATA);
  3130. res.set_content(req.body, "text/plain");
  3131. })
  3132. .Post("/post-loopback",
  3133. [&](const Request &, Response &res,
  3134. ContentReader const &content_reader) {
  3135. std::string body;
  3136. content_reader([&](const char *data, size_t data_length) {
  3137. body.append(data, data_length);
  3138. return true;
  3139. });
  3140. res.set_content(body, "text/plain");
  3141. })
  3142. .Put("/put-loopback",
  3143. [&](const Request &, Response &res,
  3144. ContentReader const &content_reader) {
  3145. std::string body;
  3146. content_reader([&](const char *data, size_t data_length) {
  3147. body.append(data, data_length);
  3148. return true;
  3149. });
  3150. res.set_content(body, "text/plain");
  3151. })
  3152. .Patch("/patch-loopback",
  3153. [&](const Request &, Response &res,
  3154. ContentReader const &content_reader) {
  3155. std::string body;
  3156. content_reader([&](const char *data, size_t data_length) {
  3157. body.append(data, data_length);
  3158. return true;
  3159. });
  3160. res.set_content(body, "text/plain");
  3161. })
  3162. .Put("/empty-no-content-type",
  3163. [&](const Request &req, Response &res) {
  3164. EXPECT_EQ(req.body, "");
  3165. EXPECT_FALSE(req.has_header("Content-Type"));
  3166. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3167. res.set_content("empty-no-content-type", "text/plain");
  3168. })
  3169. .Put("/put",
  3170. [&](const Request &req, Response &res) {
  3171. EXPECT_EQ(req.body, "PUT");
  3172. res.set_content(req.body, "text/plain");
  3173. })
  3174. .Put("/put-large",
  3175. [&](const Request &req, Response &res) {
  3176. EXPECT_EQ(req.body, LARGE_DATA);
  3177. res.set_content(req.body, "text/plain");
  3178. })
  3179. .Patch("/patch",
  3180. [&](const Request &req, Response &res) {
  3181. EXPECT_EQ(req.body, "PATCH");
  3182. res.set_content(req.body, "text/plain");
  3183. })
  3184. .Delete("/delete",
  3185. [&](const Request & /*req*/, Response &res) {
  3186. res.set_content("DELETE", "text/plain");
  3187. })
  3188. .Delete("/delete-body",
  3189. [&](const Request &req, Response &res) {
  3190. EXPECT_EQ(req.body, "content");
  3191. res.set_content(req.body, "text/plain");
  3192. })
  3193. .Options(R"(\*)",
  3194. [&](const Request & /*req*/, Response &res) {
  3195. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3196. })
  3197. .Get("/request-target",
  3198. [&](const Request &req, Response & /*res*/) {
  3199. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3200. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3201. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3202. })
  3203. .Get("/long-query-value",
  3204. [&](const Request &req, Response & /*res*/) {
  3205. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3206. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3207. })
  3208. .Get("/too-long-query-value",
  3209. [&](const Request &req, Response & /*res*/) {
  3210. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3211. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3212. })
  3213. .Get("/array-param",
  3214. [&](const Request &req, Response & /*res*/) {
  3215. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3216. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3217. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3218. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3219. })
  3220. .Post("/validate-no-multiple-headers",
  3221. [&](const Request &req, Response & /*res*/) {
  3222. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3223. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3224. })
  3225. .Post("/content_receiver",
  3226. [&](const Request &req, Response &res,
  3227. const ContentReader &content_reader) {
  3228. if (req.is_multipart_form_data()) {
  3229. std::vector<FormData> items;
  3230. content_reader(
  3231. [&](const FormData &file) {
  3232. items.push_back(file);
  3233. return true;
  3234. },
  3235. [&](const char *data, size_t data_length) {
  3236. items.back().content.append(data, data_length);
  3237. return true;
  3238. });
  3239. EXPECT_EQ(5u, items.size());
  3240. {
  3241. const auto &file = get_file_value(items, "text1");
  3242. EXPECT_TRUE(file.filename.empty());
  3243. EXPECT_EQ("text default", file.content);
  3244. }
  3245. {
  3246. const auto &file = get_file_value(items, "text2");
  3247. EXPECT_TRUE(file.filename.empty());
  3248. EXPECT_EQ("aωb", file.content);
  3249. }
  3250. {
  3251. const auto &file = get_file_value(items, "file1");
  3252. EXPECT_EQ("hello.txt", file.filename);
  3253. EXPECT_EQ("text/plain", file.content_type);
  3254. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3255. }
  3256. {
  3257. const auto &file = get_file_value(items, "file2");
  3258. EXPECT_EQ("world.json", file.filename);
  3259. EXPECT_EQ("application/json", file.content_type);
  3260. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3261. }
  3262. {
  3263. const auto &file = get_file_value(items, "file3");
  3264. EXPECT_TRUE(file.filename.empty());
  3265. EXPECT_EQ("application/octet-stream", file.content_type);
  3266. EXPECT_EQ(0u, file.content.size());
  3267. }
  3268. } else {
  3269. std::string body;
  3270. content_reader([&](const char *data, size_t data_length) {
  3271. EXPECT_EQ(7U, data_length);
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. EXPECT_EQ(body, "content");
  3276. res.set_content(body, "text/plain");
  3277. }
  3278. })
  3279. .Put("/content_receiver",
  3280. [&](const Request & /*req*/, Response &res,
  3281. const ContentReader &content_reader) {
  3282. std::string body;
  3283. content_reader([&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. EXPECT_EQ(body, "content");
  3288. res.set_content(body, "text/plain");
  3289. })
  3290. .Patch("/content_receiver",
  3291. [&](const Request & /*req*/, Response &res,
  3292. const ContentReader &content_reader) {
  3293. std::string body;
  3294. content_reader([&](const char *data, size_t data_length) {
  3295. body.append(data, data_length);
  3296. return true;
  3297. });
  3298. EXPECT_EQ(body, "content");
  3299. res.set_content(body, "text/plain");
  3300. })
  3301. .Post("/query-string-and-body",
  3302. [&](const Request &req, Response & /*res*/) {
  3303. ASSERT_TRUE(req.has_param("key"));
  3304. EXPECT_EQ(req.get_param_value("key"), "value");
  3305. EXPECT_EQ(req.body, "content");
  3306. })
  3307. .Get("/last-request",
  3308. [&](const Request &req, Response & /*res*/) {
  3309. EXPECT_EQ("close", req.get_header_value("Connection"));
  3310. })
  3311. .Get(R"(/redirect/(\d+))",
  3312. [&](const Request &req, Response &res) {
  3313. auto num = std::stoi(req.matches[1]) + 1;
  3314. std::string url = "/redirect/" + std::to_string(num);
  3315. res.set_redirect(url);
  3316. })
  3317. .Post("/binary",
  3318. [&](const Request &req, Response &res) {
  3319. EXPECT_EQ(4U, req.body.size());
  3320. EXPECT_EQ("application/octet-stream",
  3321. req.get_header_value("Content-Type"));
  3322. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3323. res.set_content(req.body, "application/octet-stream");
  3324. })
  3325. .Put("/binary",
  3326. [&](const Request &req, Response &res) {
  3327. EXPECT_EQ(4U, req.body.size());
  3328. EXPECT_EQ("application/octet-stream",
  3329. req.get_header_value("Content-Type"));
  3330. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3331. res.set_content(req.body, "application/octet-stream");
  3332. })
  3333. .Patch("/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. .Delete("/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. .Get("/issue1772",
  3350. [&](const Request & /*req*/, Response &res) {
  3351. res.status = 401;
  3352. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3353. })
  3354. .Delete("/issue609",
  3355. [](const httplib::Request &, httplib::Response &res,
  3356. const httplib::ContentReader &) {
  3357. res.set_content("ok", "text/plain");
  3358. })
  3359. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3360. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3361. .Get("/compress",
  3362. [&](const Request & /*req*/, Response &res) {
  3363. res.set_content(
  3364. "12345678901234567890123456789012345678901234567890123456789"
  3365. "01234567890123456789012345678901234567890",
  3366. "text/plain");
  3367. })
  3368. .Get("/compress-with-charset",
  3369. [&](const Request & /*req*/, Response &res) {
  3370. res.set_content(
  3371. "12345678901234567890123456789012345678901234567890123456789"
  3372. "01234567890123456789012345678901234567890",
  3373. "application/json; charset=utf-8");
  3374. })
  3375. .Get("/nocompress",
  3376. [&](const Request & /*req*/, Response &res) {
  3377. res.set_content(
  3378. "12345678901234567890123456789012345678901234567890123456789"
  3379. "01234567890123456789012345678901234567890",
  3380. "application/octet-stream");
  3381. })
  3382. .Post("/compress-multipart",
  3383. [&](const Request &req, Response & /*res*/) {
  3384. EXPECT_EQ(2u, req.form.fields.size());
  3385. ASSERT_TRUE(!req.form.has_field("???"));
  3386. {
  3387. const auto &text = req.form.get_field("key1");
  3388. EXPECT_EQ("test", text);
  3389. }
  3390. {
  3391. const auto &text = req.form.get_field("key2");
  3392. EXPECT_EQ("--abcdefg123", text);
  3393. }
  3394. })
  3395. #endif
  3396. ;
  3397. persons_["john"] = "programmer";
  3398. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3399. svr_.wait_until_ready();
  3400. }
  3401. virtual void TearDown() {
  3402. svr_.stop();
  3403. if (!request_threads_.empty()) {
  3404. std::this_thread::sleep_for(std::chrono::seconds(1));
  3405. for (auto &t : request_threads_) {
  3406. t.join();
  3407. }
  3408. }
  3409. t_.join();
  3410. }
  3411. map<string, string> persons_;
  3412. #ifdef CPPHTTPLIB_SSL_ENABLED
  3413. SSLClient cli_;
  3414. SSLServer svr_;
  3415. #else
  3416. Client cli_;
  3417. Server svr_;
  3418. #endif
  3419. thread t_;
  3420. std::vector<thread> request_threads_;
  3421. };
  3422. TEST_F(ServerTest, GetMethod200) {
  3423. auto res = cli_.Get("/hi");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ("HTTP/1.1", res->version);
  3426. EXPECT_EQ(StatusCode::OK_200, res->status);
  3427. EXPECT_EQ("OK", res->reason);
  3428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3430. EXPECT_EQ("Hello World!", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetEmptyFile) {
  3433. auto res = cli_.Get("/empty_file");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::OK_200, res->status);
  3436. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3437. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3438. EXPECT_EQ("", res->body);
  3439. }
  3440. TEST_F(ServerTest, GetFileContent) {
  3441. auto res = cli_.Get("/file_content");
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3446. EXPECT_EQ("test.html", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetFileContentWithRange) {
  3449. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3453. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3454. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3455. EXPECT_EQ("est", res->body);
  3456. }
  3457. TEST_F(ServerTest, GetFileContentWithContentType) {
  3458. auto res = cli_.Get("/file_content_with_content_type");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3462. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3463. EXPECT_EQ("file\n", res->body);
  3464. }
  3465. TEST_F(ServerTest, GetInvalidFileContent) {
  3466. auto res = cli_.Get("/invalid_file_content");
  3467. ASSERT_TRUE(res);
  3468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3469. }
  3470. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3471. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3472. ASSERT_TRUE(res);
  3473. EXPECT_EQ("HTTP/1.1", res->version);
  3474. EXPECT_EQ(StatusCode::OK_200, res->status);
  3475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3476. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3477. EXPECT_EQ("Hello World!", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethod302) {
  3480. auto res = cli_.Get("/");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::Found_302, res->status);
  3483. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3484. }
  3485. TEST_F(ServerTest, GetMethod302Redirect) {
  3486. cli_.set_follow_location(true);
  3487. auto res = cli_.Get("/");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::OK_200, res->status);
  3490. EXPECT_EQ("Hello World!", res->body);
  3491. EXPECT_EQ("/hi", res->location);
  3492. }
  3493. TEST_F(ServerTest, GetMethod404) {
  3494. auto res = cli_.Get("/invalid");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3497. }
  3498. TEST_F(ServerTest, HeadMethod200) {
  3499. auto res = cli_.Head("/hi");
  3500. ASSERT_TRUE(res);
  3501. EXPECT_EQ(StatusCode::OK_200, res->status);
  3502. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3503. EXPECT_TRUE(res->body.empty());
  3504. }
  3505. TEST_F(ServerTest, HeadMethod200Static) {
  3506. auto res = cli_.Head("/mount/dir/index.html");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3510. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3511. EXPECT_TRUE(res->body.empty());
  3512. }
  3513. TEST_F(ServerTest, HeadMethod404) {
  3514. auto res = cli_.Head("/invalid");
  3515. ASSERT_TRUE(res);
  3516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3517. EXPECT_TRUE(res->body.empty());
  3518. }
  3519. TEST_F(ServerTest, GetMethodPersonJohn) {
  3520. auto res = cli_.Get("/person/john");
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3524. EXPECT_EQ("programmer", res->body);
  3525. }
  3526. TEST_F(ServerTest, PostMethod1) {
  3527. auto res = cli_.Get("/person/john1");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3530. res = cli_.Post("/person", "name=john1&note=coder",
  3531. "application/x-www-form-urlencoded");
  3532. ASSERT_TRUE(res);
  3533. ASSERT_EQ(StatusCode::OK_200, res->status);
  3534. res = cli_.Get("/person/john1");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3538. ASSERT_EQ("coder", res->body);
  3539. }
  3540. TEST_F(ServerTest, PostMethod2) {
  3541. auto res = cli_.Get("/person/john2");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3544. Params params;
  3545. params.emplace("name", "john2");
  3546. params.emplace("note", "coder");
  3547. res = cli_.Post("/person", params);
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. res = cli_.Get("/person/john2");
  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, PutMethod3) {
  3557. auto res = cli_.Get("/person/john3");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3560. Params params;
  3561. params.emplace("name", "john3");
  3562. params.emplace("note", "coder");
  3563. res = cli_.Put("/person", params);
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. res = cli_.Get("/person/john3");
  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, DeleteMethod1) {
  3573. auto res = cli_.Get("/person/john4");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. Params params;
  3577. params.emplace("name", "john4");
  3578. params.emplace("note", "coder");
  3579. res = cli_.Post("/person", params);
  3580. ASSERT_TRUE(res);
  3581. ASSERT_EQ(StatusCode::OK_200, res->status);
  3582. res = cli_.Get("/person/john4");
  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. Params delete_params;
  3588. delete_params.emplace("name", "john4");
  3589. res = cli_.Delete("/person", delete_params);
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_EQ("DELETED", res->body);
  3593. res = cli_.Get("/person/john4");
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3596. }
  3597. TEST_F(ServerTest, DeleteMethod2) {
  3598. auto res = cli_.Get("/person/john5");
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3601. Params params;
  3602. params.emplace("name", "john5");
  3603. params.emplace("note", "developer");
  3604. res = cli_.Post("/person", params);
  3605. ASSERT_TRUE(res);
  3606. ASSERT_EQ(StatusCode::OK_200, res->status);
  3607. res = cli_.Get("/person/john5");
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3611. ASSERT_EQ("developer", res->body);
  3612. Params delete_params;
  3613. delete_params.emplace("name", "john5");
  3614. Headers headers;
  3615. headers.emplace("Custom-Header", "test-value");
  3616. res = cli_.Delete("/person", headers, delete_params);
  3617. ASSERT_TRUE(res);
  3618. ASSERT_EQ(StatusCode::OK_200, res->status);
  3619. ASSERT_EQ("DELETED", res->body);
  3620. res = cli_.Get("/person/john5");
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3623. }
  3624. TEST_F(ServerTest, DeleteMethod3) {
  3625. auto res = cli_.Get("/person/john6");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3628. Params params;
  3629. params.emplace("name", "john6");
  3630. params.emplace("note", "tester");
  3631. res = cli_.Post("/person", params);
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. res = cli_.Get("/person/john6");
  3635. ASSERT_TRUE(res);
  3636. ASSERT_EQ(StatusCode::OK_200, res->status);
  3637. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3638. ASSERT_EQ("tester", res->body);
  3639. Params delete_params;
  3640. delete_params.emplace("name", "john6");
  3641. Headers headers;
  3642. headers.emplace("Custom-Header", "test-value");
  3643. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ("DELETED", res->body);
  3647. res = cli_.Get("/person/john6");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3650. }
  3651. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3652. Params params;
  3653. params.emplace("json", JSON_DATA);
  3654. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::OK_200, res->status);
  3657. ASSERT_EQ(JSON_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PostEmptyContent) {
  3660. auto res = cli_.Post("/empty", "", "text/plain");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ("empty", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3666. auto res = cli_.Post("/empty-no-content-type");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::OK_200, res->status);
  3669. ASSERT_EQ("empty-no-content-type", res->body);
  3670. }
  3671. TEST_F(ServerTest, PostPathOnly) {
  3672. auto res = cli_.Post("/path-only");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. ASSERT_EQ("path-only", res->body);
  3676. }
  3677. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3678. auto res = cli_.Post("/path-headers-only",
  3679. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ("path-headers-only", res->body);
  3683. }
  3684. TEST_F(ServerTest, PostLarge) {
  3685. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3686. ASSERT_TRUE(res);
  3687. ASSERT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ(LARGE_DATA, res->body);
  3689. }
  3690. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3691. auto res = cli_.Put("/empty-no-content-type");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("empty-no-content-type", res->body);
  3695. }
  3696. TEST_F(ServerTest, GetMethodDir) {
  3697. auto res = cli_.Get("/dir/");
  3698. ASSERT_TRUE(res);
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3701. auto body = R"(<html>
  3702. <head>
  3703. </head>
  3704. <body>
  3705. <a href="/dir/test.html">Test</a>
  3706. <a href="/hi">hi</a>
  3707. </body>
  3708. </html>
  3709. )";
  3710. EXPECT_EQ(body, res->body);
  3711. }
  3712. TEST_F(ServerTest, GetMethodDirTest) {
  3713. auto res = cli_.Get("/dir/test.html");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3717. EXPECT_EQ("test.html", res->body);
  3718. }
  3719. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3720. auto res = cli_.Get("/dir/../dir/test.html");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3724. EXPECT_EQ("test.html", res->body);
  3725. }
  3726. TEST_F(ServerTest, GetMethodInvalidPath) {
  3727. auto res = cli_.Get("/dir/../test.html");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3730. }
  3731. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3732. auto res = cli_.Get("/../www/dir/test.html");
  3733. ASSERT_TRUE(res);
  3734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3735. }
  3736. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3737. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3738. ASSERT_TRUE(res);
  3739. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3740. }
  3741. TEST_F(ServerTest, GetMethodDirMountTest) {
  3742. auto res = cli_.Get("/mount/dir/test.html");
  3743. ASSERT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3746. EXPECT_EQ("test.html", res->body);
  3747. }
  3748. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3749. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3753. EXPECT_EQ("test.html", res->body);
  3754. }
  3755. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3756. auto res = cli_.Get("/mount/dir/../test.html");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3759. }
  3760. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3761. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3762. ASSERT_TRUE(res);
  3763. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3764. }
  3765. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3766. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3767. ASSERT_TRUE(res);
  3768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3769. }
  3770. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3771. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3774. }
  3775. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3776. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3779. }
  3780. TEST_F(ServerTest, PostMethod303) {
  3781. auto res = cli_.Post("/1", "body", "text/plain");
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3784. EXPECT_EQ("/2", res->get_header_value("Location"));
  3785. }
  3786. TEST_F(ServerTest, PostMethod303Redirect) {
  3787. cli_.set_follow_location(true);
  3788. auto res = cli_.Post("/1", "body", "text/plain");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. EXPECT_EQ("redirected.", res->body);
  3792. EXPECT_EQ("/2", res->location);
  3793. }
  3794. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3795. auto res = cli_.Get("/dir/test.abcde");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::OK_200, res->status);
  3798. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3799. EXPECT_EQ("abcde", res->body);
  3800. }
  3801. TEST_F(ServerTest, StaticFileRange) {
  3802. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3809. EXPECT_EQ(std::string("cd"), res->body);
  3810. }
  3811. TEST_F(ServerTest, StaticFileRanges) {
  3812. auto res =
  3813. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_TRUE(
  3817. res->get_header_value("Content-Type")
  3818. .find(
  3819. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3820. 0);
  3821. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3822. }
  3823. TEST_F(ServerTest, StaticFileRangeHead) {
  3824. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3825. ASSERT_TRUE(res);
  3826. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3827. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3829. EXPECT_EQ(true, res->has_header("Content-Range"));
  3830. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3831. }
  3832. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3833. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3837. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(true, res->has_header("Content-Range"));
  3839. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3840. res->get_header_value("Content-Range"));
  3841. EXPECT_EQ("LAST\n", res->body);
  3842. }
  3843. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3844. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3849. EXPECT_EQ(true, res->has_header("Content-Range"));
  3850. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3851. }
  3852. TEST_F(ServerTest, StaticFileBigFile) {
  3853. auto res = cli_.Get("/dir/1MB.txt");
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::OK_200, res->status);
  3856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3858. }
  3859. TEST_F(ServerTest, InvalidBaseDirMount) {
  3860. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3861. }
  3862. TEST_F(ServerTest, Binary) {
  3863. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3864. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3865. "application/octet-stream");
  3866. ASSERT_TRUE(res);
  3867. ASSERT_EQ(StatusCode::OK_200, res->status);
  3868. ASSERT_EQ(4U, res->body.size());
  3869. res = cli_.Put("/binary", binary.data(), binary.size(),
  3870. "application/octet-stream");
  3871. ASSERT_TRUE(res);
  3872. ASSERT_EQ(StatusCode::OK_200, res->status);
  3873. ASSERT_EQ(4U, res->body.size());
  3874. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3875. "application/octet-stream");
  3876. ASSERT_TRUE(res);
  3877. ASSERT_EQ(StatusCode::OK_200, res->status);
  3878. ASSERT_EQ(4U, res->body.size());
  3879. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3880. "application/octet-stream");
  3881. ASSERT_TRUE(res);
  3882. ASSERT_EQ(StatusCode::OK_200, res->status);
  3883. ASSERT_EQ(4U, res->body.size());
  3884. }
  3885. TEST_F(ServerTest, BinaryString) {
  3886. auto binary = std::string("\x00\x01\x02\x03", 4);
  3887. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::OK_200, res->status);
  3890. ASSERT_EQ(4U, res->body.size());
  3891. res = cli_.Put("/binary", binary, "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_.Patch("/binary", binary, "application/octet-stream");
  3896. ASSERT_TRUE(res);
  3897. ASSERT_EQ(StatusCode::OK_200, res->status);
  3898. ASSERT_EQ(4U, res->body.size());
  3899. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3900. ASSERT_TRUE(res);
  3901. ASSERT_EQ(StatusCode::OK_200, res->status);
  3902. ASSERT_EQ(4U, res->body.size());
  3903. }
  3904. TEST_F(ServerTest, EmptyRequest) {
  3905. auto res = cli_.Get("");
  3906. ASSERT_TRUE(!res);
  3907. EXPECT_EQ(Error::Connection, res.error());
  3908. }
  3909. TEST_F(ServerTest, LongRequest) {
  3910. std::string request;
  3911. for (size_t i = 0; i < 545; i++) {
  3912. request += "/TooLongRequest";
  3913. }
  3914. request += "OK";
  3915. auto res = cli_.Get(request.c_str());
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3918. }
  3919. TEST_F(ServerTest, TooLongRequest) {
  3920. std::string request;
  3921. for (size_t i = 0; i < 546; i++) {
  3922. request += "/TooLongRequest";
  3923. }
  3924. request += "_NG";
  3925. auto start = std::chrono::high_resolution_clock::now();
  3926. cli_.set_keep_alive(true);
  3927. auto res = cli_.Get(request.c_str());
  3928. auto end = std::chrono::high_resolution_clock::now();
  3929. auto elapsed =
  3930. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3931. .count();
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3934. EXPECT_LE(elapsed, 1000);
  3935. EXPECT_EQ("close", res->get_header_value("Connection"));
  3936. EXPECT_FALSE(cli_.is_socket_open());
  3937. }
  3938. TEST_F(ServerTest, AlmostTooLongRequest) {
  3939. // test for #2046 - URI length check shouldn't include other content on req
  3940. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3941. // leading /, space, HTTP/1.1)
  3942. std::string request =
  3943. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3944. auto res = cli_.Get(request.c_str());
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3947. }
  3948. TEST_F(ServerTest, LongHeader) {
  3949. Request req;
  3950. req.method = "GET";
  3951. req.path = "/hi";
  3952. std::string host_and_port;
  3953. host_and_port += HOST;
  3954. host_and_port += ":";
  3955. host_and_port += std::to_string(PORT);
  3956. req.headers.emplace("Host", host_and_port.c_str());
  3957. req.headers.emplace("Accept", "*/*");
  3958. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3959. req.headers.emplace(
  3960. "Header-Name",
  3961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@");
  3990. auto res = std::make_shared<Response>();
  3991. auto error = Error::Success;
  3992. auto ret = cli_.send(req, *res, error);
  3993. ASSERT_TRUE(ret);
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. }
  3996. TEST_F(ServerTest, LongQueryValue) {
  3997. auto start = std::chrono::high_resolution_clock::now();
  3998. cli_.set_keep_alive(true);
  3999. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4000. auto end = std::chrono::high_resolution_clock::now();
  4001. auto elapsed =
  4002. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4003. .count();
  4004. ASSERT_TRUE(res);
  4005. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4006. EXPECT_LE(elapsed, 1000);
  4007. EXPECT_EQ("close", res->get_header_value("Connection"));
  4008. EXPECT_FALSE(cli_.is_socket_open());
  4009. }
  4010. TEST_F(ServerTest, TooLongQueryValue) {
  4011. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4012. ASSERT_FALSE(res);
  4013. EXPECT_EQ(Error::Read, res.error());
  4014. }
  4015. TEST_F(ServerTest, TooLongHeader) {
  4016. Request req;
  4017. req.method = "GET";
  4018. req.path = "/hi";
  4019. std::string host_and_port;
  4020. host_and_port += HOST;
  4021. host_and_port += ":";
  4022. host_and_port += std::to_string(PORT);
  4023. req.headers.emplace("Host", host_and_port.c_str());
  4024. req.headers.emplace("Accept", "*/*");
  4025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4026. req.headers.emplace(
  4027. "Header-Name",
  4028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@");
  4057. auto res = std::make_shared<Response>();
  4058. auto error = Error::Success;
  4059. auto ret = cli_.send(req, *res, error);
  4060. ASSERT_TRUE(ret);
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. }
  4063. TEST_F(ServerTest, HeaderCountAtLimit) {
  4064. // Test with headers just under the 100 limit
  4065. httplib::Headers headers;
  4066. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4067. // This should keep us just under the 100 header limit
  4068. for (int i = 0; i < 95; i++) {
  4069. std::string name = "X-Test-Header-" + std::to_string(i);
  4070. std::string value = "value" + std::to_string(i);
  4071. headers.emplace(name, value);
  4072. }
  4073. // This should work fine as we're under the limit
  4074. auto res = cli_.Get("/hi", headers);
  4075. EXPECT_TRUE(res);
  4076. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4077. }
  4078. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4079. // Test with many headers to exceed the 100 limit
  4080. httplib::Headers headers;
  4081. // Add 150 headers to definitely exceed the 100 limit
  4082. for (int i = 0; i < 150; i++) {
  4083. std::string name = "X-Test-Header-" + std::to_string(i);
  4084. std::string value = "value" + std::to_string(i);
  4085. headers.emplace(name, value);
  4086. }
  4087. // This should fail due to exceeding header count limit
  4088. cli_.set_keep_alive(true);
  4089. auto res = cli_.Get("/hi", headers);
  4090. // The server should respond with 400 Bad Request
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4093. EXPECT_EQ("close", res->get_header_value("Connection"));
  4094. EXPECT_FALSE(cli_.is_socket_open());
  4095. }
  4096. TEST_F(ServerTest, PercentEncoding) {
  4097. auto res = cli_.Get("/e%6edwith%");
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. }
  4101. TEST_F(ServerTest, PercentEncodingUnicode) {
  4102. auto res = cli_.Get("/e%u006edwith%");
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::OK_200, res->status);
  4105. }
  4106. TEST_F(ServerTest, InvalidPercentEncoding) {
  4107. auto res = cli_.Get("/%endwith%");
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4110. }
  4111. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4112. auto res = cli_.Get("/%uendwith%");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4115. }
  4116. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4117. auto res = cli_.Get("/hello?aaa=bbb%");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4120. }
  4121. TEST_F(ServerTest, PlusSignEncoding) {
  4122. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::OK_200, res->status);
  4125. EXPECT_EQ("a +b", res->body);
  4126. }
  4127. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4128. // This test simulates a potential DoS attack using many headers
  4129. // to verify our security fix prevents memory exhaustion
  4130. httplib::Headers attack_headers;
  4131. // Attempt to add many headers like an attacker would (200 headers to far
  4132. // exceed limit)
  4133. for (int i = 0; i < 200; i++) {
  4134. std::string name = "X-Attack-Header-" + std::to_string(i);
  4135. std::string value = "attack_payload_" + std::to_string(i);
  4136. attack_headers.emplace(name, value);
  4137. }
  4138. // Try to POST with excessive headers
  4139. cli_.set_keep_alive(true);
  4140. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4141. // Should either fail or return 400 Bad Request due to security limit
  4142. if (res) {
  4143. // If we get a response, it should be 400 Bad Request
  4144. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4145. EXPECT_EQ("close", res->get_header_value("Connection"));
  4146. }
  4147. EXPECT_FALSE(cli_.is_socket_open());
  4148. }
  4149. TEST_F(ServerTest, MultipartFormData) {
  4150. UploadFormDataItems items = {
  4151. {"text1", "text default", "", ""},
  4152. {"text2", "aωb", "", ""},
  4153. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4154. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4155. {"file3", "", "", "application/octet-stream"},
  4156. {"file4", "", "", " application/json tmp-string "}};
  4157. auto res = cli_.Post("/multipart", items);
  4158. ASSERT_TRUE(res);
  4159. EXPECT_EQ(StatusCode::OK_200, res->status);
  4160. }
  4161. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4162. UploadFormDataItems items = {
  4163. {"text", "default text", "", ""},
  4164. {"multi_text1", "aaaaa", "", ""},
  4165. {"multi_text1", "bbbbb", "", ""},
  4166. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4167. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4168. "application/json"},
  4169. };
  4170. auto res = cli_.Post("/multipart/multi_file_values", items);
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. }
  4174. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4175. auto res = cli_.Get("/hi");
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::OK_200, res->status);
  4178. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4179. EXPECT_EQ("Hello World!", res->body);
  4180. }
  4181. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4182. Request req;
  4183. req.method = "POST";
  4184. req.path = "/chunked";
  4185. std::string host_and_port;
  4186. host_and_port += HOST;
  4187. host_and_port += ":";
  4188. host_and_port += std::to_string(PORT);
  4189. req.headers.emplace("Host", host_and_port.c_str());
  4190. req.headers.emplace("Accept", "*/*");
  4191. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4192. req.headers.emplace("Content-Type", "text/plain");
  4193. req.headers.emplace("Content-Length", "0");
  4194. req.headers.emplace(
  4195. "Transfer-Encoding",
  4196. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4197. // Client does not chunk, so make a chunked body manually.
  4198. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4199. auto res = std::make_shared<Response>();
  4200. auto error = Error::Success;
  4201. auto ret = cli_.send(req, *res, error);
  4202. ASSERT_TRUE(ret);
  4203. EXPECT_EQ(StatusCode::OK_200, res->status);
  4204. }
  4205. TEST_F(ServerTest, GetStreamed2) {
  4206. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("ab"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetStreamed) {
  4215. auto res = cli_.Get("/streamed");
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4219. EXPECT_EQ(std::string("aaabbb"), res->body);
  4220. }
  4221. TEST_F(ServerTest, GetStreamedWithRange1) {
  4222. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4225. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(true, res->has_header("Content-Range"));
  4227. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4228. EXPECT_EQ(std::string("def"), res->body);
  4229. }
  4230. TEST_F(ServerTest, GetStreamedWithRange2) {
  4231. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("bcdefg"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4240. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4241. ASSERT_TRUE(res);
  4242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4243. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4244. EXPECT_EQ(true, res->has_header("Content-Range"));
  4245. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4246. EXPECT_EQ(std::string("efg"), res->body);
  4247. }
  4248. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4249. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4252. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4253. EXPECT_EQ(false, res->has_header("Content-Range"));
  4254. EXPECT_EQ(0U, res->body.size());
  4255. }
  4256. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4257. auto res = cli_.Get("/streamed-with-range",
  4258. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4259. "92233720368547758079223372036854775807"}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4262. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(0U, res->body.size());
  4265. }
  4266. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4267. auto res = cli_.Get(
  4268. "/with-range",
  4269. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4270. {"Accept-Encoding", ""}});
  4271. ASSERT_TRUE(res);
  4272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4274. EXPECT_EQ(true, res->has_header("Content-Range"));
  4275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4276. EXPECT_EQ(std::string("abcdefg"), res->body);
  4277. }
  4278. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4279. auto res = cli_.Get("/with-range", {
  4280. {"Range", "bytes=0-"},
  4281. {"Accept-Encoding", ""},
  4282. });
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4285. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4286. EXPECT_EQ(true, res->has_header("Content-Range"));
  4287. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4288. EXPECT_EQ(std::string("abcdefg"), res->body);
  4289. }
  4290. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4291. auto res =
  4292. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4293. ASSERT_TRUE(res);
  4294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4295. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4296. EXPECT_EQ(false, res->has_header("Content-Range"));
  4297. EXPECT_EQ(267U, res->body.size());
  4298. // Check that both range contents are present
  4299. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4300. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4301. // Check that Content-Range headers are present for both ranges
  4302. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4303. std::string::npos);
  4304. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4305. std::string::npos);
  4306. }
  4307. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4308. Ranges ranges;
  4309. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4310. ranges.emplace_back(0, -1);
  4311. }
  4312. auto res =
  4313. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4314. ASSERT_TRUE(res);
  4315. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4316. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4317. EXPECT_EQ(false, res->has_header("Content-Range"));
  4318. EXPECT_EQ(0U, res->body.size());
  4319. }
  4320. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4321. auto res =
  4322. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ(5U, res->body.size());
  4326. // Check that overlapping ranges are coalesced into a single range
  4327. EXPECT_EQ("bcdef", res->body);
  4328. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4329. // Should be single range, not multipart
  4330. EXPECT_TRUE(res->has_header("Content-Range"));
  4331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4332. }
  4333. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4334. auto res =
  4335. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4338. EXPECT_EQ(268U, res->body.size());
  4339. // Check that both range contents are present
  4340. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4341. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4342. // Check that Content-Range headers are present for both ranges
  4343. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4344. std::string::npos);
  4345. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4346. std::string::npos);
  4347. }
  4348. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4349. auto res =
  4350. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4353. EXPECT_EQ(269U, res->body.size());
  4354. // Check that both duplicate range contents are present
  4355. size_t first_abc = res->body.find("abc\r\n");
  4356. EXPECT_TRUE(first_abc != std::string::npos);
  4357. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4358. EXPECT_TRUE(second_abc != std::string::npos);
  4359. // Check that Content-Range headers are present for both ranges
  4360. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4361. EXPECT_TRUE(first_range != std::string::npos);
  4362. size_t second_range =
  4363. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4364. EXPECT_TRUE(second_range != std::string::npos);
  4365. }
  4366. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4367. auto res = cli_.Get("/streamed-with-range?error",
  4368. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4372. EXPECT_EQ(false, res->has_header("Content-Range"));
  4373. EXPECT_EQ(0U, res->body.size());
  4374. }
  4375. TEST_F(ServerTest, GetStreamedEndless) {
  4376. uint64_t offset = 0;
  4377. auto res = cli_.Get("/streamed-cancel",
  4378. [&](const char * /*data*/, uint64_t data_length) {
  4379. if (offset < 100) {
  4380. offset += data_length;
  4381. return true;
  4382. }
  4383. return false;
  4384. });
  4385. ASSERT_TRUE(!res);
  4386. EXPECT_EQ(Error::Canceled, res.error());
  4387. }
  4388. TEST_F(ServerTest, ClientStop) {
  4389. std::atomic_size_t count{4};
  4390. std::vector<std::thread> threads;
  4391. for (auto i = count.load(); i != 0; --i) {
  4392. threads.emplace_back([&]() {
  4393. auto res = cli_.Get("/streamed-cancel",
  4394. [&](const char *, uint64_t) { return true; });
  4395. --count;
  4396. ASSERT_TRUE(!res);
  4397. EXPECT_TRUE(res.error() == Error::Canceled ||
  4398. res.error() == Error::Read || res.error() == Error::Write);
  4399. });
  4400. }
  4401. std::this_thread::sleep_for(std::chrono::seconds(2));
  4402. while (count != 0) {
  4403. cli_.stop();
  4404. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4405. }
  4406. for (auto &t : threads) {
  4407. t.join();
  4408. }
  4409. }
  4410. TEST_F(ServerTest, GetWithRange1) {
  4411. auto res = cli_.Get("/with-range", {
  4412. make_range_header({{3, 5}}),
  4413. {"Accept-Encoding", ""},
  4414. });
  4415. ASSERT_TRUE(res);
  4416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4417. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4418. EXPECT_EQ(true, res->has_header("Content-Range"));
  4419. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4420. EXPECT_EQ(std::string("def"), res->body);
  4421. }
  4422. TEST_F(ServerTest, GetWithRange2) {
  4423. auto res = cli_.Get("/with-range", {
  4424. make_range_header({{1, -1}}),
  4425. {"Accept-Encoding", ""},
  4426. });
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4429. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4430. EXPECT_EQ(true, res->has_header("Content-Range"));
  4431. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4432. EXPECT_EQ(std::string("bcdefg"), res->body);
  4433. }
  4434. TEST_F(ServerTest, GetWithRange3) {
  4435. auto res = cli_.Get("/with-range", {
  4436. make_range_header({{0, 0}}),
  4437. {"Accept-Encoding", ""},
  4438. });
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4441. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4442. EXPECT_EQ(true, res->has_header("Content-Range"));
  4443. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4444. EXPECT_EQ(std::string("a"), res->body);
  4445. }
  4446. TEST_F(ServerTest, GetWithRange4) {
  4447. auto res = cli_.Get("/with-range", {
  4448. make_range_header({{-1, 2}}),
  4449. {"Accept-Encoding", ""},
  4450. });
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4453. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ(true, res->has_header("Content-Range"));
  4455. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4456. EXPECT_EQ(std::string("fg"), res->body);
  4457. }
  4458. TEST_F(ServerTest, GetWithRange5) {
  4459. auto res = cli_.Get("/with-range", {
  4460. make_range_header({{0, 5}}),
  4461. {"Accept-Encoding", ""},
  4462. });
  4463. ASSERT_TRUE(res);
  4464. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4465. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4466. EXPECT_EQ(true, res->has_header("Content-Range"));
  4467. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4468. EXPECT_EQ(std::string("abcdef"), res->body);
  4469. }
  4470. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4471. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4472. ASSERT_TRUE(res);
  4473. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4474. }
  4475. TEST_F(ServerTest, GetWithRangeMultipart) {
  4476. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4477. ASSERT_TRUE(res);
  4478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4479. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4480. EXPECT_EQ(false, res->has_header("Content-Range"));
  4481. EXPECT_EQ(267U, res->body.size());
  4482. }
  4483. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4484. auto res =
  4485. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4488. }
  4489. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4490. auto res = cli_.Get("/with-range-customized-response",
  4491. {{make_range_header({{1, 2}})}});
  4492. ASSERT_TRUE(res);
  4493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4494. EXPECT_EQ(true, res->has_header("Content-Length"));
  4495. EXPECT_EQ(false, res->has_header("Content-Range"));
  4496. EXPECT_EQ(JSON_DATA, res->body);
  4497. }
  4498. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4499. auto res = cli_.Get("/with-range-customized-response",
  4500. {{make_range_header({{1, 2}, {4, 5}})}});
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4503. EXPECT_EQ(true, res->has_header("Content-Length"));
  4504. EXPECT_EQ(false, res->has_header("Content-Range"));
  4505. EXPECT_EQ(JSON_DATA, res->body);
  4506. }
  4507. TEST_F(ServerTest, Issue1772) {
  4508. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4511. }
  4512. TEST_F(ServerTest, Issue609) {
  4513. auto res = cli_.Delete("/issue609");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ(std::string("ok"), res->body);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedChunked) {
  4519. auto res = cli_.Get("/streamed-chunked");
  4520. ASSERT_TRUE(res);
  4521. EXPECT_EQ(StatusCode::OK_200, res->status);
  4522. EXPECT_EQ(std::string("123456789"), res->body);
  4523. }
  4524. TEST_F(ServerTest, GetStreamedChunked2) {
  4525. auto res = cli_.Get("/streamed-chunked2");
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. EXPECT_EQ(std::string("123456789"), res->body);
  4529. }
  4530. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4531. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. EXPECT_EQ(std::string("123456789"), res->body);
  4535. EXPECT_TRUE(res->has_header("Trailer"));
  4536. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4537. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4538. // Trailers are now stored separately from headers (security fix)
  4539. EXPECT_EQ(2U, res->trailers.size());
  4540. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4541. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4542. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4543. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4544. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4545. // Verify trailers are NOT in headers (security verification)
  4546. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4547. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4548. }
  4549. TEST_F(ServerTest, LargeChunkedPost) {
  4550. Request req;
  4551. req.method = "POST";
  4552. req.path = "/large-chunked";
  4553. std::string host_and_port;
  4554. host_and_port += HOST;
  4555. host_and_port += ":";
  4556. host_and_port += std::to_string(PORT);
  4557. req.headers.emplace("Host", host_and_port.c_str());
  4558. req.headers.emplace("Accept", "*/*");
  4559. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4560. req.headers.emplace("Content-Type", "text/plain");
  4561. req.headers.emplace("Content-Length", "0");
  4562. req.headers.emplace("Transfer-Encoding", "chunked");
  4563. std::string long_string(30 * 1024u, 'a');
  4564. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4565. // Attempt to make a large enough post to exceed OS buffers, to test that
  4566. // the server handles short reads if the full chunk data isn't available.
  4567. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4568. auto res = std::make_shared<Response>();
  4569. auto error = Error::Success;
  4570. auto ret = cli_.send(req, *res, error);
  4571. ASSERT_TRUE(ret);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. }
  4574. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4575. auto res = cli_.Get("/remote_addr");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4579. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4580. }
  4581. TEST_F(ServerTest, GetMethodLocalAddr) {
  4582. auto res = cli_.Get("/local_addr");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4586. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4587. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4588. }
  4589. TEST_F(ServerTest, HTTPResponseSplitting) {
  4590. auto res = cli_.Get("/http_response_splitting");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. }
  4594. TEST_F(ServerTest, SlowRequest) {
  4595. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4596. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4597. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4598. }
  4599. #if 0
  4600. TEST_F(ServerTest, SlowPost) {
  4601. char buffer[64 * 1024];
  4602. memset(buffer, 0x42, sizeof(buffer));
  4603. auto res = cli_.Post(
  4604. "/slowpost", 64 * 1024 * 1024,
  4605. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4606. auto ret = sink.write(buffer, sizeof(buffer));
  4607. EXPECT_TRUE(ret);
  4608. return true;
  4609. },
  4610. "text/plain");
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(StatusCode::OK_200, res->status);
  4613. }
  4614. TEST_F(ServerTest, SlowPostFail) {
  4615. char buffer[64 * 1024];
  4616. memset(buffer, 0x42, sizeof(buffer));
  4617. cli_.set_write_timeout(std::chrono::seconds(0));
  4618. auto res = cli_.Post(
  4619. "/slowpost", 64 * 1024 * 1024,
  4620. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4621. sink.write(buffer, sizeof(buffer));
  4622. return true;
  4623. },
  4624. "text/plain");
  4625. ASSERT_TRUE(!res);
  4626. EXPECT_EQ(Error::Write, res.error());
  4627. }
  4628. #endif
  4629. TEST_F(ServerTest, Put) {
  4630. auto res = cli_.Put("/put", "PUT", "text/plain");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("PUT", res->body);
  4634. }
  4635. TEST_F(ServerTest, PutWithContentProvider) {
  4636. auto res = cli_.Put(
  4637. "/put", 3,
  4638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4639. sink.os << "PUT";
  4640. return true;
  4641. },
  4642. "text/plain");
  4643. ASSERT_TRUE(res);
  4644. EXPECT_EQ(StatusCode::OK_200, res->status);
  4645. EXPECT_EQ("PUT", res->body);
  4646. }
  4647. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4648. auto res = cli_.Post(
  4649. "/post", 42,
  4650. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4651. return false;
  4652. },
  4653. "text/plain");
  4654. ASSERT_TRUE(!res);
  4655. EXPECT_EQ(Error::Canceled, res.error());
  4656. }
  4657. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4658. auto res = cli_.Put(
  4659. "/put",
  4660. [](size_t /*offset*/, DataSink &sink) {
  4661. sink.os << "PUT";
  4662. sink.done();
  4663. return true;
  4664. },
  4665. "text/plain");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("PUT", res->body);
  4669. }
  4670. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4671. auto res = cli_.Post(
  4672. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4673. "text/plain");
  4674. ASSERT_TRUE(!res);
  4675. EXPECT_EQ(Error::Canceled, res.error());
  4676. }
  4677. TEST_F(ServerTest, PostLoopBack) {
  4678. std::string body;
  4679. auto res = cli_.Post(
  4680. "/post-loopback", 9,
  4681. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4682. EXPECT_EQ(9u, length);
  4683. sink.write("123", 3);
  4684. sink.write("456", 3);
  4685. sink.write("789", 3);
  4686. return true;
  4687. },
  4688. "text/plain",
  4689. [&body](const char *data, size_t data_length) {
  4690. body.append(data, data_length);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(res);
  4694. EXPECT_EQ(StatusCode::OK_200, res->status);
  4695. EXPECT_EQ("123456789", body);
  4696. }
  4697. TEST_F(ServerTest, PutLoopBack) {
  4698. std::string body;
  4699. auto res = cli_.Put(
  4700. "/put-loopback", 9,
  4701. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4702. EXPECT_EQ(9u, length);
  4703. sink.write("123", 3);
  4704. sink.write("456", 3);
  4705. sink.write("789", 3);
  4706. return true;
  4707. },
  4708. "text/plain",
  4709. [&body](const char *data, size_t data_length) {
  4710. body.append(data, data_length);
  4711. return true;
  4712. });
  4713. ASSERT_TRUE(res);
  4714. EXPECT_EQ(StatusCode::OK_200, res->status);
  4715. EXPECT_EQ("123456789", body);
  4716. }
  4717. TEST_F(ServerTest, PatchLoopBack) {
  4718. std::string body;
  4719. auto res = cli_.Patch(
  4720. "/patch-loopback", 9,
  4721. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4722. EXPECT_EQ(9u, length);
  4723. sink.write("123", 3);
  4724. sink.write("456", 3);
  4725. sink.write("789", 3);
  4726. return true;
  4727. },
  4728. "text/plain",
  4729. [&body](const char *data, size_t data_length) {
  4730. body.append(data, data_length);
  4731. return true;
  4732. });
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("123456789", body);
  4736. }
  4737. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4738. std::string body;
  4739. auto res = cli_.Post(
  4740. "/post-loopback",
  4741. [](size_t /*offset*/, DataSink &sink) {
  4742. sink.write("123", 3);
  4743. sink.write("456", 3);
  4744. sink.write("789", 3);
  4745. sink.done();
  4746. return true;
  4747. },
  4748. "text/plain",
  4749. [&body](const char *data, size_t data_length) {
  4750. body.append(data, data_length);
  4751. return true;
  4752. });
  4753. ASSERT_TRUE(res);
  4754. EXPECT_EQ(StatusCode::OK_200, res->status);
  4755. EXPECT_EQ("123456789", body);
  4756. }
  4757. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4758. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4759. cli_.set_compress(true);
  4760. auto res = cli_.Put(
  4761. "/put", 3,
  4762. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4763. sink.os << "PUT";
  4764. return true;
  4765. },
  4766. "text/plain");
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. EXPECT_EQ("PUT", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4772. cli_.set_compress(true);
  4773. auto res = cli_.Post(
  4774. "/post", 42,
  4775. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4776. return false;
  4777. },
  4778. "text/plain");
  4779. ASSERT_TRUE(!res);
  4780. EXPECT_EQ(Error::Canceled, res.error());
  4781. }
  4782. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4783. cli_.set_compress(true);
  4784. auto res = cli_.Put(
  4785. "/put",
  4786. [](size_t /*offset*/, DataSink &sink) {
  4787. sink.os << "PUT";
  4788. sink.done();
  4789. return true;
  4790. },
  4791. "text/plain");
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ("PUT", res->body);
  4795. }
  4796. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4797. cli_.set_compress(true);
  4798. auto res = cli_.Post(
  4799. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4800. "text/plain");
  4801. ASSERT_TRUE(!res);
  4802. EXPECT_EQ(Error::Canceled, res.error());
  4803. }
  4804. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4805. cli_.set_compress(true);
  4806. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ(LARGE_DATA, res->body);
  4810. }
  4811. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4812. #ifdef CPPHTTPLIB_SSL_ENABLED
  4813. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4814. Client cli(s.c_str());
  4815. cli.enable_server_certificate_verification(false);
  4816. #else
  4817. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4818. Client cli(s.c_str());
  4819. #endif
  4820. cli.set_compress(true);
  4821. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4822. ASSERT_TRUE(res);
  4823. EXPECT_EQ(StatusCode::OK_200, res->status);
  4824. EXPECT_EQ(LARGE_DATA, res->body);
  4825. // The compressed size should be less than a 10th of the original. May vary
  4826. // depending on the zlib library.
  4827. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4828. static_cast<uint64_t>(10 * 1024 * 1024));
  4829. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4830. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4831. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4832. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4833. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4834. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4835. #endif
  4836. }
  4837. TEST_F(ServerTest, PutContentWithDeflate) {
  4838. cli_.set_compress(false);
  4839. Headers headers;
  4840. headers.emplace("Content-Encoding", "deflate");
  4841. // PUT in deflate format:
  4842. auto res = cli_.Put("/put", headers,
  4843. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("PUT", res->body);
  4847. }
  4848. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4849. Headers headers;
  4850. headers.emplace("Accept-Encoding", "gzip, deflate");
  4851. auto res = cli_.Get("/streamed-chunked", headers);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ(std::string("123456789"), res->body);
  4855. }
  4856. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4857. Headers headers;
  4858. headers.emplace("Accept-Encoding", "gzip, deflate");
  4859. auto res = cli_.Get("/streamed-chunked2", headers);
  4860. ASSERT_TRUE(res);
  4861. EXPECT_EQ(StatusCode::OK_200, res->status);
  4862. EXPECT_EQ(std::string("123456789"), res->body);
  4863. }
  4864. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4865. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::OK_200, res->status);
  4868. }
  4869. TEST(GzipDecompressor, ChunkedDecompression) {
  4870. std::string data;
  4871. for (size_t i = 0; i < 32 * 1024; ++i) {
  4872. data.push_back(static_cast<char>('a' + i % 26));
  4873. }
  4874. std::string compressed_data;
  4875. {
  4876. httplib::detail::gzip_compressor compressor;
  4877. bool result = compressor.compress(
  4878. data.data(), data.size(),
  4879. /*last=*/true,
  4880. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4881. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4882. compressed_data_size);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(result);
  4886. }
  4887. std::string decompressed_data;
  4888. {
  4889. httplib::detail::gzip_decompressor decompressor;
  4890. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4891. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4892. size_t chunk_size = 130;
  4893. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4894. chunk_begin += chunk_size) {
  4895. size_t current_chunk_size =
  4896. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4897. bool result = decompressor.decompress(
  4898. compressed_data.data() + chunk_begin, current_chunk_size,
  4899. [&](const char *decompressed_data_chunk,
  4900. size_t decompressed_data_chunk_size) {
  4901. decompressed_data.insert(decompressed_data.size(),
  4902. decompressed_data_chunk,
  4903. decompressed_data_chunk_size);
  4904. return true;
  4905. });
  4906. ASSERT_TRUE(result);
  4907. }
  4908. }
  4909. ASSERT_EQ(data, decompressed_data);
  4910. }
  4911. TEST(GzipDecompressor, DeflateDecompression) {
  4912. std::string original_text = "Raw deflate without gzip";
  4913. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4914. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4915. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4916. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4917. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4918. std::string decompressed_data;
  4919. {
  4920. httplib::detail::gzip_decompressor decompressor;
  4921. bool result = decompressor.decompress(
  4922. compressed_data.data(), compressed_data.size(),
  4923. [&](const char *decompressed_data_chunk,
  4924. size_t decompressed_data_chunk_size) {
  4925. decompressed_data.insert(decompressed_data.size(),
  4926. decompressed_data_chunk,
  4927. decompressed_data_chunk_size);
  4928. return true;
  4929. });
  4930. ASSERT_TRUE(result);
  4931. }
  4932. ASSERT_EQ(original_text, decompressed_data);
  4933. }
  4934. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4935. std::string original_text = "Raw deflate without gzip";
  4936. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4937. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4938. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4939. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4940. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4941. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4942. std::string decompressed_data;
  4943. {
  4944. httplib::detail::gzip_decompressor decompressor;
  4945. bool result = decompressor.decompress(
  4946. compressed_data.data(), compressed_data.size(),
  4947. [&](const char *decompressed_data_chunk,
  4948. size_t decompressed_data_chunk_size) {
  4949. decompressed_data.insert(decompressed_data.size(),
  4950. decompressed_data_chunk,
  4951. decompressed_data_chunk_size);
  4952. return true;
  4953. });
  4954. ASSERT_TRUE(result);
  4955. }
  4956. ASSERT_EQ(original_text, decompressed_data);
  4957. }
  4958. #endif
  4959. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4960. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4961. Headers headers;
  4962. headers.emplace("Accept-Encoding", "br");
  4963. auto res = cli_.Get("/streamed-chunked", headers);
  4964. ASSERT_TRUE(res);
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ(std::string("123456789"), res->body);
  4967. }
  4968. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4969. Headers headers;
  4970. headers.emplace("Accept-Encoding", "br");
  4971. auto res = cli_.Get("/streamed-chunked2", headers);
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ(StatusCode::OK_200, res->status);
  4974. EXPECT_EQ(std::string("123456789"), res->body);
  4975. }
  4976. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4977. cli_.set_compress(true);
  4978. auto res = cli_.Put(
  4979. "/put", 3,
  4980. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4981. sink.os << "PUT";
  4982. return true;
  4983. },
  4984. "text/plain");
  4985. ASSERT_TRUE(res);
  4986. EXPECT_EQ(StatusCode::OK_200, res->status);
  4987. EXPECT_EQ("PUT", res->body);
  4988. }
  4989. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4990. cli_.set_compress(true);
  4991. auto res = cli_.Put(
  4992. "/put",
  4993. [](size_t /*offset*/, DataSink &sink) {
  4994. sink.os << "PUT";
  4995. sink.done();
  4996. return true;
  4997. },
  4998. "text/plain");
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::OK_200, res->status);
  5001. EXPECT_EQ("PUT", res->body);
  5002. }
  5003. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5004. cli_.set_compress(true);
  5005. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. EXPECT_EQ(LARGE_DATA, res->body);
  5009. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5010. }
  5011. #endif
  5012. TEST_F(ServerTest, Patch) {
  5013. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::OK_200, res->status);
  5016. EXPECT_EQ("PATCH", res->body);
  5017. }
  5018. TEST_F(ServerTest, Delete) {
  5019. auto res = cli_.Delete("/delete");
  5020. ASSERT_TRUE(res);
  5021. EXPECT_EQ(StatusCode::OK_200, res->status);
  5022. EXPECT_EQ("DELETE", res->body);
  5023. }
  5024. TEST_F(ServerTest, DeleteContentReceiver) {
  5025. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("content", res->body);
  5029. }
  5030. TEST_F(ServerTest, Options) {
  5031. auto res = cli_.Options("*");
  5032. ASSERT_TRUE(res);
  5033. EXPECT_EQ(StatusCode::OK_200, res->status);
  5034. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5035. EXPECT_TRUE(res->body.empty());
  5036. }
  5037. TEST_F(ServerTest, URL) {
  5038. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. }
  5042. TEST_F(ServerTest, ArrayParam) {
  5043. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5044. ASSERT_TRUE(res);
  5045. EXPECT_EQ(StatusCode::OK_200, res->status);
  5046. }
  5047. TEST_F(ServerTest, NoMultipleHeaders) {
  5048. Headers headers = {{"Content-Length", "5"}};
  5049. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5050. "text/plain");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. }
  5054. TEST_F(ServerTest, PostContentReceiver) {
  5055. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5056. ASSERT_TRUE(res);
  5057. ASSERT_EQ(StatusCode::OK_200, res->status);
  5058. ASSERT_EQ("content", res->body);
  5059. }
  5060. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5061. UploadFormDataItems items = {
  5062. {"text1", "text default", "", ""},
  5063. {"text2", "aωb", "", ""},
  5064. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5065. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5066. {"file3", "", "", "application/octet-stream"},
  5067. };
  5068. auto res = cli_.Post("/content_receiver", items);
  5069. ASSERT_TRUE(res);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5073. UploadFormDataItems items = {
  5074. {"text1", "text default", "", ""},
  5075. {"text2", "aωb", "", ""},
  5076. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5077. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5078. {"file3", "", "", "application/octet-stream"},
  5079. };
  5080. auto boundary = std::string("+++++");
  5081. std::string body;
  5082. for (const auto &item : items) {
  5083. body += "--" + boundary + "\r\n";
  5084. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5085. if (!item.filename.empty()) {
  5086. body += "; filename=\"" + item.filename + "\"";
  5087. }
  5088. body += "\r\n";
  5089. if (!item.content_type.empty()) {
  5090. body += "Content-Type: " + item.content_type + "\r\n";
  5091. }
  5092. body += "\r\n";
  5093. body += item.content + "\r\n";
  5094. }
  5095. body += "--" + boundary + "--\r\n";
  5096. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5097. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. }
  5101. TEST_F(ServerTest, PostContentReceiverGzip) {
  5102. cli_.set_compress(true);
  5103. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5104. ASSERT_TRUE(res);
  5105. ASSERT_EQ(StatusCode::OK_200, res->status);
  5106. ASSERT_EQ("content", res->body);
  5107. }
  5108. TEST_F(ServerTest, PutContentReceiver) {
  5109. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. ASSERT_EQ(StatusCode::OK_200, res->status);
  5112. ASSERT_EQ("content", res->body);
  5113. }
  5114. TEST_F(ServerTest, PatchContentReceiver) {
  5115. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5116. ASSERT_TRUE(res);
  5117. ASSERT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ("content", res->body);
  5119. }
  5120. template <typename ClientType>
  5121. void TestWithHeadersAndContentReceiver(
  5122. ClientType &cli,
  5123. std::function<Result(ClientType &, const std::string &, const Headers &,
  5124. const std::string &, const std::string &,
  5125. ContentReceiver, DownloadProgress)>
  5126. request_func) {
  5127. Headers headers;
  5128. headers.emplace("X-Custom-Header", "test-value");
  5129. std::string received_body;
  5130. auto res = request_func(
  5131. cli, "/content_receiver", headers, "content", "application/json",
  5132. [&](const char *data, size_t data_length) {
  5133. received_body.append(data, data_length);
  5134. return true;
  5135. },
  5136. nullptr);
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("content", received_body);
  5140. }
  5141. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5142. #ifdef CPPHTTPLIB_SSL_ENABLED
  5143. using ClientT = SSLClient;
  5144. #else
  5145. using ClientT = Client;
  5146. #endif
  5147. TestWithHeadersAndContentReceiver<ClientT>(
  5148. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5149. const std::string &body, const std::string &content_type,
  5150. ContentReceiver receiver, DownloadProgress progress) {
  5151. return cli.Post(path, headers, body, content_type, receiver, progress);
  5152. });
  5153. }
  5154. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5155. #ifdef CPPHTTPLIB_SSL_ENABLED
  5156. using ClientT = SSLClient;
  5157. #else
  5158. using ClientT = Client;
  5159. #endif
  5160. TestWithHeadersAndContentReceiver<ClientT>(
  5161. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5162. const std::string &body, const std::string &content_type,
  5163. ContentReceiver receiver, DownloadProgress progress) {
  5164. return cli.Put(path, headers, body, content_type, receiver, progress);
  5165. });
  5166. }
  5167. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5168. #ifdef CPPHTTPLIB_SSL_ENABLED
  5169. using ClientT = SSLClient;
  5170. #else
  5171. using ClientT = Client;
  5172. #endif
  5173. TestWithHeadersAndContentReceiver<ClientT>(
  5174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5175. const std::string &body, const std::string &content_type,
  5176. ContentReceiver receiver, DownloadProgress progress) {
  5177. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5178. });
  5179. }
  5180. template <typename ClientType>
  5181. void TestWithHeadersAndContentReceiverWithProgress(
  5182. ClientType &cli,
  5183. std::function<Result(ClientType &, const std::string &, const Headers &,
  5184. const std::string &, const std::string &,
  5185. ContentReceiver, DownloadProgress)>
  5186. request_func) {
  5187. Headers headers;
  5188. headers.emplace("X-Test-Header", "progress-test");
  5189. std::string received_body;
  5190. auto progress_called = false;
  5191. auto res = request_func(
  5192. cli, "/content_receiver", headers, "content", "text/plain",
  5193. [&](const char *data, size_t data_length) {
  5194. received_body.append(data, data_length);
  5195. return true;
  5196. },
  5197. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5198. progress_called = true;
  5199. return true;
  5200. });
  5201. ASSERT_TRUE(res);
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. EXPECT_EQ("content", received_body);
  5204. EXPECT_TRUE(progress_called);
  5205. }
  5206. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. using ClientT = SSLClient;
  5209. #else
  5210. using ClientT = Client;
  5211. #endif
  5212. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5213. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5214. const std::string &body, const std::string &content_type,
  5215. ContentReceiver receiver, DownloadProgress progress) {
  5216. return cli.Post(path, headers, body, content_type, receiver, progress);
  5217. });
  5218. }
  5219. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver, DownloadProgress progress) {
  5229. return cli.Put(path, headers, body, content_type, receiver, progress);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver, DownloadProgress progress) {
  5242. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5243. });
  5244. }
  5245. template <typename ClientType>
  5246. void TestWithHeadersAndContentReceiverError(
  5247. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5248. const Headers &, const std::string &,
  5249. const std::string &, ContentReceiver)>
  5250. request_func) {
  5251. Headers headers;
  5252. headers.emplace("X-Error-Test", "true");
  5253. std::string received_body;
  5254. auto receiver_failed = false;
  5255. auto res =
  5256. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5257. [&](const char *data, size_t data_length) {
  5258. received_body.append(data, data_length);
  5259. receiver_failed = true;
  5260. return false;
  5261. });
  5262. ASSERT_FALSE(res);
  5263. EXPECT_TRUE(receiver_failed);
  5264. }
  5265. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5266. #ifdef CPPHTTPLIB_SSL_ENABLED
  5267. using ClientT = SSLClient;
  5268. #else
  5269. using ClientT = Client;
  5270. #endif
  5271. TestWithHeadersAndContentReceiverError<ClientT>(
  5272. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5273. const std::string &body, const std::string &content_type,
  5274. ContentReceiver receiver) {
  5275. return cli.Post(path, headers, body, content_type, receiver);
  5276. });
  5277. }
  5278. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5279. #ifdef CPPHTTPLIB_SSL_ENABLED
  5280. using ClientT = SSLClient;
  5281. #else
  5282. using ClientT = Client;
  5283. #endif
  5284. TestWithHeadersAndContentReceiverError<ClientT>(
  5285. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5286. const std::string &body, const std::string &content_type,
  5287. ContentReceiver receiver) {
  5288. return cli.Put(path, headers, body, content_type, receiver);
  5289. });
  5290. }
  5291. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5292. #ifdef CPPHTTPLIB_SSL_ENABLED
  5293. using ClientT = SSLClient;
  5294. #else
  5295. using ClientT = Client;
  5296. #endif
  5297. TestWithHeadersAndContentReceiverError<ClientT>(
  5298. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5299. const std::string &body, const std::string &content_type,
  5300. ContentReceiver receiver) {
  5301. return cli.Patch(path, headers, body, content_type, receiver);
  5302. });
  5303. }
  5304. TEST_F(ServerTest, PostQueryStringAndBody) {
  5305. auto res =
  5306. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5307. ASSERT_TRUE(res);
  5308. ASSERT_EQ(StatusCode::OK_200, res->status);
  5309. }
  5310. TEST_F(ServerTest, HTTP2Magic) {
  5311. Request req;
  5312. req.method = "PRI";
  5313. req.path = "*";
  5314. req.body = "SM";
  5315. auto res = std::make_shared<Response>();
  5316. auto error = Error::Success;
  5317. auto ret = cli_.send(req, *res, error);
  5318. ASSERT_TRUE(ret);
  5319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5320. }
  5321. TEST_F(ServerTest, KeepAlive) {
  5322. auto res = cli_.Get("/hi");
  5323. ASSERT_TRUE(res);
  5324. EXPECT_EQ(StatusCode::OK_200, res->status);
  5325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5326. EXPECT_EQ("Hello World!", res->body);
  5327. res = cli_.Get("/hi");
  5328. ASSERT_TRUE(res);
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5331. EXPECT_EQ("Hello World!", res->body);
  5332. res = cli_.Get("/hi");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5336. EXPECT_EQ("Hello World!", res->body);
  5337. res = cli_.Get("/not-exist");
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5340. res = cli_.Post("/empty", "", "text/plain");
  5341. ASSERT_TRUE(res);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5344. EXPECT_EQ("empty", res->body);
  5345. EXPECT_EQ("close", res->get_header_value("Connection"));
  5346. res = cli_.Post(
  5347. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5348. "text/plain");
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5352. EXPECT_EQ("empty", res->body);
  5353. cli_.set_keep_alive(false);
  5354. res = cli_.Get("/last-request");
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. EXPECT_EQ("close", res->get_header_value("Connection"));
  5358. }
  5359. TEST_F(ServerTest, TooManyRedirect) {
  5360. cli_.set_follow_location(true);
  5361. auto res = cli_.Get("/redirect/0");
  5362. ASSERT_TRUE(!res);
  5363. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5364. }
  5365. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5366. Request req;
  5367. req.method = "FOOBAR";
  5368. req.path = "/hi";
  5369. cli_.set_keep_alive(true);
  5370. auto res = cli_.send(req);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5373. EXPECT_EQ("close", res->get_header_value("Connection"));
  5374. EXPECT_FALSE(cli_.is_socket_open());
  5375. }
  5376. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5377. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5378. TEST_F(ServerTest, Gzip) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "gzip, deflate");
  5381. auto res = cli_.Get("/compress", headers);
  5382. ASSERT_TRUE(res);
  5383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5385. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5387. "7890123456789012345678901234567890",
  5388. res->body);
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5392. Headers headers;
  5393. headers.emplace("Accept-Encoding", "gzip, deflate");
  5394. auto res = cli_.Get("/compress-with-charset", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("application/json; charset=utf-8",
  5398. res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. res->body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5405. Headers headers;
  5406. headers.emplace("Accept-Encoding", "");
  5407. auto res = cli_.Get("/compress", headers);
  5408. ASSERT_TRUE(res);
  5409. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5411. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5413. "7890123456789012345678901234567890",
  5414. res->body);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithContentReceiver) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "gzip, deflate");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. cli_.set_decompress(false);
  5440. auto res = cli_.Get("/compress", headers);
  5441. ASSERT_TRUE(res);
  5442. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5444. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5445. EXPECT_EQ(33U, res->body.size());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. }
  5448. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5449. Headers headers;
  5450. headers.emplace("Accept-Encoding", "");
  5451. std::string body;
  5452. auto res = cli_.Get("/compress", headers,
  5453. [&](const char *data, uint64_t data_length) {
  5454. EXPECT_EQ(100U, data_length);
  5455. body.append(data, data_length);
  5456. return true;
  5457. });
  5458. ASSERT_TRUE(res);
  5459. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5461. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5463. "7890123456789012345678901234567890",
  5464. body);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. }
  5467. TEST_F(ServerTest, NoGzip) {
  5468. Headers headers;
  5469. headers.emplace("Accept-Encoding", "gzip, deflate");
  5470. auto res = cli_.Get("/nocompress", headers);
  5471. ASSERT_TRUE(res);
  5472. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5473. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5474. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5475. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5476. "7890123456789012345678901234567890",
  5477. res->body);
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. }
  5480. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip, deflate");
  5483. std::string body;
  5484. auto res = cli_.Get("/nocompress", headers,
  5485. [&](const char *data, uint64_t data_length) {
  5486. EXPECT_EQ(100U, data_length);
  5487. body.append(data, data_length);
  5488. return true;
  5489. });
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5492. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5493. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5494. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5495. "7890123456789012345678901234567890",
  5496. body);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. }
  5499. TEST_F(ServerTest, MultipartFormDataGzip) {
  5500. UploadFormDataItems items = {
  5501. {"key1", "test", "", ""},
  5502. {"key2", "--abcdefg123", "", ""},
  5503. };
  5504. cli_.set_compress(true);
  5505. auto res = cli_.Post("/compress-multipart", items);
  5506. ASSERT_TRUE(res);
  5507. EXPECT_EQ(StatusCode::OK_200, res->status);
  5508. }
  5509. #endif
  5510. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5511. TEST_F(ServerTest, Brotli) {
  5512. Headers headers;
  5513. headers.emplace("Accept-Encoding", "br");
  5514. auto res = cli_.Get("/compress", headers);
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5518. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5519. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5520. "7890123456789012345678901234567890",
  5521. res->body);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. }
  5524. #endif
  5525. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5526. TEST_F(ServerTest, Zstd) {
  5527. Headers headers;
  5528. headers.emplace("Accept-Encoding", "zstd");
  5529. auto res = cli_.Get("/compress", headers);
  5530. ASSERT_TRUE(res);
  5531. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5533. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5534. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5535. "7890123456789012345678901234567890",
  5536. res->body);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. }
  5539. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5540. Headers headers;
  5541. headers.emplace("Accept-Encoding", "");
  5542. auto res = cli_.Get("/compress", headers);
  5543. ASSERT_TRUE(res);
  5544. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5548. "7890123456789012345678901234567890",
  5549. res->body);
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. }
  5552. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5553. Headers headers;
  5554. headers.emplace("Accept-Encoding", "zstd");
  5555. std::string body;
  5556. auto res = cli_.Get("/compress", headers,
  5557. [&](const char *data, uint64_t data_length) {
  5558. EXPECT_EQ(100U, data_length);
  5559. body.append(data, data_length);
  5560. return true;
  5561. });
  5562. ASSERT_TRUE(res);
  5563. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5565. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5566. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5567. "7890123456789012345678901234567890",
  5568. body);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. }
  5571. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5572. Headers headers;
  5573. headers.emplace("Accept-Encoding", "zstd");
  5574. cli_.set_decompress(false);
  5575. auto res = cli_.Get("/compress", headers);
  5576. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5577. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5578. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5579. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5580. ASSERT_TRUE(res);
  5581. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5583. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(26U, res->body.size());
  5586. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5587. 0);
  5588. }
  5589. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5590. Headers headers;
  5591. headers.emplace("Accept-Encoding", "");
  5592. std::string body;
  5593. auto res = cli_.Get("/compress", headers,
  5594. [&](const char *data, uint64_t data_length) {
  5595. EXPECT_EQ(100U, data_length);
  5596. body.append(data, data_length);
  5597. return true;
  5598. });
  5599. ASSERT_TRUE(res);
  5600. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5604. "7890123456789012345678901234567890",
  5605. body);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. }
  5608. TEST_F(ServerTest, NoZstd) {
  5609. Headers headers;
  5610. headers.emplace("Accept-Encoding", "zstd");
  5611. auto res = cli_.Get("/nocompress", headers);
  5612. ASSERT_TRUE(res);
  5613. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5614. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5617. "7890123456789012345678901234567890",
  5618. res->body);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5622. Headers headers;
  5623. headers.emplace("Accept-Encoding", "zstd");
  5624. std::string body;
  5625. auto res = cli_.Get("/nocompress", headers,
  5626. [&](const char *data, uint64_t data_length) {
  5627. EXPECT_EQ(100U, data_length);
  5628. body.append(data, data_length);
  5629. return true;
  5630. });
  5631. ASSERT_TRUE(res);
  5632. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5633. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5636. "7890123456789012345678901234567890",
  5637. body);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. }
  5640. // TODO: How to enable zstd ??
  5641. TEST_F(ServerTest, MultipartFormDataZstd) {
  5642. UploadFormDataItems items = {
  5643. {"key1", "test", "", ""},
  5644. {"key2", "--abcdefg123", "", ""},
  5645. };
  5646. Headers headers;
  5647. headers.emplace("Accept-Encoding", "zstd");
  5648. cli_.set_compress(true);
  5649. auto res = cli_.Post("/compress-multipart", headers, items);
  5650. ASSERT_TRUE(res);
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. }
  5653. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5654. Headers headers;
  5655. headers.emplace("Accept-Encoding", "zstd");
  5656. cli_.set_compress(true);
  5657. auto res = cli_.Put(
  5658. "/put", headers, 3,
  5659. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5660. sink.os << "PUT";
  5661. return true;
  5662. },
  5663. "text/plain");
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. EXPECT_EQ("PUT", res->body);
  5667. }
  5668. // Pre-compression logging tests
  5669. TEST_F(ServerTest, PreCompressionLogging) {
  5670. // Test data for compression (matches the actual /compress endpoint content)
  5671. const std::string test_content =
  5672. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5673. "3456789012345678901234567890";
  5674. // Variables to capture logging data
  5675. std::string pre_compression_body;
  5676. std::string pre_compression_content_type;
  5677. std::string pre_compression_content_encoding;
  5678. std::string post_compression_body;
  5679. std::string post_compression_content_type;
  5680. std::string post_compression_content_encoding;
  5681. // Set up pre-compression logger
  5682. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5683. const Response &res) {
  5684. pre_compression_body = res.body;
  5685. pre_compression_content_type = res.get_header_value("Content-Type");
  5686. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5687. });
  5688. // Set up post-compression logger
  5689. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5690. post_compression_body = res.body;
  5691. post_compression_content_type = res.get_header_value("Content-Type");
  5692. post_compression_content_encoding =
  5693. res.get_header_value("Content-Encoding");
  5694. });
  5695. // Test with gzip compression
  5696. Headers headers;
  5697. headers.emplace("Accept-Encoding", "gzip");
  5698. auto res = cli_.Get("/compress", headers);
  5699. // Verify response was compressed
  5700. ASSERT_TRUE(res);
  5701. EXPECT_EQ(StatusCode::OK_200, res->status);
  5702. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5703. // Verify pre-compression logger captured uncompressed content
  5704. EXPECT_EQ(test_content, pre_compression_body);
  5705. EXPECT_EQ("text/plain", pre_compression_content_type);
  5706. EXPECT_TRUE(pre_compression_content_encoding
  5707. .empty()); // No encoding header before compression
  5708. // Verify post-compression logger captured compressed content
  5709. EXPECT_NE(test_content,
  5710. post_compression_body); // Should be different after compression
  5711. EXPECT_EQ("text/plain", post_compression_content_type);
  5712. EXPECT_EQ("gzip", post_compression_content_encoding);
  5713. // Verify compressed content is smaller
  5714. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5715. }
  5716. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5717. const std::string test_content =
  5718. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5719. "3456789012345678901234567890";
  5720. std::string pre_compression_body;
  5721. std::string post_compression_body;
  5722. svr_.set_pre_compression_logger(
  5723. [&](const Request & /*req*/, const Response &res) {
  5724. pre_compression_body = res.body;
  5725. });
  5726. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5727. post_compression_body = res.body;
  5728. });
  5729. Headers headers;
  5730. headers.emplace("Accept-Encoding", "br");
  5731. auto res = cli_.Get("/compress", headers);
  5732. ASSERT_TRUE(res);
  5733. EXPECT_EQ(StatusCode::OK_200, res->status);
  5734. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5735. // Verify pre-compression content is uncompressed
  5736. EXPECT_EQ(test_content, pre_compression_body);
  5737. // Verify post-compression content is compressed
  5738. EXPECT_NE(test_content, post_compression_body);
  5739. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5740. }
  5741. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5742. const std::string test_content =
  5743. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5744. "3456789012345678901234567890";
  5745. std::string pre_compression_body;
  5746. std::string post_compression_body;
  5747. svr_.set_pre_compression_logger(
  5748. [&](const Request & /*req*/, const Response &res) {
  5749. pre_compression_body = res.body;
  5750. });
  5751. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5752. post_compression_body = res.body;
  5753. });
  5754. // Request without compression (use /nocompress endpoint)
  5755. Headers headers;
  5756. auto res = cli_.Get("/nocompress", headers);
  5757. ASSERT_TRUE(res);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5760. // Pre-compression logger should not be called when no compression is applied
  5761. EXPECT_TRUE(
  5762. pre_compression_body.empty()); // Pre-compression logger not called
  5763. EXPECT_EQ(
  5764. test_content,
  5765. post_compression_body); // Post-compression logger captures final content
  5766. }
  5767. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5768. const std::string test_content =
  5769. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5770. "3456789012345678901234567890";
  5771. std::string pre_compression_body;
  5772. bool pre_logger_called = false;
  5773. // Set only pre-compression logger
  5774. svr_.set_pre_compression_logger(
  5775. [&](const Request & /*req*/, const Response &res) {
  5776. pre_compression_body = res.body;
  5777. pre_logger_called = true;
  5778. });
  5779. Headers headers;
  5780. headers.emplace("Accept-Encoding", "gzip");
  5781. auto res = cli_.Get("/compress", headers);
  5782. ASSERT_TRUE(res);
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5785. // Verify pre-compression logger was called
  5786. EXPECT_TRUE(pre_logger_called);
  5787. EXPECT_EQ(test_content, pre_compression_body);
  5788. }
  5789. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5790. {
  5791. // Test with Expect: 100-continue header - success case
  5792. // Server returns 100 Continue, client sends body, server returns 200 OK
  5793. Request req;
  5794. req.method = "POST";
  5795. req.path = "/post-large";
  5796. req.set_header("Expect", "100-continue");
  5797. req.body = LARGE_DATA;
  5798. Response res;
  5799. auto error = Error::Success;
  5800. cli_.set_keep_alive(true);
  5801. auto ret = cli_.send(req, res, error);
  5802. EXPECT_TRUE(ret);
  5803. EXPECT_EQ(StatusCode::OK_200, res.status);
  5804. EXPECT_EQ(LARGE_DATA, res.body);
  5805. }
  5806. {
  5807. // Test with Expect: 100-continue header - error case
  5808. // Client should not send the body when server returns an error
  5809. Request req;
  5810. req.method = "POST";
  5811. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5812. req.set_header("Expect", "100-continue");
  5813. req.body = LARGE_DATA;
  5814. Response res;
  5815. auto error = Error::Success;
  5816. auto start = std::chrono::high_resolution_clock::now();
  5817. cli_.set_keep_alive(true);
  5818. auto ret = cli_.send(req, res, error);
  5819. auto end = std::chrono::high_resolution_clock::now();
  5820. auto elapsed =
  5821. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5822. .count();
  5823. // With Expect: 100-continue, request completes successfully but with error
  5824. EXPECT_TRUE(ret);
  5825. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5826. EXPECT_EQ("close", res.get_header_value("Connection"));
  5827. EXPECT_FALSE(cli_.is_socket_open());
  5828. EXPECT_LE(elapsed, 200);
  5829. }
  5830. {
  5831. // Send an extra GET request to ensure error recovery without hanging
  5832. Request req;
  5833. req.method = "GET";
  5834. req.path = "/hi";
  5835. auto start = std::chrono::high_resolution_clock::now();
  5836. auto res = cli_.send(req);
  5837. auto end = std::chrono::high_resolution_clock::now();
  5838. auto elapsed =
  5839. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5840. .count();
  5841. ASSERT_TRUE(res);
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. EXPECT_EQ("Hello World!", res->body);
  5844. EXPECT_LE(elapsed, 500);
  5845. }
  5846. }
  5847. TEST(ZstdDecompressor, ChunkedDecompression) {
  5848. std::string data;
  5849. for (size_t i = 0; i < 32 * 1024; ++i) {
  5850. data.push_back(static_cast<char>('a' + i % 26));
  5851. }
  5852. std::string compressed_data;
  5853. {
  5854. httplib::detail::zstd_compressor compressor;
  5855. bool result = compressor.compress(
  5856. data.data(), data.size(),
  5857. /*last=*/true,
  5858. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5859. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5860. compressed_data_size);
  5861. return true;
  5862. });
  5863. ASSERT_TRUE(result);
  5864. }
  5865. std::string decompressed_data;
  5866. {
  5867. httplib::detail::zstd_decompressor decompressor;
  5868. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5869. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5870. size_t chunk_size = 130;
  5871. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5872. chunk_begin += chunk_size) {
  5873. size_t current_chunk_size =
  5874. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5875. bool result = decompressor.decompress(
  5876. compressed_data.data() + chunk_begin, current_chunk_size,
  5877. [&](const char *decompressed_data_chunk,
  5878. size_t decompressed_data_chunk_size) {
  5879. decompressed_data.insert(decompressed_data.size(),
  5880. decompressed_data_chunk,
  5881. decompressed_data_chunk_size);
  5882. return true;
  5883. });
  5884. ASSERT_TRUE(result);
  5885. }
  5886. }
  5887. ASSERT_EQ(data, decompressed_data);
  5888. }
  5889. TEST(ZstdDecompressor, Decompress) {
  5890. std::string original_text = "Compressed with ZSTD";
  5891. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5892. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5893. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5894. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5895. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5896. std::string decompressed_data;
  5897. {
  5898. httplib::detail::zstd_decompressor decompressor;
  5899. bool result = decompressor.decompress(
  5900. compressed_data.data(), compressed_data.size(),
  5901. [&](const char *decompressed_data_chunk,
  5902. size_t decompressed_data_chunk_size) {
  5903. decompressed_data.insert(decompressed_data.size(),
  5904. decompressed_data_chunk,
  5905. decompressed_data_chunk_size);
  5906. return true;
  5907. });
  5908. ASSERT_TRUE(result);
  5909. }
  5910. ASSERT_EQ(original_text, decompressed_data);
  5911. }
  5912. #endif
  5913. // Sends a raw request to a server listening at HOST:PORT.
  5914. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5915. std::string *resp = nullptr) {
  5916. auto error = Error::Success;
  5917. auto client_sock = detail::create_client_socket(
  5918. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5919. /*connection_timeout_sec=*/5, 0,
  5920. /*read_timeout_sec=*/5, 0,
  5921. /*write_timeout_sec=*/5, 0, std::string(), error);
  5922. if (client_sock == INVALID_SOCKET) { return false; }
  5923. auto ret = detail::process_client_socket(
  5924. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5925. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5926. if (req.size() !=
  5927. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5928. return false;
  5929. }
  5930. char buf[512];
  5931. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5932. while (line_reader.getline()) {
  5933. if (resp) { *resp += line_reader.ptr(); }
  5934. }
  5935. return true;
  5936. });
  5937. detail::close_socket(client_sock);
  5938. return ret;
  5939. }
  5940. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5941. Server svr;
  5942. std::string header_value;
  5943. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5944. header_value = req.get_header_value("foo");
  5945. res.set_content("ok", "text/plain");
  5946. });
  5947. thread t = thread([&] { svr.listen(HOST, PORT); });
  5948. auto se = detail::scope_exit([&] {
  5949. svr.stop();
  5950. t.join();
  5951. ASSERT_FALSE(svr.is_running());
  5952. });
  5953. svr.wait_until_ready();
  5954. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5955. // like characters are not treated the same - use vertical tab and escape.
  5956. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5957. "foo: \t \v bar \x1B\t \r\n"
  5958. "Connection: close\r\n"
  5959. "\r\n";
  5960. std::string res;
  5961. ASSERT_TRUE(send_request(5, req, &res));
  5962. EXPECT_EQ(header_value, "");
  5963. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5964. }
  5965. // Sends a raw request and verifies that there isn't a crash or exception.
  5966. static void test_raw_request(const std::string &req,
  5967. std::string *out = nullptr) {
  5968. Server svr;
  5969. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5970. res.set_content("ok", "text/plain");
  5971. });
  5972. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5973. res.set_content("ok", "text/plain");
  5974. });
  5975. svr.Get("/header_field_value_check",
  5976. [&](const Request & /*req*/, Response &res) {
  5977. res.set_content("ok", "text/plain");
  5978. });
  5979. // Server read timeout must be longer than the client read timeout for the
  5980. // bug to reproduce, probably to force the server to process a request
  5981. // without a trailing blank line.
  5982. const time_t client_read_timeout_sec = 1;
  5983. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5984. bool listen_thread_ok = false;
  5985. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5986. auto se = detail::scope_exit([&] {
  5987. svr.stop();
  5988. t.join();
  5989. ASSERT_FALSE(svr.is_running());
  5990. EXPECT_TRUE(listen_thread_ok);
  5991. });
  5992. svr.wait_until_ready();
  5993. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5994. }
  5995. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5996. // A certain header line causes an exception if the header property is parsed
  5997. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5998. test_raw_request(
  5999. "GET /hi HTTP/1.1\r\n"
  6000. " : "
  6001. " "
  6002. " ");
  6003. }
  6004. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6005. // A certain header line causes an exception if the header property *name* is
  6006. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6007. // greedy matcher and requires backtracking when there are a lot of ":"
  6008. // characters.
  6009. // This occurs with libc++ but not libstdc++.
  6010. test_raw_request(
  6011. "GET /hi HTTP/1.1\r\n"
  6012. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6013. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6014. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6015. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6016. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6017. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6018. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6019. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6020. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6021. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6022. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6023. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6024. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6025. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6026. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6027. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6028. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6029. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6030. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6031. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6032. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6033. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6034. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6035. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6036. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6037. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6038. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6039. "&&&%%%");
  6040. }
  6041. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6042. // Make sure this doesn't crash the server.
  6043. // In a previous version of the header line regex, the "\r" rendered the line
  6044. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6045. // a new position where the leading white space ended and the field value
  6046. // began.
  6047. // The crash occurs with libc++ but not libstdc++.
  6048. test_raw_request("GET /hi HTTP/1.1\r\n"
  6049. "a:" +
  6050. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6051. "\r\n"
  6052. "\r\n");
  6053. }
  6054. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6055. std::string out;
  6056. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6057. "Content-Type: text/plain\r\n"
  6058. "Transfer-Encoding: chunked\r\n"
  6059. "\r\n"
  6060. "nothex\r\n",
  6061. &out);
  6062. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6063. }
  6064. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6065. std::string out;
  6066. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6067. "Content-Type: text/plain\r\n"
  6068. "Transfer-Encoding: chunked\r\n"
  6069. "\r\n"
  6070. "3\r\n"
  6071. "xyz\r\n"
  6072. "NaN\r\n",
  6073. &out);
  6074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6075. }
  6076. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6077. std::string out;
  6078. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6079. "Content-Type: text/plain\r\n"
  6080. "Transfer-Encoding: chunked\r\n"
  6081. "\r\n"
  6082. // Length is too large for 64 bits.
  6083. "1ffffffffffffffff\r\n"
  6084. "xyz\r\n",
  6085. &out);
  6086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6087. }
  6088. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6089. test_raw_request("GET /hi HTTP/1.1\r\n"
  6090. "Content-Type: text/plain\r\n\r");
  6091. }
  6092. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6093. std::string out;
  6094. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6095. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6096. }
  6097. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6098. Server svr;
  6099. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6100. EXPECT_TRUE(!req.remote_addr.empty());
  6101. });
  6102. thread t = thread([&] { svr.listen(HOST, PORT); });
  6103. auto se = detail::scope_exit([&] {
  6104. svr.stop();
  6105. t.join();
  6106. ASSERT_FALSE(svr.is_running());
  6107. });
  6108. svr.wait_until_ready();
  6109. // Send an invalid request line to trigger Bad Request
  6110. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6111. std::string out;
  6112. ASSERT_TRUE(send_request(5, bad_req, &out));
  6113. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6114. }
  6115. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6116. std::string out;
  6117. std::string request(
  6118. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6119. test_raw_request(request, &out);
  6120. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6121. }
  6122. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6123. std::string out;
  6124. std::string request(
  6125. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6126. test_raw_request(request, &out);
  6127. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6128. }
  6129. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6130. std::string out;
  6131. std::string request(
  6132. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6133. test_raw_request(request, &out);
  6134. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6135. }
  6136. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6137. std::string out;
  6138. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6139. "Test: \r\n\r\n",
  6140. &out);
  6141. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6142. }
  6143. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6144. Server svr;
  6145. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6146. res.set_header("Cache-Control", "no-cache");
  6147. res.set_chunked_content_provider(
  6148. "text/event-stream", [](size_t offset, DataSink &sink) {
  6149. std::string s = "data:";
  6150. s += std::to_string(offset);
  6151. s += "\n\n";
  6152. auto ret = sink.write(s.data(), s.size());
  6153. EXPECT_TRUE(ret);
  6154. std::this_thread::sleep_for(std::chrono::seconds(1));
  6155. return true;
  6156. });
  6157. });
  6158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6159. svr.wait_until_ready();
  6160. Client client(HOST, PORT);
  6161. const Headers headers = {{"Accept", "text/event-stream"}};
  6162. auto get_thread = std::thread([&client, &headers]() {
  6163. auto res = client.Get(
  6164. "/events", headers,
  6165. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6166. });
  6167. auto se = detail::scope_exit([&] {
  6168. svr.stop();
  6169. get_thread.join();
  6170. listen_thread.join();
  6171. ASSERT_FALSE(svr.is_running());
  6172. });
  6173. // Give GET time to get a few messages.
  6174. std::this_thread::sleep_for(std::chrono::seconds(2));
  6175. }
  6176. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6177. httplib::Server svr;
  6178. svr.Post("/hi",
  6179. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6180. res.status = StatusCode::OK_200;
  6181. });
  6182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6183. svr.wait_until_ready();
  6184. Client cli(HOST, PORT);
  6185. auto res = cli.Post("/hi", "data", "text/plain");
  6186. ASSERT_TRUE(res);
  6187. EXPECT_EQ(StatusCode::OK_200, res->status);
  6188. svr.stop();
  6189. thread.join();
  6190. ASSERT_FALSE(svr.is_running());
  6191. res = cli.Post("/hi", "data", "text/plain");
  6192. ASSERT_FALSE(res);
  6193. }
  6194. TEST(ServerStopTest, ListenFailure) {
  6195. Server svr;
  6196. auto t = thread([&]() {
  6197. auto ret = svr.listen("????", PORT);
  6198. EXPECT_FALSE(ret);
  6199. });
  6200. svr.wait_until_ready();
  6201. svr.stop();
  6202. t.join();
  6203. }
  6204. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6205. TEST(ServerStopTest, Decommision) {
  6206. Server svr;
  6207. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6208. for (int i = 0; i < 4; i++) {
  6209. auto is_even = !(i % 2);
  6210. std::thread t{[&] {
  6211. try {
  6212. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6213. if (is_even) {
  6214. throw std::runtime_error("Some thing that happens to go wrong.");
  6215. }
  6216. svr.listen(HOST, PORT);
  6217. } catch (...) { svr.decommission(); }
  6218. }};
  6219. svr.wait_until_ready();
  6220. // Server is up
  6221. {
  6222. Client cli(HOST, PORT);
  6223. auto res = cli.Get("/hi");
  6224. if (is_even) {
  6225. EXPECT_FALSE(res);
  6226. } else {
  6227. EXPECT_TRUE(res);
  6228. EXPECT_EQ("hi...", res->body);
  6229. }
  6230. }
  6231. svr.stop();
  6232. t.join();
  6233. // Server is down...
  6234. {
  6235. Client cli(HOST, PORT);
  6236. auto res = cli.Get("/hi");
  6237. EXPECT_FALSE(res);
  6238. }
  6239. }
  6240. }
  6241. #endif
  6242. // Helper function for string body upload progress tests
  6243. template <typename SetupHandler, typename ClientCall>
  6244. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6245. ClientCall &&client_call,
  6246. const string &body) {
  6247. Server svr;
  6248. setup_handler(svr);
  6249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6250. auto se = detail::scope_exit([&] {
  6251. svr.stop();
  6252. t.join();
  6253. });
  6254. svr.wait_until_ready();
  6255. Client cli(HOST, PORT);
  6256. vector<uint64_t> progress_values;
  6257. bool progress_called = false;
  6258. auto res =
  6259. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6260. progress_values.push_back(current);
  6261. progress_called = true;
  6262. return true;
  6263. });
  6264. ASSERT_TRUE(res);
  6265. EXPECT_EQ(200, res->status);
  6266. EXPECT_TRUE(progress_called);
  6267. }
  6268. TEST(UploadProgressTest, PostStringBodyBasic) {
  6269. TestStringBodyUploadProgress(
  6270. [](Server &svr) {
  6271. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6272. res.set_content("received", "text/plain");
  6273. });
  6274. },
  6275. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6276. return cli.Post("/test", body, "text/plain", progress_callback);
  6277. },
  6278. "test data for upload progress");
  6279. }
  6280. TEST(UploadProgressTest, PutStringBodyBasic) {
  6281. TestStringBodyUploadProgress(
  6282. [](Server &svr) {
  6283. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6284. res.set_content("put received", "text/plain");
  6285. });
  6286. },
  6287. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6288. return cli.Put("/test", body, "text/plain", progress_callback);
  6289. },
  6290. "put test data for upload progress");
  6291. }
  6292. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6293. TestStringBodyUploadProgress(
  6294. [](Server &svr) {
  6295. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6296. res.set_content("patch received", "text/plain");
  6297. });
  6298. },
  6299. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6300. return cli.Patch("/test", body, "text/plain", progress_callback);
  6301. },
  6302. "patch test data for upload progress");
  6303. }
  6304. // Helper function for content provider upload progress tests
  6305. template <typename SetupHandler, typename ClientCall>
  6306. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6307. ClientCall &&client_call) {
  6308. Server svr;
  6309. setup_handler(svr);
  6310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6311. auto se = detail::scope_exit([&] {
  6312. svr.stop();
  6313. t.join();
  6314. });
  6315. svr.wait_until_ready();
  6316. Client cli(HOST, PORT);
  6317. vector<uint64_t> progress_values;
  6318. auto res =
  6319. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6320. progress_values.push_back(current);
  6321. return true;
  6322. });
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(200, res->status);
  6325. EXPECT_FALSE(progress_values.empty());
  6326. }
  6327. TEST(UploadProgressTest, PostContentProviderProgress) {
  6328. TestContentProviderUploadProgress(
  6329. [](Server &svr) {
  6330. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6331. res.set_content("provider received", "text/plain");
  6332. });
  6333. },
  6334. [](Client &cli, UploadProgress progress_callback) {
  6335. return cli.Post(
  6336. "/test", 10,
  6337. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6338. sink.os << "test data";
  6339. return true;
  6340. },
  6341. "text/plain", progress_callback);
  6342. });
  6343. }
  6344. // Helper function for multipart upload progress tests
  6345. template <typename SetupHandler, typename ClientCall>
  6346. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6347. ClientCall &&client_call,
  6348. const string &endpoint) {
  6349. Server svr;
  6350. setup_handler(svr);
  6351. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6352. auto se = detail::scope_exit([&] {
  6353. svr.stop();
  6354. t.join();
  6355. });
  6356. svr.wait_until_ready();
  6357. Client cli(HOST, PORT);
  6358. vector<uint64_t> progress_values;
  6359. UploadFormDataItems items = {
  6360. {"field1", "value1", "", ""},
  6361. {"field2", "longer value for progress tracking test", "", ""},
  6362. {"file1", "file content data for upload progress", "test.txt",
  6363. "text/plain"}};
  6364. auto res = client_call(cli, endpoint, items,
  6365. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6366. progress_values.push_back(current);
  6367. return true;
  6368. });
  6369. ASSERT_TRUE(res);
  6370. EXPECT_EQ(200, res->status);
  6371. EXPECT_FALSE(progress_values.empty());
  6372. }
  6373. TEST(UploadProgressTest, PostMultipartProgress) {
  6374. TestMultipartUploadProgress(
  6375. [](Server &svr) {
  6376. svr.Post("/multipart", [](const Request &req, Response &res) {
  6377. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6378. res.set_content("multipart received", "text/plain");
  6379. });
  6380. },
  6381. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6382. UploadProgress progress_callback) {
  6383. return cli.Post(endpoint, items, progress_callback);
  6384. },
  6385. "/multipart");
  6386. }
  6387. // Helper function for basic download progress tests
  6388. template <typename SetupHandler, typename ClientCall>
  6389. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6390. ClientCall &&client_call, const string &endpoint,
  6391. size_t expected_content_size) {
  6392. Server svr;
  6393. setup_handler(svr);
  6394. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6395. auto se = detail::scope_exit([&] {
  6396. svr.stop();
  6397. t.join();
  6398. });
  6399. svr.wait_until_ready();
  6400. Client cli(HOST, PORT);
  6401. vector<uint64_t> progress_values;
  6402. auto res = client_call(cli, endpoint,
  6403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6404. progress_values.push_back(current);
  6405. return true;
  6406. });
  6407. ASSERT_TRUE(res);
  6408. EXPECT_EQ(200, res->status);
  6409. EXPECT_FALSE(progress_values.empty());
  6410. EXPECT_EQ(expected_content_size, res->body.size());
  6411. }
  6412. TEST(DownloadProgressTest, GetBasic) {
  6413. TestBasicDownloadProgress(
  6414. [](Server &svr) {
  6415. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6416. string content(1000, 'D');
  6417. res.set_content(content, "text/plain");
  6418. });
  6419. },
  6420. [](Client &cli, const string &endpoint,
  6421. DownloadProgress progress_callback) {
  6422. return cli.Get(endpoint, progress_callback);
  6423. },
  6424. "/download", 1000u);
  6425. }
  6426. // Helper function for content receiver download progress tests
  6427. template <typename SetupHandler, typename ClientCall>
  6428. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6429. ClientCall &&client_call,
  6430. const string &endpoint,
  6431. size_t expected_content_size) {
  6432. Server svr;
  6433. setup_handler(svr);
  6434. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6435. auto se = detail::scope_exit([&] {
  6436. svr.stop();
  6437. t.join();
  6438. });
  6439. svr.wait_until_ready();
  6440. Client cli(HOST, PORT);
  6441. vector<uint64_t> progress_values;
  6442. string received_body;
  6443. auto res = client_call(
  6444. cli, endpoint,
  6445. [&](const char *data, size_t data_length) -> bool {
  6446. received_body.append(data, data_length);
  6447. return true;
  6448. },
  6449. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6450. progress_values.push_back(current);
  6451. return true;
  6452. });
  6453. ASSERT_TRUE(res);
  6454. EXPECT_EQ(200, res->status);
  6455. EXPECT_FALSE(progress_values.empty());
  6456. EXPECT_EQ(expected_content_size, received_body.size());
  6457. EXPECT_TRUE(res->body.empty());
  6458. }
  6459. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6460. TestContentReceiverDownloadProgress(
  6461. [](Server &svr) {
  6462. svr.Get("/download-receiver",
  6463. [](const Request & /*req*/, Response &res) {
  6464. string content(2000, 'R');
  6465. res.set_content(content, "text/plain");
  6466. });
  6467. },
  6468. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6469. DownloadProgress progress_callback) {
  6470. return cli.Get(endpoint, content_receiver, progress_callback);
  6471. },
  6472. "/download-receiver", 2000u);
  6473. }
  6474. TEST(StreamingTest, NoContentLengthStreaming) {
  6475. Server svr;
  6476. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6477. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6478. if (offset < 6) {
  6479. sink.os << (offset < 3 ? "a" : "b");
  6480. } else {
  6481. sink.done();
  6482. }
  6483. return true;
  6484. });
  6485. });
  6486. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6487. auto listen_se = detail::scope_exit([&] {
  6488. svr.stop();
  6489. listen_thread.join();
  6490. ASSERT_FALSE(svr.is_running());
  6491. });
  6492. svr.wait_until_ready();
  6493. Client client(HOST, PORT);
  6494. auto get_thread = std::thread([&client]() {
  6495. std::string s;
  6496. auto res =
  6497. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6498. s += std::string(data, len);
  6499. return true;
  6500. });
  6501. ASSERT_TRUE(res);
  6502. EXPECT_EQ(StatusCode::OK_200, res->status);
  6503. EXPECT_EQ("aaabbb", s);
  6504. });
  6505. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6506. // Give GET time to get a few messages.
  6507. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6508. }
  6509. TEST(MountTest, Unmount) {
  6510. Server svr;
  6511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6512. auto se = detail::scope_exit([&] {
  6513. svr.stop();
  6514. listen_thread.join();
  6515. ASSERT_FALSE(svr.is_running());
  6516. });
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. svr.set_mount_point("/mount2", "./www2");
  6520. auto res = cli.Get("/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. res = cli.Get("/mount2/dir/test.html");
  6524. ASSERT_TRUE(res);
  6525. EXPECT_EQ(StatusCode::OK_200, res->status);
  6526. svr.set_mount_point("/", "./www");
  6527. res = cli.Get("/dir/");
  6528. ASSERT_TRUE(res);
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. svr.remove_mount_point("/");
  6531. res = cli.Get("/dir/");
  6532. ASSERT_TRUE(res);
  6533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6534. svr.remove_mount_point("/mount2");
  6535. res = cli.Get("/mount2/dir/test.html");
  6536. ASSERT_TRUE(res);
  6537. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6538. }
  6539. TEST(MountTest, Redicect) {
  6540. Server svr;
  6541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.set_mount_point("/", "./www");
  6548. svr.wait_until_ready();
  6549. Client cli("localhost", PORT);
  6550. auto res = cli.Get("/dir/");
  6551. ASSERT_TRUE(res);
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. res = cli.Get("/dir");
  6554. ASSERT_TRUE(res);
  6555. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6556. res = cli.Get("/file");
  6557. ASSERT_TRUE(res);
  6558. EXPECT_EQ(StatusCode::OK_200, res->status);
  6559. res = cli.Get("/file/");
  6560. ASSERT_TRUE(res);
  6561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6562. cli.set_follow_location(true);
  6563. res = cli.Get("/dir");
  6564. ASSERT_TRUE(res);
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. }
  6567. TEST(MountTest, MultibytesPathName) {
  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.set_mount_point("/", "./www");
  6576. svr.wait_until_ready();
  6577. Client cli("localhost", PORT);
  6578. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6579. ASSERT_TRUE(res);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6582. }
  6583. TEST(KeepAliveTest, ReadTimeout) {
  6584. Server svr;
  6585. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6586. std::this_thread::sleep_for(std::chrono::seconds(2));
  6587. res.set_content("a", "text/plain");
  6588. });
  6589. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6590. res.set_content("b", "text/plain");
  6591. });
  6592. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6593. auto se = detail::scope_exit([&] {
  6594. svr.stop();
  6595. listen_thread.join();
  6596. ASSERT_FALSE(svr.is_running());
  6597. });
  6598. svr.wait_until_ready();
  6599. Client cli("localhost", PORT);
  6600. cli.set_keep_alive(true);
  6601. cli.set_read_timeout(std::chrono::seconds(1));
  6602. auto resa = cli.Get("/a");
  6603. ASSERT_FALSE(resa);
  6604. EXPECT_EQ(Error::Read, resa.error());
  6605. auto resb = cli.Get("/b");
  6606. ASSERT_TRUE(resb);
  6607. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6608. EXPECT_EQ("b", resb->body);
  6609. }
  6610. TEST(KeepAliveTest, MaxCount) {
  6611. size_t keep_alive_max_count = 3;
  6612. Server svr;
  6613. svr.set_keep_alive_max_count(keep_alive_max_count);
  6614. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6615. res.set_content("Hello World!", "text/plain");
  6616. });
  6617. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6618. auto se = detail::scope_exit([&] {
  6619. svr.stop();
  6620. listen_thread.join();
  6621. ASSERT_FALSE(svr.is_running());
  6622. });
  6623. svr.wait_until_ready();
  6624. Client cli(HOST, PORT);
  6625. cli.set_keep_alive(true);
  6626. for (size_t i = 0; i < 5; i++) {
  6627. auto result = cli.Get("/hi");
  6628. ASSERT_TRUE(result);
  6629. EXPECT_EQ(StatusCode::OK_200, result->status);
  6630. if (i == keep_alive_max_count - 1) {
  6631. EXPECT_EQ("close", result->get_header_value("Connection"));
  6632. } else {
  6633. EXPECT_FALSE(result->has_header("Connection"));
  6634. }
  6635. }
  6636. }
  6637. TEST(KeepAliveTest, Issue1041) {
  6638. Server svr;
  6639. svr.set_keep_alive_timeout(3);
  6640. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6641. res.set_content("Hello World!", "text/plain");
  6642. });
  6643. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6644. auto se = detail::scope_exit([&] {
  6645. svr.stop();
  6646. listen_thread.join();
  6647. ASSERT_FALSE(svr.is_running());
  6648. });
  6649. svr.wait_until_ready();
  6650. Client cli(HOST, PORT);
  6651. cli.set_keep_alive(true);
  6652. auto result = cli.Get("/hi");
  6653. ASSERT_TRUE(result);
  6654. EXPECT_EQ(StatusCode::OK_200, result->status);
  6655. std::this_thread::sleep_for(std::chrono::seconds(5));
  6656. result = cli.Get("/hi");
  6657. ASSERT_TRUE(result);
  6658. EXPECT_EQ(StatusCode::OK_200, result->status);
  6659. }
  6660. TEST(KeepAliveTest, Issue1959) {
  6661. Server svr;
  6662. svr.set_keep_alive_timeout(5);
  6663. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6664. res.set_content("a", "text/plain");
  6665. });
  6666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6667. auto se = detail::scope_exit([&] {
  6668. if (!svr.is_running()) return;
  6669. svr.stop();
  6670. listen_thread.join();
  6671. ASSERT_FALSE(svr.is_running());
  6672. });
  6673. svr.wait_until_ready();
  6674. Client cli("localhost", PORT);
  6675. cli.set_keep_alive(true);
  6676. using namespace std::chrono;
  6677. auto start = steady_clock::now();
  6678. cli.Get("/a");
  6679. svr.stop();
  6680. listen_thread.join();
  6681. auto end = steady_clock::now();
  6682. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6683. EXPECT_LT(elapsed, 5000);
  6684. }
  6685. #ifdef CPPHTTPLIB_SSL_ENABLED
  6686. TEST(KeepAliveTest, SSLClientReconnection) {
  6687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6688. ASSERT_TRUE(svr.is_valid());
  6689. svr.set_keep_alive_timeout(1);
  6690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6691. res.set_content("Hello World!", "text/plain");
  6692. });
  6693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6694. auto se = detail::scope_exit([&] {
  6695. svr.stop();
  6696. listen_thread.join();
  6697. ASSERT_FALSE(svr.is_running());
  6698. });
  6699. svr.wait_until_ready();
  6700. SSLClient cli(HOST, PORT);
  6701. cli.enable_server_certificate_verification(false);
  6702. cli.set_keep_alive(true);
  6703. auto result = cli.Get("/hi");
  6704. ASSERT_TRUE(result);
  6705. EXPECT_EQ(StatusCode::OK_200, result->status);
  6706. result = cli.Get("/hi");
  6707. ASSERT_TRUE(result);
  6708. EXPECT_EQ(StatusCode::OK_200, result->status);
  6709. std::this_thread::sleep_for(std::chrono::seconds(2));
  6710. // Recoonect
  6711. result = cli.Get("/hi");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(StatusCode::OK_200, result->status);
  6714. result = cli.Get("/hi");
  6715. ASSERT_TRUE(result);
  6716. EXPECT_EQ(StatusCode::OK_200, result->status);
  6717. }
  6718. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6720. ASSERT_TRUE(svr.is_valid());
  6721. svr.set_keep_alive_timeout(1);
  6722. std::string content = "reconnect";
  6723. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6724. res.set_content("Hello World!", "text/plain");
  6725. });
  6726. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6727. auto se = detail::scope_exit([&] {
  6728. svr.stop();
  6729. listen_thread.join();
  6730. ASSERT_FALSE(svr.is_running());
  6731. });
  6732. svr.wait_until_ready();
  6733. SSLClient cli(HOST, PORT);
  6734. cli.enable_server_certificate_verification(false);
  6735. cli.set_keep_alive(true);
  6736. auto result = cli.Post(
  6737. "/hi", content.size(),
  6738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6739. sink.write(content.c_str(), content.size());
  6740. return true;
  6741. },
  6742. "text/plain");
  6743. ASSERT_TRUE(result);
  6744. EXPECT_EQ(200, result->status);
  6745. std::this_thread::sleep_for(std::chrono::seconds(2));
  6746. // Recoonect
  6747. result = cli.Post(
  6748. "/hi", content.size(),
  6749. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6750. sink.write(content.c_str(), content.size());
  6751. return true;
  6752. },
  6753. "text/plain");
  6754. ASSERT_TRUE(result);
  6755. EXPECT_EQ(200, result->status);
  6756. result = cli.Post(
  6757. "/hi", content.size(),
  6758. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6759. sink.write(content.c_str(), content.size());
  6760. return true;
  6761. },
  6762. "text/plain");
  6763. ASSERT_TRUE(result);
  6764. EXPECT_EQ(200, result->status);
  6765. }
  6766. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6767. using namespace httplib::tls;
  6768. {
  6769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6770. ASSERT_TRUE(svr.is_valid());
  6771. svr.Get("/sni", [&](const Request &req, Response &res) {
  6772. std::string expected = req.sni();
  6773. EXPECT_EQ(expected, req.get_param_value("expected"));
  6774. res.set_content("ok", "text/plain");
  6775. });
  6776. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6777. auto se = detail::scope_exit([&] {
  6778. svr.stop();
  6779. listen_thread.join();
  6780. ASSERT_FALSE(svr.is_running());
  6781. });
  6782. svr.wait_until_ready();
  6783. {
  6784. SSLClient cli("localhost", PORT);
  6785. cli.enable_server_certificate_verification(false);
  6786. auto res = cli.Get("/sni?expected=localhost");
  6787. ASSERT_TRUE(res);
  6788. }
  6789. {
  6790. SSLClient cli("::1", PORT);
  6791. cli.enable_server_certificate_verification(false);
  6792. auto res = cli.Get("/sni?expected=");
  6793. // NOTE: This may fail if the server is listening on IPv4 only
  6794. // (e.g., when localhost resolves to 127.0.0.1 only)
  6795. if (res) {
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. } else {
  6798. EXPECT_EQ(Error::Connection, res.error());
  6799. }
  6800. }
  6801. }
  6802. }
  6803. #endif
  6804. TEST(ClientProblemDetectionTest, ContentProvider) {
  6805. Server svr;
  6806. size_t content_length = 1024 * 1024;
  6807. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content_provider(
  6809. content_length, "text/plain",
  6810. [&](size_t offset, size_t length, DataSink &sink) {
  6811. auto out_len = std::min(length, static_cast<size_t>(1024));
  6812. std::string out(out_len, '@');
  6813. sink.write(out.data(), out_len);
  6814. return offset < 4096;
  6815. },
  6816. [](bool success) { ASSERT_FALSE(success); });
  6817. });
  6818. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6819. res.set_content_provider(
  6820. 0, "text/plain",
  6821. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6822. EXPECT_TRUE(false);
  6823. return true;
  6824. },
  6825. [](bool success) { ASSERT_FALSE(success); });
  6826. });
  6827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6828. auto se = detail::scope_exit([&] {
  6829. svr.stop();
  6830. listen_thread.join();
  6831. ASSERT_FALSE(svr.is_running());
  6832. });
  6833. svr.wait_until_ready();
  6834. Client cli("localhost", PORT);
  6835. {
  6836. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6837. size_t /*data_length*/) { return false; });
  6838. ASSERT_FALSE(res);
  6839. }
  6840. {
  6841. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6842. size_t /*data_length*/) { return false; });
  6843. ASSERT_TRUE(res);
  6844. }
  6845. }
  6846. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6847. Server svr;
  6848. svr.set_error_handler([](Request const &, Response &res) -> void {
  6849. res.set_chunked_content_provider(
  6850. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6851. sink.os << "hello";
  6852. sink.os << "world";
  6853. sink.done();
  6854. return true;
  6855. });
  6856. });
  6857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6858. auto se = detail::scope_exit([&] {
  6859. svr.stop();
  6860. listen_thread.join();
  6861. ASSERT_FALSE(svr.is_running());
  6862. });
  6863. svr.wait_until_ready();
  6864. Client cli("localhost", PORT);
  6865. auto res = cli.Get("/");
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6868. EXPECT_EQ("helloworld", res->body);
  6869. }
  6870. TEST(LongPollingTest, ClientCloseDetection) {
  6871. Server svr;
  6872. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6873. res.set_chunked_content_provider(
  6874. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6875. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6876. sink.os << "hello";
  6877. auto count = 10;
  6878. while (count > 0 && sink.is_writable()) {
  6879. this_thread::sleep_for(chrono::milliseconds(10));
  6880. count--;
  6881. }
  6882. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6883. return true;
  6884. });
  6885. });
  6886. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6887. auto se = detail::scope_exit([&] {
  6888. svr.stop();
  6889. listen_thread.join();
  6890. ASSERT_FALSE(svr.is_running());
  6891. });
  6892. svr.wait_until_ready();
  6893. Client cli("localhost", PORT);
  6894. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6895. EXPECT_EQ("hello", string(data, data_length));
  6896. return false; // close the socket immediately.
  6897. });
  6898. ASSERT_FALSE(res);
  6899. }
  6900. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6901. Server svr;
  6902. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6903. res.set_chunked_content_provider(
  6904. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6905. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6906. sink.os << "hello";
  6907. EXPECT_TRUE(sink.os.good());
  6908. // Wait for the client to close the connection
  6909. auto count = 10;
  6910. while (count > 0 && sink.is_writable()) {
  6911. this_thread::sleep_for(chrono::milliseconds(10));
  6912. count--;
  6913. }
  6914. // After client disconnect, write repeatedly until the socket
  6915. // write actually fails (small writes may be absorbed by the
  6916. // kernel buffer)
  6917. std::string chunk(1024, 'x');
  6918. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6919. sink.os << chunk;
  6920. }
  6921. EXPECT_TRUE(sink.os.fail());
  6922. return true;
  6923. });
  6924. });
  6925. auto port = svr.bind_to_any_port("localhost");
  6926. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6927. auto se = detail::scope_exit([&] {
  6928. svr.stop();
  6929. listen_thread.join();
  6930. ASSERT_FALSE(svr.is_running());
  6931. });
  6932. svr.wait_until_ready();
  6933. Client cli("localhost", port);
  6934. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6935. EXPECT_EQ("hello", string(data, data_length));
  6936. return false; // close the socket immediately.
  6937. });
  6938. ASSERT_FALSE(res);
  6939. }
  6940. TEST(GetWithParametersTest, GetWithParameters) {
  6941. Server svr;
  6942. svr.Get("/", [&](const Request &req, Response &) {
  6943. EXPECT_EQ("world", req.get_param_value("hello"));
  6944. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6945. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6946. });
  6947. svr.Get("/params", [&](const Request &req, Response &) {
  6948. EXPECT_EQ("world", req.get_param_value("hello"));
  6949. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6950. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6951. });
  6952. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6953. EXPECT_EQ("resource-id", req.matches[1]);
  6954. EXPECT_EQ("foo", req.get_param_value("param1"));
  6955. EXPECT_EQ("bar", req.get_param_value("param2"));
  6956. });
  6957. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6958. EXPECT_EQ("user-id", req.path_params.at("id"));
  6959. EXPECT_EQ("foo", req.get_param_value("param1"));
  6960. EXPECT_EQ("bar", req.get_param_value("param2"));
  6961. });
  6962. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6963. auto se = detail::scope_exit([&] {
  6964. svr.stop();
  6965. listen_thread.join();
  6966. ASSERT_FALSE(svr.is_running());
  6967. });
  6968. svr.wait_until_ready();
  6969. {
  6970. Client cli(HOST, PORT);
  6971. Params params;
  6972. params.emplace("hello", "world");
  6973. params.emplace("hello2", "world2");
  6974. params.emplace("hello3", "world3");
  6975. auto res = cli.Get("/", params, Headers{});
  6976. ASSERT_TRUE(res);
  6977. EXPECT_EQ(StatusCode::OK_200, res->status);
  6978. }
  6979. {
  6980. Client cli(HOST, PORT);
  6981. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6982. ASSERT_TRUE(res);
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. {
  6986. Client cli(HOST, PORT);
  6987. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6988. ASSERT_TRUE(res);
  6989. EXPECT_EQ(StatusCode::OK_200, res->status);
  6990. }
  6991. {
  6992. Client cli(HOST, PORT);
  6993. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6994. ASSERT_TRUE(res);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. }
  6998. TEST(GetWithParametersTest, GetWithParameters2) {
  6999. Server svr;
  7000. svr.Get("/", [&](const Request &req, Response &res) {
  7001. auto text = req.get_param_value("hello");
  7002. res.set_content(text, "text/plain");
  7003. });
  7004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7005. auto se = detail::scope_exit([&] {
  7006. svr.stop();
  7007. listen_thread.join();
  7008. ASSERT_FALSE(svr.is_running());
  7009. });
  7010. svr.wait_until_ready();
  7011. Client cli("localhost", PORT);
  7012. Params params;
  7013. params.emplace("hello", "world");
  7014. std::string body;
  7015. auto res = cli.Get("/", params, Headers{},
  7016. [&](const char *data, size_t data_length) {
  7017. body.append(data, data_length);
  7018. return true;
  7019. });
  7020. ASSERT_TRUE(res);
  7021. EXPECT_EQ(StatusCode::OK_200, res->status);
  7022. EXPECT_EQ("world", body);
  7023. }
  7024. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7025. auto host = "httpbingo.org";
  7026. auto path = std::string{"/range/32"};
  7027. #ifdef CPPHTTPLIB_SSL_ENABLED
  7028. SSLClient cli(host);
  7029. #else
  7030. Client cli(host);
  7031. #endif
  7032. cli.set_default_headers({make_range_header({{1, 10}})});
  7033. cli.set_connection_timeout(5);
  7034. {
  7035. auto res = cli.Get(path);
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ("bcdefghijk", res->body);
  7038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7039. }
  7040. {
  7041. auto res = cli.Get(path);
  7042. ASSERT_TRUE(res);
  7043. EXPECT_EQ("bcdefghijk", res->body);
  7044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7045. }
  7046. }
  7047. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7048. Server svr;
  7049. svr.set_default_headers({{"Hello", "World"}});
  7050. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7051. res.set_content("ok", "text/plain");
  7052. });
  7053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7054. auto se = detail::scope_exit([&] {
  7055. svr.stop();
  7056. listen_thread.join();
  7057. ASSERT_FALSE(svr.is_running());
  7058. });
  7059. svr.wait_until_ready();
  7060. Client cli("localhost", PORT);
  7061. auto res = cli.Get("/");
  7062. ASSERT_TRUE(res);
  7063. EXPECT_EQ(StatusCode::OK_200, res->status);
  7064. EXPECT_EQ("ok", res->body);
  7065. EXPECT_EQ("World", res->get_header_value("Hello"));
  7066. }
  7067. #ifdef CPPHTTPLIB_SSL_ENABLED
  7068. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7070. ASSERT_TRUE(svr.is_valid());
  7071. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7072. std::this_thread::sleep_for(std::chrono::seconds(2));
  7073. res.set_content("a", "text/plain");
  7074. });
  7075. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7076. res.set_content("b", "text/plain");
  7077. });
  7078. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7079. auto se = detail::scope_exit([&] {
  7080. svr.stop();
  7081. listen_thread.join();
  7082. ASSERT_FALSE(svr.is_running());
  7083. });
  7084. svr.wait_until_ready();
  7085. SSLClient cli("localhost", PORT);
  7086. cli.enable_server_certificate_verification(false);
  7087. cli.set_keep_alive(true);
  7088. cli.set_read_timeout(std::chrono::seconds(1));
  7089. auto resa = cli.Get("/a");
  7090. ASSERT_TRUE(!resa);
  7091. EXPECT_EQ(Error::Read, resa.error());
  7092. auto resb = cli.Get("/b");
  7093. ASSERT_TRUE(resb);
  7094. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7095. EXPECT_EQ("b", resb->body);
  7096. }
  7097. #endif
  7098. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7099. protected:
  7100. ServerTestWithAI_PASSIVE()
  7101. : cli_(HOST, PORT)
  7102. #ifdef CPPHTTPLIB_SSL_ENABLED
  7103. ,
  7104. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7105. #endif
  7106. {
  7107. #ifdef CPPHTTPLIB_SSL_ENABLED
  7108. cli_.enable_server_certificate_verification(false);
  7109. #endif
  7110. }
  7111. virtual void SetUp() {
  7112. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7113. res.set_content("Hello World!", "text/plain");
  7114. });
  7115. t_ = thread(
  7116. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7117. svr_.wait_until_ready();
  7118. }
  7119. virtual void TearDown() {
  7120. svr_.stop();
  7121. t_.join();
  7122. }
  7123. #ifdef CPPHTTPLIB_SSL_ENABLED
  7124. SSLClient cli_;
  7125. SSLServer svr_;
  7126. #else
  7127. Client cli_;
  7128. Server svr_;
  7129. #endif
  7130. thread t_;
  7131. };
  7132. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7133. auto res = cli_.Get("/hi");
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7137. EXPECT_EQ("Hello World!", res->body);
  7138. }
  7139. class ServerUpDownTest : public ::testing::Test {
  7140. protected:
  7141. ServerUpDownTest() : cli_(HOST, PORT) {}
  7142. virtual void SetUp() {
  7143. t_ = thread([&]() {
  7144. svr_.bind_to_any_port(HOST);
  7145. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7146. ASSERT_TRUE(svr_.listen_after_bind());
  7147. });
  7148. svr_.wait_until_ready();
  7149. }
  7150. virtual void TearDown() {
  7151. svr_.stop();
  7152. t_.join();
  7153. }
  7154. Client cli_;
  7155. Server svr_;
  7156. thread t_;
  7157. };
  7158. TEST_F(ServerUpDownTest, QuickStartStop) {
  7159. // Should not crash, especially when run with
  7160. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7161. }
  7162. class PayloadMaxLengthTest : public ::testing::Test {
  7163. protected:
  7164. PayloadMaxLengthTest()
  7165. : cli_(HOST, PORT)
  7166. #ifdef CPPHTTPLIB_SSL_ENABLED
  7167. ,
  7168. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7169. #endif
  7170. {
  7171. #ifdef CPPHTTPLIB_SSL_ENABLED
  7172. cli_.enable_server_certificate_verification(false);
  7173. #endif
  7174. }
  7175. virtual void SetUp() {
  7176. svr_.set_payload_max_length(8);
  7177. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7178. res.set_content("test", "text/plain");
  7179. });
  7180. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7181. svr_.wait_until_ready();
  7182. }
  7183. virtual void TearDown() {
  7184. svr_.stop();
  7185. t_.join();
  7186. }
  7187. #ifdef CPPHTTPLIB_SSL_ENABLED
  7188. SSLClient cli_;
  7189. SSLServer svr_;
  7190. #else
  7191. Client cli_;
  7192. Server svr_;
  7193. #endif
  7194. thread t_;
  7195. };
  7196. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7197. auto res = cli_.Post("/test", "123456789", "text/plain");
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7200. res = cli_.Post("/test", "12345678", "text/plain");
  7201. ASSERT_TRUE(res);
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. }
  7204. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7205. // Test chunked encoding with payload exceeding the 8-byte limit
  7206. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7207. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7208. ASSERT_TRUE(res);
  7209. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7210. }
  7211. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7212. // Test chunked encoding with payload within the 8-byte limit
  7213. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7214. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7215. ASSERT_TRUE(res);
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7219. // Test using send_request to send chunked data exceeding payload limit
  7220. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7221. "Host: " +
  7222. std::string(HOST) + ":" + std::to_string(PORT) +
  7223. "\r\n"
  7224. "Transfer-Encoding: chunked\r\n"
  7225. "Connection: close\r\n"
  7226. "\r\n"
  7227. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7228. "0123456789\r\n"
  7229. "0\r\n" // End chunk
  7230. "\r\n";
  7231. std::string response;
  7232. bool result = send_request(1, chunked_request, &response);
  7233. if (!result) {
  7234. // If send_request fails, it might be because the server closed the
  7235. // connection due to payload limit enforcement, which is acceptable
  7236. SUCCEED()
  7237. << "Server rejected oversized chunked request (connection closed)";
  7238. } else {
  7239. // If we got a response, check if it's an error response or connection was
  7240. // closed early Short response length indicates connection was closed due to
  7241. // payload limit
  7242. if (response.length() <= 10) {
  7243. SUCCEED() << "Server closed connection for oversized chunked request";
  7244. } else {
  7245. // Check for error status codes
  7246. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7247. response.find("Payload Too Large") != std::string::npos ||
  7248. response.find("400") != std::string::npos);
  7249. }
  7250. }
  7251. }
  7252. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7253. // Test request without Content-Length header exceeding payload limit
  7254. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7255. "Host: " +
  7256. std::string(HOST) + ":" +
  7257. std::to_string(PORT) +
  7258. "\r\n"
  7259. "Connection: close\r\n"
  7260. "\r\n";
  7261. // Add payload exceeding the 8-byte limit
  7262. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7263. request_without_content_length += large_payload;
  7264. std::string response;
  7265. bool result = send_request(1, request_without_content_length, &response);
  7266. if (!result) {
  7267. // If send_request fails, server likely closed connection due to payload
  7268. // limit
  7269. SUCCEED() << "Server rejected oversized request without Content-Length "
  7270. "(connection closed)";
  7271. } else {
  7272. // Check if server responded with error or closed connection early
  7273. if (response.length() <= 10) {
  7274. SUCCEED() << "Server closed connection for oversized request without "
  7275. "Content-Length";
  7276. } else {
  7277. // Check for error status codes
  7278. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7279. response.find("Payload Too Large") != std::string::npos ||
  7280. response.find("400") != std::string::npos);
  7281. }
  7282. }
  7283. }
  7284. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7285. // Test request without Content-Length header within payload limit
  7286. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7287. "Host: " +
  7288. std::string(HOST) + ":" +
  7289. std::to_string(PORT) +
  7290. "\r\n"
  7291. "Connection: close\r\n"
  7292. "\r\n";
  7293. // Add payload within the 8-byte limit
  7294. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7295. request_without_content_length += small_payload;
  7296. std::string response;
  7297. bool result = send_request(1, request_without_content_length, &response);
  7298. // For requests without Content-Length, the server may have different behavior
  7299. // The key is that it should not reject due to payload limit for small
  7300. // payloads
  7301. if (result) {
  7302. // Check for any HTTP response (success or error, but not connection closed)
  7303. if (response.length() > 10) {
  7304. SUCCEED()
  7305. << "Server processed request without Content-Length within limit";
  7306. } else {
  7307. // Short response might indicate connection closed, which is acceptable
  7308. SUCCEED() << "Server closed connection for request without "
  7309. "Content-Length (acceptable behavior)";
  7310. }
  7311. } else {
  7312. // Connection failure might be due to protocol requirements
  7313. SUCCEED() << "Connection issue with request without Content-Length "
  7314. "(environment-specific)";
  7315. }
  7316. }
  7317. class LargePayloadMaxLengthTest : public ::testing::Test {
  7318. protected:
  7319. LargePayloadMaxLengthTest()
  7320. : cli_(HOST, PORT)
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. ,
  7323. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7324. #endif
  7325. {
  7326. #ifdef CPPHTTPLIB_SSL_ENABLED
  7327. cli_.enable_server_certificate_verification(false);
  7328. #endif
  7329. }
  7330. virtual void SetUp() {
  7331. // Set 10MB payload limit
  7332. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7333. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7334. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7335. res.set_content("Large payload test", "text/plain");
  7336. });
  7337. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7338. svr_.wait_until_ready();
  7339. }
  7340. virtual void TearDown() {
  7341. svr_.stop();
  7342. t_.join();
  7343. }
  7344. #ifdef CPPHTTPLIB_SSL_ENABLED
  7345. SSLClient cli_;
  7346. SSLServer svr_;
  7347. #else
  7348. Client cli_;
  7349. Server svr_;
  7350. #endif
  7351. thread t_;
  7352. };
  7353. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7354. // Test chunked encoding with payload within 10MB limit
  7355. std::string medium_payload(5 * 1024 * 1024,
  7356. 'A'); // 5MB payload, within 10MB limit
  7357. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7358. ASSERT_TRUE(res);
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. }
  7361. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7362. // Test chunked encoding with payload exceeding 10MB limit
  7363. std::string large_payload(12 * 1024 * 1024,
  7364. 'B'); // 12MB payload, exceeds 10MB limit
  7365. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7366. // Server may either return 413 or close the connection
  7367. if (res) {
  7368. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7369. } else {
  7370. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7371. }
  7372. }
  7373. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7374. // Test request without Content-Length header within 10MB limit
  7375. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7376. "Host: " +
  7377. std::string(HOST) + ":" +
  7378. std::to_string(PORT) +
  7379. "\r\n"
  7380. "Connection: close\r\n"
  7381. "\r\n";
  7382. // Add 1MB payload (within 10MB limit)
  7383. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7384. request_without_content_length += medium_payload;
  7385. std::string response;
  7386. bool result = send_request(5, request_without_content_length, &response);
  7387. if (result) {
  7388. // Should get a proper HTTP response for payloads within limit
  7389. if (response.length() > 10) {
  7390. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7391. "10MB limit";
  7392. } else {
  7393. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7394. "Content-Length)";
  7395. }
  7396. } else {
  7397. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7398. }
  7399. }
  7400. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7401. // Test request without Content-Length header exceeding 10MB limit
  7402. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7403. "Host: " +
  7404. std::string(HOST) + ":" +
  7405. std::to_string(PORT) +
  7406. "\r\n"
  7407. "Connection: close\r\n"
  7408. "\r\n";
  7409. // Add 12MB payload (exceeds 10MB limit)
  7410. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7411. request_without_content_length += large_payload;
  7412. std::string response;
  7413. bool result = send_request(10, request_without_content_length, &response);
  7414. if (!result) {
  7415. // Server should close connection due to payload limit
  7416. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7417. "(connection closed)";
  7418. } else {
  7419. // Check for error response
  7420. if (response.length() <= 10) {
  7421. SUCCEED()
  7422. << "Server closed connection for 12MB request exceeding 10MB limit";
  7423. } else {
  7424. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7425. response.find("Payload Too Large") != std::string::npos ||
  7426. response.find("400") != std::string::npos);
  7427. }
  7428. }
  7429. }
  7430. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7431. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7432. // path.
  7433. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7434. Server svr;
  7435. const size_t LIMIT = 64 * 1024; // 64KB
  7436. svr.set_payload_max_length(LIMIT);
  7437. size_t total = 0;
  7438. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7439. const ContentReader &content_reader) {
  7440. content_reader([&](const char * /*data*/, size_t len) {
  7441. total += len;
  7442. return true;
  7443. });
  7444. res.status = 200;
  7445. res.set_content("stream_ok", "text/plain");
  7446. });
  7447. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7448. auto se = detail::scope_exit([&] {
  7449. svr.stop();
  7450. thread.join();
  7451. ASSERT_FALSE(svr.is_running());
  7452. });
  7453. svr.wait_until_ready();
  7454. // Prepare 256KB raw data and gzip-compress it
  7455. std::string raw(256 * 1024, 'A');
  7456. std::string gz;
  7457. {
  7458. z_stream zs{};
  7459. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7460. Z_DEFAULT_STRATEGY);
  7461. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7462. zs.avail_in = static_cast<uInt>(raw.size());
  7463. char outbuf[4096];
  7464. int ret;
  7465. do {
  7466. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7467. zs.avail_out = sizeof(outbuf);
  7468. ret = deflate(&zs, Z_FINISH);
  7469. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7470. } while (ret != Z_STREAM_END);
  7471. deflateEnd(&zs);
  7472. }
  7473. Client cli(HOST, PORT);
  7474. cli.set_connection_timeout(std::chrono::seconds(5));
  7475. Headers headers = {{"Content-Encoding", "gzip"}};
  7476. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7477. "application/octet-stream");
  7478. ASSERT_TRUE(res);
  7479. // Server must reject oversized decompressed payloads with 413.
  7480. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7481. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7482. EXPECT_LE(total, LIMIT);
  7483. }
  7484. #endif
  7485. // Regression test for DoS vulnerability: a malicious server sending a response
  7486. // without Content-Length header must not cause unbounded memory consumption on
  7487. // the client side. The client should stop reading after a reasonable limit,
  7488. // similar to the server-side set_payload_max_length protection.
  7489. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7490. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7491. #ifndef _WIN32
  7492. signal(SIGPIPE, SIG_IGN);
  7493. #endif
  7494. auto server_thread = std::thread([] {
  7495. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7496. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7497. default_socket_options(srv);
  7498. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7499. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7500. sockaddr_in addr{};
  7501. addr.sin_family = AF_INET;
  7502. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7504. int opt = 1;
  7505. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7506. #ifdef _WIN32
  7507. reinterpret_cast<const char *>(&opt),
  7508. #else
  7509. &opt,
  7510. #endif
  7511. sizeof(opt));
  7512. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7513. ::listen(srv, 1);
  7514. sockaddr_in cli_addr{};
  7515. socklen_t cli_len = sizeof(cli_addr);
  7516. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7517. if (cli != INVALID_SOCKET) {
  7518. char buf[4096];
  7519. ::recv(cli, buf, sizeof(buf), 0);
  7520. // Malicious response: no Content-Length, no chunked encoding
  7521. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7522. "Connection: close\r\n"
  7523. "\r\n";
  7524. ::send(cli,
  7525. #ifdef _WIN32
  7526. static_cast<const char *>(response_header.c_str()),
  7527. static_cast<int>(response_header.size()),
  7528. #else
  7529. response_header.c_str(), response_header.size(),
  7530. #endif
  7531. 0);
  7532. // Send 10MB of data
  7533. std::string chunk(64 * 1024, 'A');
  7534. size_t total_sent = 0;
  7535. while (total_sent < MALICIOUS_DATA_SIZE) {
  7536. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7537. auto sent = ::send(cli,
  7538. #ifdef _WIN32
  7539. static_cast<const char *>(chunk.c_str()),
  7540. static_cast<int>(to_send),
  7541. #else
  7542. chunk.c_str(), to_send,
  7543. #endif
  7544. 0);
  7545. if (sent <= 0) break;
  7546. total_sent += static_cast<size_t>(sent);
  7547. }
  7548. detail::close_socket(cli);
  7549. }
  7550. detail::close_socket(srv);
  7551. });
  7552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7553. size_t total_read = 0;
  7554. {
  7555. Client cli("127.0.0.1", PORT + 2);
  7556. cli.set_read_timeout(5, 0);
  7557. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7558. auto stream = cli.open_stream("GET", "/malicious");
  7559. ASSERT_TRUE(stream.is_valid());
  7560. char buffer[64 * 1024];
  7561. ssize_t n;
  7562. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7563. total_read += static_cast<size_t>(n);
  7564. }
  7565. } // StreamHandle and Client destroyed here, closing the socket
  7566. server_thread.join();
  7567. // With set_payload_max_length, the client must stop reading before consuming
  7568. // all 10MB. The read loop should be cut off at or near the configured limit.
  7569. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7570. << "Client read " << total_read << " bytes, exceeding the configured "
  7571. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7572. }
  7573. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7574. // the entire response body without truncation.
  7575. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7576. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7577. #ifndef _WIN32
  7578. signal(SIGPIPE, SIG_IGN);
  7579. #endif
  7580. auto server_thread = std::thread([] {
  7581. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7582. default_socket_options(srv);
  7583. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7584. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7585. sockaddr_in addr{};
  7586. addr.sin_family = AF_INET;
  7587. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7588. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7589. int opt = 1;
  7590. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7591. #ifdef _WIN32
  7592. reinterpret_cast<const char *>(&opt),
  7593. #else
  7594. &opt,
  7595. #endif
  7596. sizeof(opt));
  7597. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7598. ::listen(srv, 1);
  7599. sockaddr_in cli_addr{};
  7600. socklen_t cli_len = sizeof(cli_addr);
  7601. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7602. if (cli != INVALID_SOCKET) {
  7603. char buf[4096];
  7604. ::recv(cli, buf, sizeof(buf), 0);
  7605. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7606. "Connection: close\r\n"
  7607. "\r\n";
  7608. ::send(cli,
  7609. #ifdef _WIN32
  7610. static_cast<const char *>(response_header.c_str()),
  7611. static_cast<int>(response_header.size()),
  7612. #else
  7613. response_header.c_str(), response_header.size(),
  7614. #endif
  7615. 0);
  7616. std::string chunk(64 * 1024, 'A');
  7617. size_t total_sent = 0;
  7618. while (total_sent < DATA_SIZE) {
  7619. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7620. auto sent = ::send(cli,
  7621. #ifdef _WIN32
  7622. static_cast<const char *>(chunk.c_str()),
  7623. static_cast<int>(to_send),
  7624. #else
  7625. chunk.c_str(), to_send,
  7626. #endif
  7627. 0);
  7628. if (sent <= 0) break;
  7629. total_sent += static_cast<size_t>(sent);
  7630. }
  7631. #ifdef _WIN32
  7632. ::shutdown(cli, SD_SEND);
  7633. #else
  7634. ::shutdown(cli, SHUT_WR);
  7635. #endif
  7636. // Drain until the client closes its end, ensuring all data is delivered
  7637. char drain[1024];
  7638. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7639. detail::close_socket(cli);
  7640. }
  7641. detail::close_socket(srv);
  7642. });
  7643. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7644. size_t total_read = 0;
  7645. {
  7646. Client cli("127.0.0.1", PORT + 2);
  7647. cli.set_read_timeout(5, 0);
  7648. cli.set_payload_max_length(0); // 0 means no limit
  7649. auto stream = cli.open_stream("GET", "/data");
  7650. ASSERT_TRUE(stream.is_valid());
  7651. char buffer[64 * 1024];
  7652. ssize_t n;
  7653. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7654. total_read += static_cast<size_t>(n);
  7655. }
  7656. }
  7657. server_thread.join();
  7658. EXPECT_EQ(total_read, DATA_SIZE)
  7659. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7660. << " bytes without truncation, but only read " << total_read << " bytes.";
  7661. }
  7662. // Verify that content_receiver bypasses the default payload_max_length,
  7663. // allowing streaming downloads larger than 100MB without requiring an explicit
  7664. // set_payload_max_length call.
  7665. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7666. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7667. #ifndef _WIN32
  7668. signal(SIGPIPE, SIG_IGN);
  7669. #endif
  7670. auto server_thread = std::thread([] {
  7671. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7672. default_socket_options(srv);
  7673. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7674. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7675. sockaddr_in addr{};
  7676. addr.sin_family = AF_INET;
  7677. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7678. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7679. int opt = 1;
  7680. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7681. #ifdef _WIN32
  7682. reinterpret_cast<const char *>(&opt),
  7683. #else
  7684. &opt,
  7685. #endif
  7686. sizeof(opt));
  7687. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7688. ::listen(srv, 1);
  7689. sockaddr_in cli_addr{};
  7690. socklen_t cli_len = sizeof(cli_addr);
  7691. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7692. if (cli != INVALID_SOCKET) {
  7693. char buf[4096];
  7694. ::recv(cli, buf, sizeof(buf), 0);
  7695. // Response with Content-Length larger than default 100MB limit
  7696. auto content_length = std::to_string(DATA_SIZE);
  7697. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7698. "Content-Length: " +
  7699. content_length +
  7700. "\r\n"
  7701. "Connection: close\r\n"
  7702. "\r\n";
  7703. ::send(cli,
  7704. #ifdef _WIN32
  7705. static_cast<const char *>(response_header.c_str()),
  7706. static_cast<int>(response_header.size()),
  7707. #else
  7708. response_header.c_str(), response_header.size(),
  7709. #endif
  7710. 0);
  7711. std::string chunk(64 * 1024, 'A');
  7712. size_t total_sent = 0;
  7713. while (total_sent < DATA_SIZE) {
  7714. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7715. auto sent = ::send(cli,
  7716. #ifdef _WIN32
  7717. static_cast<const char *>(chunk.c_str()),
  7718. static_cast<int>(to_send),
  7719. #else
  7720. chunk.c_str(), to_send,
  7721. #endif
  7722. 0);
  7723. if (sent <= 0) break;
  7724. total_sent += static_cast<size_t>(sent);
  7725. }
  7726. detail::close_socket(cli);
  7727. }
  7728. detail::close_socket(srv);
  7729. });
  7730. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7731. size_t total_received = 0;
  7732. {
  7733. Client cli("127.0.0.1", PORT + 2);
  7734. cli.set_read_timeout(10, 0);
  7735. // Do NOT call set_payload_max_length — use the default 100MB limit
  7736. auto res =
  7737. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7738. total_received += data_length;
  7739. return true;
  7740. });
  7741. ASSERT_TRUE(res);
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. }
  7744. server_thread.join();
  7745. EXPECT_EQ(total_received, DATA_SIZE)
  7746. << "With content_receiver, the client should read all " << DATA_SIZE
  7747. << " bytes despite the default 100MB payload_max_length, but only read "
  7748. << total_received << " bytes.";
  7749. }
  7750. // Verify that an explicit set_payload_max_length smaller than the response is
  7751. // enforced even when a content_receiver is used.
  7752. TEST(ClientVulnerabilityTest,
  7753. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7754. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7755. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7756. #ifndef _WIN32
  7757. signal(SIGPIPE, SIG_IGN);
  7758. #endif
  7759. auto server_thread = std::thread([] {
  7760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7761. default_socket_options(srv);
  7762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7764. sockaddr_in addr{};
  7765. addr.sin_family = AF_INET;
  7766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7768. int opt = 1;
  7769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7770. #ifdef _WIN32
  7771. reinterpret_cast<const char *>(&opt),
  7772. #else
  7773. &opt,
  7774. #endif
  7775. sizeof(opt));
  7776. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7777. ::listen(srv, 1);
  7778. sockaddr_in cli_addr{};
  7779. socklen_t cli_len = sizeof(cli_addr);
  7780. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7781. if (cli != INVALID_SOCKET) {
  7782. char buf[4096];
  7783. ::recv(cli, buf, sizeof(buf), 0);
  7784. auto content_length = std::to_string(DATA_SIZE);
  7785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7786. "Content-Length: " +
  7787. content_length +
  7788. "\r\n"
  7789. "Connection: close\r\n"
  7790. "\r\n";
  7791. ::send(cli,
  7792. #ifdef _WIN32
  7793. static_cast<const char *>(response_header.c_str()),
  7794. static_cast<int>(response_header.size()),
  7795. #else
  7796. response_header.c_str(), response_header.size(),
  7797. #endif
  7798. 0);
  7799. std::string chunk(64 * 1024, 'A');
  7800. size_t total_sent = 0;
  7801. while (total_sent < DATA_SIZE) {
  7802. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7803. auto sent = ::send(cli,
  7804. #ifdef _WIN32
  7805. static_cast<const char *>(chunk.c_str()),
  7806. static_cast<int>(to_send),
  7807. #else
  7808. chunk.c_str(), to_send,
  7809. #endif
  7810. 0);
  7811. if (sent <= 0) break;
  7812. total_sent += static_cast<size_t>(sent);
  7813. }
  7814. detail::close_socket(cli);
  7815. }
  7816. detail::close_socket(srv);
  7817. });
  7818. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7819. size_t total_received = 0;
  7820. {
  7821. Client cli("127.0.0.1", PORT + 2);
  7822. cli.set_read_timeout(10, 0);
  7823. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7824. auto res =
  7825. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7826. total_received += data_length;
  7827. return true;
  7828. });
  7829. // Should fail because 200MB exceeds the explicit 150MB limit
  7830. EXPECT_FALSE(res);
  7831. }
  7832. server_thread.join();
  7833. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7834. << "Client with content_receiver should respect the explicit "
  7835. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7836. << total_received << " bytes.";
  7837. }
  7838. // Verify that an explicit set_payload_max_length larger than the response
  7839. // allows the content_receiver to read all data successfully.
  7840. TEST(ClientVulnerabilityTest,
  7841. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7842. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7843. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7844. #ifndef _WIN32
  7845. signal(SIGPIPE, SIG_IGN);
  7846. #endif
  7847. auto server_thread = std::thread([] {
  7848. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7849. default_socket_options(srv);
  7850. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7851. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7852. sockaddr_in addr{};
  7853. addr.sin_family = AF_INET;
  7854. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7856. int opt = 1;
  7857. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7858. #ifdef _WIN32
  7859. reinterpret_cast<const char *>(&opt),
  7860. #else
  7861. &opt,
  7862. #endif
  7863. sizeof(opt));
  7864. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7865. ::listen(srv, 1);
  7866. sockaddr_in cli_addr{};
  7867. socklen_t cli_len = sizeof(cli_addr);
  7868. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7869. if (cli != INVALID_SOCKET) {
  7870. char buf[4096];
  7871. ::recv(cli, buf, sizeof(buf), 0);
  7872. auto content_length = std::to_string(DATA_SIZE);
  7873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7874. "Content-Length: " +
  7875. content_length +
  7876. "\r\n"
  7877. "Connection: close\r\n"
  7878. "\r\n";
  7879. ::send(cli,
  7880. #ifdef _WIN32
  7881. static_cast<const char *>(response_header.c_str()),
  7882. static_cast<int>(response_header.size()),
  7883. #else
  7884. response_header.c_str(), response_header.size(),
  7885. #endif
  7886. 0);
  7887. std::string chunk(64 * 1024, 'A');
  7888. size_t total_sent = 0;
  7889. while (total_sent < DATA_SIZE) {
  7890. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7891. auto sent = ::send(cli,
  7892. #ifdef _WIN32
  7893. static_cast<const char *>(chunk.c_str()),
  7894. static_cast<int>(to_send),
  7895. #else
  7896. chunk.c_str(), to_send,
  7897. #endif
  7898. 0);
  7899. if (sent <= 0) break;
  7900. total_sent += static_cast<size_t>(sent);
  7901. }
  7902. #ifdef _WIN32
  7903. ::shutdown(cli, SD_SEND);
  7904. #else
  7905. ::shutdown(cli, SHUT_WR);
  7906. #endif
  7907. char drain[1024];
  7908. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7909. detail::close_socket(cli);
  7910. }
  7911. detail::close_socket(srv);
  7912. });
  7913. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7914. size_t total_received = 0;
  7915. {
  7916. Client cli("127.0.0.1", PORT + 2);
  7917. cli.set_read_timeout(10, 0);
  7918. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7919. auto res =
  7920. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7921. total_received += data_length;
  7922. return true;
  7923. });
  7924. ASSERT_TRUE(res);
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. }
  7927. server_thread.join();
  7928. EXPECT_EQ(total_received, DATA_SIZE)
  7929. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7930. << " bytes (larger than " << DATA_SIZE
  7931. << " bytes response), content_receiver should read all data, but only "
  7932. "read "
  7933. << total_received << " bytes.";
  7934. }
  7935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7936. // Regression test for "zip bomb" attack on the client side: a malicious server
  7937. // sends a small gzip-compressed response that decompresses to a huge payload.
  7938. // The client must enforce payload_max_length on the decompressed size.
  7939. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7940. constexpr size_t DECOMPRESSED_SIZE =
  7941. 10 * 1024 * 1024; // 10MB after decompression
  7942. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7943. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7944. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7945. std::string compressed;
  7946. {
  7947. httplib::detail::gzip_compressor compressor;
  7948. bool ok =
  7949. compressor.compress(uncompressed.data(), uncompressed.size(),
  7950. /*last=*/true, [&](const char *buf, size_t len) {
  7951. compressed.append(buf, len);
  7952. return true;
  7953. });
  7954. ASSERT_TRUE(ok);
  7955. }
  7956. // Sanity: compressed data should be much smaller than the decompressed size
  7957. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7958. #ifndef _WIN32
  7959. signal(SIGPIPE, SIG_IGN);
  7960. #endif
  7961. // Set up the listening socket in the main thread so the server is guaranteed
  7962. // to be ready before the client connects (eliminates race condition).
  7963. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7964. default_socket_options(srv);
  7965. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7966. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7967. sockaddr_in addr{};
  7968. addr.sin_family = AF_INET;
  7969. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7970. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7971. int opt = 1;
  7972. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7973. #ifdef _WIN32
  7974. reinterpret_cast<const char *>(&opt),
  7975. #else
  7976. &opt,
  7977. #endif
  7978. sizeof(opt));
  7979. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7980. ASSERT_EQ(0, ::listen(srv, 1));
  7981. auto server_thread = std::thread([&compressed, srv] {
  7982. sockaddr_in cli_addr{};
  7983. socklen_t cli_len = sizeof(cli_addr);
  7984. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7985. if (cli != INVALID_SOCKET) {
  7986. // Read the full HTTP request (until \r\n\r\n)
  7987. char buf[4096];
  7988. size_t total = 0;
  7989. while (total < sizeof(buf)) {
  7990. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7991. if (n <= 0) break;
  7992. total += static_cast<size_t>(n);
  7993. // Check for end of headers
  7994. if (total >= 4) {
  7995. std::string req(buf, total);
  7996. if (req.find("\r\n\r\n") != std::string::npos) break;
  7997. }
  7998. }
  7999. // Malicious response: gzip-compressed body, no Content-Length
  8000. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8001. "Content-Encoding: gzip\r\n"
  8002. "Connection: close\r\n"
  8003. "\r\n";
  8004. ::send(cli,
  8005. #ifdef _WIN32
  8006. static_cast<const char *>(response_header.c_str()),
  8007. static_cast<int>(response_header.size()),
  8008. #else
  8009. response_header.c_str(), response_header.size(),
  8010. #endif
  8011. 0);
  8012. // Send the compressed payload (small on the wire, huge when decompressed)
  8013. size_t total_sent = 0;
  8014. while (total_sent < compressed.size()) {
  8015. auto to_send = std::min(compressed.size() - total_sent,
  8016. static_cast<size_t>(64 * 1024));
  8017. auto sent =
  8018. ::send(cli,
  8019. #ifdef _WIN32
  8020. static_cast<const char *>(compressed.c_str() + total_sent),
  8021. static_cast<int>(to_send),
  8022. #else
  8023. compressed.c_str() + total_sent, to_send,
  8024. #endif
  8025. 0);
  8026. if (sent <= 0) break;
  8027. total_sent += static_cast<size_t>(sent);
  8028. }
  8029. detail::close_socket(cli);
  8030. }
  8031. });
  8032. auto se = detail::scope_exit([&] {
  8033. detail::close_socket(srv);
  8034. server_thread.join();
  8035. });
  8036. size_t total_decompressed = 0;
  8037. {
  8038. Client cli("127.0.0.1", PORT + 3);
  8039. cli.set_read_timeout(5, 0);
  8040. cli.set_decompress(true);
  8041. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8042. auto stream = cli.open_stream("GET", "/zipbomb");
  8043. ASSERT_TRUE(stream.is_valid());
  8044. char buffer[64 * 1024];
  8045. ssize_t n;
  8046. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8047. total_decompressed += static_cast<size_t>(n);
  8048. }
  8049. }
  8050. // The decompressed size must be capped by payload_max_length. Without
  8051. // protection, the client would decompress the full 10MB from a tiny
  8052. // compressed payload, enabling a zip bomb DoS attack.
  8053. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8054. << "Client decompressed " << total_decompressed
  8055. << " bytes from a gzip response. The decompressed size should be "
  8056. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8057. }
  8058. #endif
  8059. TEST(HostAndPortPropertiesTest, NoSSL) {
  8060. httplib::Client cli("www.google.com", 1234);
  8061. ASSERT_EQ("www.google.com", cli.host());
  8062. ASSERT_EQ(1234, cli.port());
  8063. }
  8064. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8065. httplib::Client cli("www.google.com:1234");
  8066. ASSERT_EQ("www.google.com", cli.host());
  8067. ASSERT_EQ(1234, cli.port());
  8068. }
  8069. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8070. // Port number that overflows int — should not crash, client becomes invalid
  8071. httplib::Client cli("http://www.google.com:99999999999999999999");
  8072. ASSERT_FALSE(cli.is_valid());
  8073. }
  8074. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8075. // Port 99999 exceeds valid range (1-65535) — should not crash
  8076. httplib::Client cli("http://www.google.com:99999");
  8077. ASSERT_FALSE(cli.is_valid());
  8078. }
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. TEST(HostAndPortPropertiesTest, SSL) {
  8081. httplib::SSLClient cli("www.google.com");
  8082. ASSERT_EQ("www.google.com", cli.host());
  8083. ASSERT_EQ(443, cli.port());
  8084. }
  8085. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8086. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8087. std::string cert;
  8088. read_file(CA_CERT_FILE, cert);
  8089. httplib::SSLClient httplib_client("www.google.com");
  8090. // Load CA store first time
  8091. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8092. // Load CA store second time (update)
  8093. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8094. // Verify client is still valid and can make connections
  8095. httplib_client.enable_server_certificate_verification(true);
  8096. auto res = httplib_client.Get("/");
  8097. ASSERT_TRUE(res);
  8098. // Google may return 200 or 301 depending on various factors
  8099. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8100. res->status == StatusCode::MovedPermanently_301);
  8101. }
  8102. TEST(SSLClientTest, ServerNameIndication_Online) {
  8103. auto host = "httpbingo.org";
  8104. auto path = std::string{"/get"};
  8105. SSLClient cli(host, 443);
  8106. auto res = cli.Get(path);
  8107. ASSERT_TRUE(res);
  8108. ASSERT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8111. // Use a site that will cause SSL verification failure due to self-signed cert
  8112. SSLClient cli("self-signed.badssl.com", 443);
  8113. cli.enable_server_certificate_verification(true);
  8114. auto res = cli.Get("/");
  8115. ASSERT_TRUE(!res);
  8116. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8117. // Verify backend error is captured for SSLServerVerification
  8118. // This occurs when certificate verification fails
  8119. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8120. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8121. EXPECT_NE(0UL, res.ssl_backend_error());
  8122. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8123. // For OpenSSL, ssl_error is 0 for verification errors
  8124. EXPECT_EQ(0, res.ssl_error());
  8125. #if !defined(_WIN32) || \
  8126. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8127. // On non-Windows or when Windows Schannel is disabled, the error comes
  8128. // from OpenSSL's verification
  8129. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8130. res.ssl_backend_error());
  8131. #endif
  8132. #endif
  8133. }
  8134. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8135. // Use a site where hostname doesn't match the certificate
  8136. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8137. SSLClient cli("wrong.host.badssl.com", 443);
  8138. cli.enable_server_certificate_verification(true);
  8139. cli.enable_server_hostname_verification(true);
  8140. auto res = cli.Get("/");
  8141. ASSERT_TRUE(!res);
  8142. // The error type depends on when hostname verification occurs:
  8143. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8144. // - Mbed TLS: SSLServerVerification (during handshake)
  8145. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8146. res.error() == Error::SSLServerVerification);
  8147. // Verify backend error is captured for hostname verification failure
  8148. EXPECT_NE(0UL, res.ssl_backend_error());
  8149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8150. // For OpenSSL, ssl_error is 0 for verification errors
  8151. EXPECT_EQ(0, res.ssl_error());
  8152. #if !defined(_WIN32) || \
  8153. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8154. // On non-Windows or when Windows Schannel is disabled, the error comes
  8155. // from OpenSSL's hostname verification
  8156. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8157. res.ssl_backend_error());
  8158. #endif
  8159. #endif
  8160. }
  8161. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8162. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8163. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8164. SSLClient cli("www.google.com", 443);
  8165. cli.enable_server_certificate_verification(true);
  8166. auto res = cli.Get("/");
  8167. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8168. }
  8169. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8170. SSLClient cli("www.google.com", 443);
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.enable_windows_certificate_verification(false);
  8173. auto res = cli.Get("/");
  8174. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8175. }
  8176. #endif
  8177. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8178. Client cli("https://google.com");
  8179. auto res = cli.Get("/");
  8180. ASSERT_TRUE(res);
  8181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8182. }
  8183. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8184. SSLClient cli("google.com");
  8185. cli.set_ca_cert_path(CA_CERT_FILE);
  8186. auto res = cli.Get("/");
  8187. ASSERT_TRUE(res);
  8188. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8189. }
  8190. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8191. SSLClient cli("google.com");
  8192. cli.enable_server_certificate_verification(true);
  8193. cli.set_ca_cert_path("hello");
  8194. auto res = cli.Get("/");
  8195. ASSERT_TRUE(!res);
  8196. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8197. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8198. // should be set
  8199. EXPECT_EQ(0, res.ssl_error());
  8200. // Verify backend error is captured for SSLLoadingCerts
  8201. // This error occurs when loading CA certificates fails
  8202. EXPECT_NE(0UL, res.ssl_backend_error());
  8203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8204. // OpenSSL specific error codes:
  8205. // > openssl errstr 0x80000002
  8206. // error:80000002:system library::No such file or directory
  8207. // > openssl errstr 0xA000126
  8208. // error:0A000126:SSL routines::unexpected eof while reading
  8209. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8210. res.ssl_backend_error() == 0xA000126);
  8211. #endif
  8212. }
  8213. TEST(SSLClientTest, ServerCertificateVerification4) {
  8214. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8215. ASSERT_TRUE(svr.is_valid());
  8216. svr.Get("/test", [&](const Request &, Response &res) {
  8217. res.set_content("test", "text/plain");
  8218. svr.stop();
  8219. ASSERT_TRUE(true);
  8220. });
  8221. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8222. auto se = detail::scope_exit([&] {
  8223. t.join();
  8224. ASSERT_FALSE(svr.is_running());
  8225. });
  8226. svr.wait_until_ready();
  8227. SSLClient cli("127.0.0.1", PORT);
  8228. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8229. cli.enable_server_certificate_verification(true);
  8230. cli.set_connection_timeout(30);
  8231. auto res = cli.Get("/test");
  8232. ASSERT_TRUE(res);
  8233. ASSERT_EQ(StatusCode::OK_200, res->status);
  8234. }
  8235. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8236. std::string cert;
  8237. read_file(CA_CERT_FILE, cert);
  8238. SSLClient cli("google.com");
  8239. cli.load_ca_cert_store(cert.data(), cert.size());
  8240. const auto res = cli.Get("/");
  8241. ASSERT_TRUE(res);
  8242. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8243. }
  8244. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8245. // clang-format off
  8246. static constexpr char cert[] =
  8247. "GlobalSign Root CA\n"
  8248. "==================\n"
  8249. "-----BEGIN CERTIFICATE-----\n"
  8250. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8251. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8252. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8253. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8254. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8255. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8256. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8257. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8258. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8259. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8260. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8261. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8262. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8263. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8264. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8265. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8266. "-----END CERTIFICATE-----\n";
  8267. // clang-format on
  8268. SSLClient cli("google.com");
  8269. cli.load_ca_cert_store(cert, sizeof(cert));
  8270. const auto res = cli.Get("/");
  8271. ASSERT_TRUE(res);
  8272. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8273. }
  8274. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8275. SSLClient cli("www.youtube.com");
  8276. cli.set_ca_cert_path(CA_CERT_FILE);
  8277. cli.enable_server_certificate_verification(true);
  8278. cli.set_follow_location(true);
  8279. auto res = cli.Get("/");
  8280. ASSERT_TRUE(res);
  8281. ASSERT_EQ(StatusCode::OK_200, res->status);
  8282. }
  8283. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8284. SSLClient cli("wWw.YouTube.Com");
  8285. cli.set_ca_cert_path(CA_CERT_FILE);
  8286. cli.enable_server_certificate_verification(true);
  8287. cli.enable_server_hostname_verification(true);
  8288. cli.set_follow_location(true);
  8289. auto res = cli.Get("/");
  8290. ASSERT_TRUE(res);
  8291. ASSERT_EQ(StatusCode::OK_200, res->status);
  8292. }
  8293. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8294. SSLClient cli("gOoGlE.COm");
  8295. cli.enable_server_certificate_verification(true);
  8296. cli.enable_server_hostname_verification(true);
  8297. cli.set_follow_location(true);
  8298. auto res = cli.Get("/");
  8299. ASSERT_TRUE(res);
  8300. ASSERT_EQ(StatusCode::OK_200, res->status);
  8301. }
  8302. TEST(SSLClientTest, Issue2004_Online) {
  8303. Client client("https://google.com");
  8304. client.set_follow_location(true);
  8305. auto res = client.Get("/");
  8306. ASSERT_TRUE(res);
  8307. ASSERT_EQ(StatusCode::OK_200, res->status);
  8308. auto body = res->body;
  8309. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8310. }
  8311. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8312. // Create SSLClient with invalid cert/key to make is_valid() return false
  8313. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8314. "nonexistent_key.pem");
  8315. // is_valid() should be false due to cert loading failure
  8316. ASSERT_FALSE(cli.is_valid());
  8317. auto res = cli.Get("/");
  8318. ASSERT_FALSE(res);
  8319. EXPECT_EQ(Error::SSLConnection, res.error());
  8320. }
  8321. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8322. // Test for Issue #2251: SSL error not properly reported when client cert
  8323. // and key paths are swapped or mismatched
  8324. // This simulates the scenario where user accidentally swaps the cert and key
  8325. // files
  8326. // Using client cert file as private key and vice versa (completely wrong)
  8327. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8328. // Should fail validation due to cert/key mismatch
  8329. ASSERT_FALSE(cli.is_valid());
  8330. // Attempt to make a request should fail with proper error
  8331. auto res = cli.Get("/");
  8332. ASSERT_FALSE(res);
  8333. EXPECT_EQ(Error::SSLConnection, res.error());
  8334. // SSL error should be recorded in the Result object (this is the key fix for
  8335. // Issue #2251)
  8336. auto backend_error = res.ssl_backend_error();
  8337. EXPECT_NE(0u, backend_error);
  8338. }
  8339. // Tests cert/key mismatch detection at the TLS context level
  8340. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8341. // Test that using mismatched cert/key causes connection failure.
  8342. // We verify this at the SSLClient level rather than through internal
  8343. // TLS API functions.
  8344. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8345. cli.enable_server_certificate_verification(false);
  8346. cli.set_connection_timeout(2);
  8347. // The mismatch should cause a connection or handshake error
  8348. auto res = cli.Get("/test");
  8349. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8350. // Either way, the request should fail
  8351. EXPECT_FALSE(res);
  8352. }
  8353. #endif
  8354. #if 0
  8355. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8356. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8357. ASSERT_TRUE(cli != nullptr);
  8358. cli->set_address_family(AF_INET6);
  8359. cli->set_interface("en0");
  8360. auto res = cli->Get("/get");
  8361. ASSERT_TRUE(res);
  8362. ASSERT_EQ(StatusCode::OK_200, res->status);
  8363. }
  8364. #endif
  8365. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8366. #ifdef CPPHTTPLIB_SSL_ENABLED
  8367. void ClientCertPresent(
  8368. const std::string &client_cert_file,
  8369. const std::string &client_private_key_file,
  8370. const std::string &client_encrypted_private_key_pass = std::string()) {
  8371. using namespace httplib::tls;
  8372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8373. CLIENT_CA_CERT_DIR);
  8374. ASSERT_TRUE(svr.is_valid());
  8375. svr.Get("/test", [&](const Request &req, Response &res) {
  8376. res.set_content("test", "text/plain");
  8377. auto cert = req.peer_cert();
  8378. ASSERT_TRUE(static_cast<bool>(cert));
  8379. std::string common_name = cert.subject_cn();
  8380. EXPECT_EQ("Common Name", common_name);
  8381. });
  8382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8383. auto se = detail::scope_exit([&] {
  8384. svr.stop();
  8385. t.join();
  8386. ASSERT_FALSE(svr.is_running());
  8387. });
  8388. svr.wait_until_ready();
  8389. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8390. client_encrypted_private_key_pass);
  8391. cli.enable_server_certificate_verification(false);
  8392. cli.set_connection_timeout(30);
  8393. auto res = cli.Get("/test");
  8394. ASSERT_TRUE(res);
  8395. ASSERT_EQ(StatusCode::OK_200, res->status);
  8396. }
  8397. TEST(SSLClientServerTest, ClientCertPresent) {
  8398. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8399. }
  8400. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8401. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8402. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8403. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8404. }
  8405. // PEM memory-based constructor tests (works with all TLS backends)
  8406. void PemMemoryClientCertPresent(
  8407. const std::string &client_cert_file,
  8408. const std::string &client_private_key_file,
  8409. const std::string &client_encrypted_private_key_pass = std::string()) {
  8410. // Read PEM files into memory
  8411. std::string server_cert_pem, server_key_pem;
  8412. std::string client_ca_pem;
  8413. std::string client_cert_pem, client_key_pem;
  8414. read_file(SERVER_CERT_FILE, server_cert_pem);
  8415. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8416. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8417. read_file(client_cert_file, client_cert_pem);
  8418. read_file(client_private_key_file, client_key_pem);
  8419. // Create server with PEM memory
  8420. SSLServer::PemMemory server_pem = {
  8421. server_cert_pem.c_str(),
  8422. server_cert_pem.size(),
  8423. server_key_pem.c_str(),
  8424. server_key_pem.size(),
  8425. client_ca_pem.c_str(),
  8426. client_ca_pem.size(),
  8427. nullptr // no password for server key
  8428. };
  8429. SSLServer svr(server_pem);
  8430. ASSERT_TRUE(svr.is_valid());
  8431. svr.Get("/test", [&](const Request &, Response &res) {
  8432. res.set_content("test", "text/plain");
  8433. });
  8434. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8435. auto se = detail::scope_exit([&] {
  8436. svr.stop();
  8437. t.join();
  8438. ASSERT_FALSE(svr.is_running());
  8439. });
  8440. svr.wait_until_ready();
  8441. // Create client with PEM memory
  8442. const char *password = client_encrypted_private_key_pass.empty()
  8443. ? nullptr
  8444. : client_encrypted_private_key_pass.c_str();
  8445. SSLClient::PemMemory client_pem = {
  8446. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8447. client_key_pem.size(), password};
  8448. SSLClient cli(HOST, PORT, client_pem);
  8449. cli.enable_server_certificate_verification(false);
  8450. cli.set_connection_timeout(30);
  8451. auto res = cli.Get("/test");
  8452. ASSERT_TRUE(res);
  8453. ASSERT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8456. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8457. }
  8458. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8459. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8460. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8461. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8462. }
  8463. TEST(SSLClientServerTest, ClientCertMissing) {
  8464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8465. CLIENT_CA_CERT_DIR);
  8466. ASSERT_TRUE(svr.is_valid());
  8467. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. t.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. SSLClient cli(HOST, PORT);
  8476. cli.set_connection_timeout(30);
  8477. auto res = cli.Get("/test");
  8478. ASSERT_TRUE(!res);
  8479. // When client cert is missing and server requires it, connection fails
  8480. // Error type depends on backend implementation
  8481. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8482. res.error() == Error::SSLConnection);
  8483. // Verify backend error is captured
  8484. // Note: This test may have different error codes depending on the exact
  8485. // verification failure
  8486. EXPECT_NE(0UL, res.ssl_backend_error());
  8487. }
  8488. TEST(SSLClientServerTest, TrustDirOptional) {
  8489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8490. ASSERT_TRUE(svr.is_valid());
  8491. svr.Get("/test", [&](const Request &, Response &res) {
  8492. res.set_content("test", "text/plain");
  8493. });
  8494. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8495. auto se = detail::scope_exit([&] {
  8496. svr.stop();
  8497. t.join();
  8498. ASSERT_FALSE(svr.is_running());
  8499. });
  8500. svr.wait_until_ready();
  8501. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8502. cli.enable_server_certificate_verification(false);
  8503. cli.set_connection_timeout(30);
  8504. auto res = cli.Get("/test");
  8505. ASSERT_TRUE(res);
  8506. ASSERT_EQ(StatusCode::OK_200, res->status);
  8507. }
  8508. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8509. class NoListenSSLServer : public SSLServer {
  8510. public:
  8511. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8512. const char *client_ca_cert_file_path,
  8513. const char *client_ca_cert_dir_path = nullptr)
  8514. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8515. client_ca_cert_dir_path),
  8516. stop_(false) {}
  8517. std::atomic_bool stop_;
  8518. private:
  8519. bool process_and_close_socket(socket_t /*sock*/) override {
  8520. // Don't create SSL context
  8521. while (!stop_.load()) {
  8522. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8523. }
  8524. return true;
  8525. }
  8526. };
  8527. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8528. CLIENT_CA_CERT_FILE);
  8529. ASSERT_TRUE(svr.is_valid());
  8530. svr.Get("/test", [&](const Request &, Response &res) {
  8531. res.set_content("test", "text/plain");
  8532. });
  8533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8534. auto se = detail::scope_exit([&] {
  8535. svr.stop_ = true;
  8536. svr.stop();
  8537. t.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8542. cli.enable_server_certificate_verification(false);
  8543. cli.set_connection_timeout(1);
  8544. auto res = cli.Get("/test");
  8545. ASSERT_TRUE(!res);
  8546. EXPECT_EQ(Error::SSLConnection, res.error());
  8547. // Timeout results in WantRead error code (maps to backend-specific value)
  8548. EXPECT_NE(0, res.ssl_error());
  8549. }
  8550. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8551. // Test SSLServer with client certificate verification using the standard
  8552. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8554. CLIENT_CA_CERT_DIR);
  8555. ASSERT_TRUE(svr.is_valid());
  8556. svr.Get("/test", [&](const Request &req, Response &res) {
  8557. res.set_content("test", "text/plain");
  8558. auto cert = req.peer_cert();
  8559. ASSERT_TRUE(static_cast<bool>(cert));
  8560. auto common_name = cert.subject_cn();
  8561. EXPECT_EQ("Common Name", common_name);
  8562. });
  8563. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8564. auto se = detail::scope_exit([&] {
  8565. svr.stop();
  8566. t.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8571. cli.enable_server_certificate_verification(false);
  8572. cli.set_connection_timeout(30);
  8573. auto res = cli.Get("/test");
  8574. ASSERT_TRUE(res);
  8575. ASSERT_EQ(StatusCode::OK_200, res->status);
  8576. }
  8577. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8578. // Verifies that wildcard matching and exact matching work consistently
  8579. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8580. using namespace httplib::tls;
  8581. // We need a running server to test against
  8582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8583. ASSERT_TRUE(svr.is_valid());
  8584. svr.Get("/test", [](const Request &, Response &res) {
  8585. res.set_content("ok", "text/plain");
  8586. });
  8587. thread t([&]() { svr.listen(HOST, PORT); });
  8588. auto se = detail::scope_exit([&] {
  8589. svr.stop();
  8590. t.join();
  8591. });
  8592. svr.wait_until_ready();
  8593. bool verify_callback_called = false;
  8594. bool verify_result_wrong = false;
  8595. SSLClient cli(HOST, PORT);
  8596. cli.enable_server_certificate_verification(true);
  8597. cli.set_ca_cert_path(CA_CERT_FILE);
  8598. cli.set_connection_timeout(5);
  8599. // Note: Test certificate has CN="Common Name", not "localhost"
  8600. bool verify_result_cn = false;
  8601. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8602. verify_callback_called = true;
  8603. if (!ctx.cert) return false;
  8604. // Test 1: "Common Name" should match (our test server cert CN)
  8605. verify_result_cn = ctx.check_hostname("Common Name");
  8606. // Test 2: wrong hostname should not match
  8607. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8608. return true; // Accept for the purpose of this test
  8609. });
  8610. auto res = cli.Get("/test");
  8611. // The request may succeed or fail depending on cert configuration
  8612. // but the callback should have been called
  8613. ASSERT_TRUE(verify_callback_called)
  8614. << "Verify callback should have been called";
  8615. // CN="Common Name" should match our test certificate
  8616. EXPECT_TRUE(verify_result_cn)
  8617. << "verify_hostname should match 'Common Name' (certificate CN)";
  8618. // Wrong hostname should not match
  8619. EXPECT_FALSE(verify_result_wrong)
  8620. << "verify_hostname should not match 'wronghost.example.com'";
  8621. }
  8622. #endif
  8623. // mbedTLS-specific callback constructor test
  8624. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8625. #ifdef CPPHTTPLIB_SSL_ENABLED
  8626. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8628. ASSERT_TRUE(svr.is_valid());
  8629. // Set up a handler to verify client certificate is present
  8630. bool client_cert_verified = false;
  8631. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8632. // Verify that client certificate was provided
  8633. client_cert_verified = true;
  8634. res.set_content("success", "text/plain");
  8635. });
  8636. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8637. auto se = detail::scope_exit([&] {
  8638. svr.stop();
  8639. t.join();
  8640. ASSERT_FALSE(svr.is_running());
  8641. });
  8642. svr.wait_until_ready();
  8643. // Client with certificate
  8644. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8645. cli.enable_server_certificate_verification(false);
  8646. cli.set_connection_timeout(30);
  8647. auto res = cli.Get("/test");
  8648. ASSERT_TRUE(res);
  8649. ASSERT_EQ(StatusCode::OK_200, res->status);
  8650. ASSERT_TRUE(client_cert_verified);
  8651. EXPECT_EQ("success", res->body);
  8652. }
  8653. #endif
  8654. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8655. // backends
  8656. #ifdef CPPHTTPLIB_SSL_ENABLED
  8657. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8658. using namespace httplib::tls;
  8659. // Test that when client CA cert file is provided,
  8660. // the server properly requests and validates client certificates
  8661. // Create a server with client authentication
  8662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8663. ASSERT_TRUE(svr.is_valid());
  8664. bool handler_called = false;
  8665. svr.Get("/test", [&](const Request &req, Response &res) {
  8666. handler_called = true;
  8667. // Verify that a client certificate was provided
  8668. auto cert = req.peer_cert();
  8669. ASSERT_TRUE(static_cast<bool>(cert));
  8670. // Get the issuer name
  8671. std::string issuer_str = cert.issuer_name();
  8672. ASSERT_FALSE(issuer_str.empty());
  8673. // The client certificate should be issued by our test CA
  8674. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8675. res.set_content("authenticated", "text/plain");
  8676. });
  8677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8678. auto se = detail::scope_exit([&] {
  8679. svr.stop();
  8680. t.join();
  8681. ASSERT_FALSE(svr.is_running());
  8682. });
  8683. svr.wait_until_ready();
  8684. // Connect with a client certificate issued by the CA
  8685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8686. cli.enable_server_certificate_verification(false);
  8687. cli.set_connection_timeout(30);
  8688. auto res = cli.Get("/test");
  8689. ASSERT_TRUE(res);
  8690. ASSERT_EQ(StatusCode::OK_200, res->status);
  8691. ASSERT_TRUE(handler_called);
  8692. EXPECT_EQ("authenticated", res->body);
  8693. }
  8694. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8695. using namespace httplib::tls;
  8696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8697. ASSERT_TRUE(svr.is_valid());
  8698. svr.Get("/test", [](const Request &, Response &res) {
  8699. res.set_content("ok", "text/plain");
  8700. });
  8701. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8702. auto se = detail::scope_exit([&] {
  8703. svr.stop();
  8704. t.join();
  8705. });
  8706. svr.wait_until_ready();
  8707. SSLClient cli(HOST, PORT);
  8708. cli.enable_server_certificate_verification(false);
  8709. cli.set_connection_timeout(30);
  8710. bool cert_checked = false;
  8711. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8712. if (ctx.cert) {
  8713. auto sans = ctx.sans();
  8714. // Test certificate may or may not have SANs - just verify the API
  8715. // works If SANs exist, verify the types are valid
  8716. for (const auto &san : sans) {
  8717. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8718. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8719. san.type == SanType::OTHER);
  8720. EXPECT_FALSE(san.value.empty());
  8721. }
  8722. cert_checked = true;
  8723. }
  8724. return true;
  8725. });
  8726. auto res = cli.Get("/test");
  8727. ASSERT_TRUE(res);
  8728. EXPECT_TRUE(cert_checked);
  8729. }
  8730. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8731. using namespace httplib::tls;
  8732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8733. ASSERT_TRUE(svr.is_valid());
  8734. svr.Get("/test", [](const Request &, Response &res) {
  8735. res.set_content("ok", "text/plain");
  8736. });
  8737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8738. auto se = detail::scope_exit([&] {
  8739. svr.stop();
  8740. t.join();
  8741. });
  8742. svr.wait_until_ready();
  8743. SSLClient cli(HOST, PORT);
  8744. cli.enable_server_certificate_verification(false);
  8745. cli.set_connection_timeout(30);
  8746. bool validity_checked = false;
  8747. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8748. if (ctx.cert) {
  8749. time_t not_before = 0, not_after = 0;
  8750. bool result = ctx.validity(not_before, not_after);
  8751. EXPECT_TRUE(result);
  8752. // Verify that not_before < now < not_after for a valid cert
  8753. time_t now = time(nullptr);
  8754. EXPECT_LT(not_before, now);
  8755. EXPECT_GT(not_after, now);
  8756. validity_checked = true;
  8757. }
  8758. return true;
  8759. });
  8760. auto res = cli.Get("/test");
  8761. ASSERT_TRUE(res);
  8762. EXPECT_TRUE(validity_checked);
  8763. }
  8764. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8765. using namespace httplib::tls;
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8767. ASSERT_TRUE(svr.is_valid());
  8768. svr.Get("/test", [](const Request &, Response &res) {
  8769. res.set_content("ok", "text/plain");
  8770. });
  8771. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. });
  8776. svr.wait_until_ready();
  8777. SSLClient cli(HOST, PORT);
  8778. cli.enable_server_certificate_verification(false);
  8779. cli.set_connection_timeout(30);
  8780. bool serial_checked = false;
  8781. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8782. if (ctx.cert) {
  8783. std::string serial = ctx.serial();
  8784. EXPECT_FALSE(serial.empty());
  8785. // Serial should be a hex string
  8786. for (char c : serial) {
  8787. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8788. (c >= 'a' && c <= 'f'));
  8789. }
  8790. serial_checked = true;
  8791. }
  8792. return true;
  8793. });
  8794. auto res = cli.Get("/test");
  8795. ASSERT_TRUE(res);
  8796. EXPECT_TRUE(serial_checked);
  8797. }
  8798. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8799. // Test 1: Valid CA file - no error should be recorded
  8800. {
  8801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8802. CLIENT_CA_CERT_FILE);
  8803. ASSERT_TRUE(svr.is_valid());
  8804. // With valid setup, last_ssl_error should be 0
  8805. EXPECT_EQ(0, svr.ssl_last_error());
  8806. }
  8807. // Test 2: Invalid CA file content
  8808. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8809. {
  8810. // Create a temporary file with completely invalid content
  8811. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8812. {
  8813. std::ofstream ofs(temp_invalid_ca);
  8814. ofs << "This is not a certificate file at all\n";
  8815. ofs << "Just plain text content\n";
  8816. }
  8817. // Create server with invalid CA file
  8818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8819. // Clean up temporary file
  8820. std::remove(temp_invalid_ca);
  8821. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8822. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8823. // Note: SSL_CTX_load_verify_locations typically fails first,
  8824. // but our error handling code path is still exercised
  8825. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8826. }
  8827. }
  8828. TEST(VerifyCallbackTest, VerifyContextFields) {
  8829. using namespace httplib::tls;
  8830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8831. ASSERT_TRUE(svr.is_valid());
  8832. svr.Get("/test", [](const Request &, Response &res) {
  8833. res.set_content("ok", "text/plain");
  8834. });
  8835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8836. auto se = detail::scope_exit([&] {
  8837. svr.stop();
  8838. t.join();
  8839. });
  8840. svr.wait_until_ready();
  8841. SSLClient cli(HOST, PORT);
  8842. cli.enable_server_certificate_verification(false);
  8843. cli.set_connection_timeout(30);
  8844. int callback_count = 0;
  8845. bool saw_leaf_cert = false;
  8846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8847. if (ctx.cert) {
  8848. callback_count++;
  8849. // We should see at least one certificate (the leaf)
  8850. std::string cn = ctx.subject_cn();
  8851. if (!cn.empty()) { saw_leaf_cert = true; }
  8852. // Verify context fields are populated
  8853. EXPECT_NE(ctx.session, nullptr);
  8854. EXPECT_GE(ctx.depth, 0);
  8855. }
  8856. return true;
  8857. });
  8858. auto res = cli.Get("/test");
  8859. ASSERT_TRUE(res);
  8860. EXPECT_GT(callback_count, 0);
  8861. EXPECT_TRUE(saw_leaf_cert);
  8862. }
  8863. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8864. using httplib::tls::TlsError;
  8865. // Test that verify_error_to_string returns empty for success
  8866. std::string success_str = TlsError::verify_error_to_string(0);
  8867. EXPECT_TRUE(success_str.empty());
  8868. // Test that verify_error_to_string returns non-empty for error codes
  8869. // Using a common error code (certificate expired)
  8870. std::string error_str =
  8871. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8872. EXPECT_FALSE(error_str.empty());
  8873. }
  8874. TEST(SessionVerifierTest, CertificateAccepted) {
  8875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8876. ASSERT_TRUE(svr.is_valid());
  8877. svr.Get("/test", [](const Request &, Response &res) {
  8878. res.set_content("ok", "text/plain");
  8879. });
  8880. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8881. auto se = detail::scope_exit([&] {
  8882. svr.stop();
  8883. t.join();
  8884. });
  8885. svr.wait_until_ready();
  8886. SSLClient cli(HOST, PORT);
  8887. cli.enable_server_certificate_verification(false);
  8888. cli.set_connection_timeout(30);
  8889. bool callback_called = false;
  8890. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8891. EXPECT_NE(session, nullptr);
  8892. callback_called = true;
  8893. return SSLVerifierResponse::CertificateAccepted;
  8894. });
  8895. auto res = cli.Get("/test");
  8896. ASSERT_TRUE(res);
  8897. EXPECT_EQ(200, res->status);
  8898. EXPECT_TRUE(callback_called);
  8899. }
  8900. TEST(SessionVerifierTest, CertificateRejected) {
  8901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8902. ASSERT_TRUE(svr.is_valid());
  8903. svr.Get("/test", [](const Request &, Response &res) {
  8904. res.set_content("ok", "text/plain");
  8905. });
  8906. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8907. auto se = detail::scope_exit([&] {
  8908. svr.stop();
  8909. t.join();
  8910. });
  8911. svr.wait_until_ready();
  8912. SSLClient cli(HOST, PORT);
  8913. cli.enable_server_certificate_verification(false);
  8914. cli.set_connection_timeout(30);
  8915. bool callback_called = false;
  8916. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8917. EXPECT_NE(session, nullptr);
  8918. callback_called = true;
  8919. return SSLVerifierResponse::CertificateRejected;
  8920. });
  8921. auto res = cli.Get("/test");
  8922. EXPECT_FALSE(res);
  8923. EXPECT_TRUE(callback_called);
  8924. }
  8925. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8927. ASSERT_TRUE(svr.is_valid());
  8928. svr.Get("/test", [](const Request &, Response &res) {
  8929. res.set_content("ok", "text/plain");
  8930. });
  8931. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. });
  8936. svr.wait_until_ready();
  8937. // NoDecisionMade with verification disabled should succeed (no default check)
  8938. SSLClient cli(HOST, PORT);
  8939. cli.enable_server_certificate_verification(false);
  8940. cli.set_connection_timeout(30);
  8941. bool callback_called = false;
  8942. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8943. EXPECT_NE(session, nullptr);
  8944. callback_called = true;
  8945. return SSLVerifierResponse::NoDecisionMade;
  8946. });
  8947. auto res = cli.Get("/test");
  8948. ASSERT_TRUE(res);
  8949. EXPECT_EQ(200, res->status);
  8950. EXPECT_TRUE(callback_called);
  8951. }
  8952. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8954. ASSERT_TRUE(svr.is_valid());
  8955. svr.Get("/test", [](const Request &, Response &res) {
  8956. res.set_content("ok", "text/plain");
  8957. });
  8958. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8959. auto se = detail::scope_exit([&] {
  8960. svr.stop();
  8961. t.join();
  8962. });
  8963. svr.wait_until_ready();
  8964. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8965. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8966. // so we only check that the request fails, not whether the callback was
  8967. // called.
  8968. SSLClient cli(HOST, PORT);
  8969. cli.enable_server_certificate_verification(true);
  8970. cli.set_connection_timeout(30);
  8971. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8972. EXPECT_NE(session, nullptr);
  8973. return SSLVerifierResponse::NoDecisionMade;
  8974. });
  8975. auto res = cli.Get("/test");
  8976. EXPECT_FALSE(res);
  8977. }
  8978. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8979. // Test SSL server using PemMemory constructor with client CA certificates
  8980. // Read PEM files
  8981. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8982. read_file(SERVER_CERT_FILE, server_cert_pem);
  8983. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8984. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8985. // Create SSLServer with PemMemory constructor including client CA
  8986. SSLServer::PemMemory server_pem = {
  8987. server_cert_pem.c_str(),
  8988. server_cert_pem.size(),
  8989. server_key_pem.c_str(),
  8990. server_key_pem.size(),
  8991. client_ca_pem.c_str(),
  8992. client_ca_pem.size(),
  8993. nullptr // no password for server key
  8994. };
  8995. SSLServer svr(server_pem);
  8996. ASSERT_TRUE(svr.is_valid());
  8997. // No SSL error should be recorded for valid setup
  8998. EXPECT_EQ(0, svr.ssl_last_error());
  8999. // Set up server endpoints
  9000. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9001. res.set_content("ok", "text/plain");
  9002. });
  9003. // Start server in a thread
  9004. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9005. svr.wait_until_ready();
  9006. // Connect with client certificate (using constructor with paths)
  9007. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9008. cli.enable_server_certificate_verification(false);
  9009. auto res = cli.Get("/test-pem-ca");
  9010. ASSERT_TRUE(res);
  9011. EXPECT_EQ(200, res->status);
  9012. EXPECT_EQ("ok", res->body);
  9013. svr.stop();
  9014. server_thread.join();
  9015. }
  9016. #endif
  9017. #ifdef _WIN32
  9018. TEST(CleanupTest, WSACleanup) {
  9019. int ret = WSACleanup();
  9020. ASSERT_EQ(0, ret);
  9021. }
  9022. #endif
  9023. #ifndef CPPHTTPLIB_SSL_ENABLED
  9024. TEST(NoSSLSupport, SimpleInterface) {
  9025. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9026. }
  9027. #endif
  9028. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9029. TEST(InvalidScheme, SimpleInterface) {
  9030. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9031. }
  9032. #endif
  9033. TEST(NoScheme, SimpleInterface) {
  9034. Client cli("yahoo.com:80");
  9035. ASSERT_TRUE(cli.is_valid());
  9036. }
  9037. TEST(SendAPI, SimpleInterface_Online) {
  9038. Client cli("http://yahoo.com");
  9039. Request req;
  9040. req.method = "GET";
  9041. req.path = "/";
  9042. auto res = cli.send(req);
  9043. ASSERT_TRUE(res);
  9044. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9045. }
  9046. TEST(SendAPI, WithParamsInRequest) {
  9047. Server svr;
  9048. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9049. EXPECT_TRUE(req.has_param("test"));
  9050. EXPECT_EQ("test_value", req.get_param_value("test"));
  9051. });
  9052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9053. auto se = detail::scope_exit([&] {
  9054. svr.stop();
  9055. t.join();
  9056. ASSERT_FALSE(svr.is_running());
  9057. });
  9058. svr.wait_until_ready();
  9059. Client cli(HOST, PORT);
  9060. {
  9061. Request req;
  9062. req.method = "GET";
  9063. req.path = "/";
  9064. req.params.emplace("test", "test_value");
  9065. auto res = cli.send(req);
  9066. ASSERT_TRUE(res);
  9067. }
  9068. {
  9069. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9070. ASSERT_TRUE(res);
  9071. }
  9072. }
  9073. TEST(ClientImplMethods, GetSocketTest) {
  9074. httplib::Server svr;
  9075. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9076. res.status = StatusCode::OK_200;
  9077. });
  9078. auto port = svr.bind_to_any_port("127.0.0.1");
  9079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9080. auto se = detail::scope_exit([&] {
  9081. svr.stop();
  9082. thread.join();
  9083. ASSERT_FALSE(svr.is_running());
  9084. });
  9085. svr.wait_until_ready();
  9086. {
  9087. httplib::Client cli("127.0.0.1", port);
  9088. cli.set_keep_alive(true);
  9089. // Use the behavior of cpp-httplib of opening the connection
  9090. // only when the first request happens. If that changes,
  9091. // this test would be obsolete.
  9092. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9093. // This also implicitly tests the server. But other tests would fail much
  9094. // earlier than this one to be considered.
  9095. auto res = cli.Get("/");
  9096. ASSERT_TRUE(res);
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9099. }
  9100. }
  9101. #ifdef CPPHTTPLIB_SSL_ENABLED
  9102. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9103. Client cli("http://yahoo.com");
  9104. auto res = cli.Get("/");
  9105. ASSERT_TRUE(res);
  9106. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9107. cli.set_follow_location(true);
  9108. res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9112. }
  9113. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9114. Client cli("https://yahoo.com");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(res);
  9117. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9118. cli.set_follow_location(true);
  9119. res = cli.Get("/");
  9120. ASSERT_TRUE(res);
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9123. }
  9124. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9125. Client cli("https://yahoo.com");
  9126. auto res = cli.Get("/");
  9127. ASSERT_TRUE(res);
  9128. ASSERT_FALSE(!res);
  9129. ASSERT_TRUE(res);
  9130. ASSERT_FALSE(res == nullptr);
  9131. ASSERT_TRUE(res != nullptr);
  9132. EXPECT_EQ(Error::Success, res.error());
  9133. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9134. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9135. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9136. cli.set_follow_location(true);
  9137. res = cli.Get("/");
  9138. ASSERT_TRUE(res);
  9139. EXPECT_EQ(Error::Success, res.error());
  9140. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9141. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9142. EXPECT_EQ(StatusCode::OK_200, res->status);
  9143. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9144. }
  9145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9146. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9147. Client cli("https://cdnjs.cloudflare.com");
  9148. auto res =
  9149. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9150. ASSERT_TRUE(res);
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ(287630U, res->body.size());
  9153. EXPECT_EQ("application/javascript; charset=utf-8",
  9154. res->get_header_value("Content-Type"));
  9155. }
  9156. #endif
  9157. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9158. #undef REDIR_HOST // Silence compiler warning
  9159. #define REDIR_HOST "https://httpbingo.org"
  9160. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9161. Client cli(REDIR_HOST);
  9162. cli.set_follow_location(true);
  9163. auto res =
  9164. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9165. ASSERT_TRUE(res);
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9169. Client cli(REDIR_HOST);
  9170. cli.set_follow_location(true);
  9171. Params params;
  9172. params.emplace("url", "http://example.com");
  9173. params.emplace("status_code", "302");
  9174. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9175. ASSERT_TRUE(res);
  9176. EXPECT_EQ(StatusCode::OK_200, res->status);
  9177. }
  9178. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9179. Client cli(REDIR_HOST);
  9180. cli.set_follow_location(true);
  9181. Params params;
  9182. params.emplace("url", "http://example.com");
  9183. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9184. ASSERT_TRUE(res);
  9185. EXPECT_EQ(StatusCode::OK_200, res->status);
  9186. }
  9187. TEST(HttpToHttpsRedirectTest, CertFile) {
  9188. auto ssl_port = PORT + 1;
  9189. Server svr;
  9190. ASSERT_TRUE(svr.is_valid());
  9191. svr.Get("/index", [&](const Request &, Response &res) {
  9192. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9193. "/index");
  9194. svr.stop();
  9195. });
  9196. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9197. ASSERT_TRUE(ssl_svr.is_valid());
  9198. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9199. res.set_content("test", "text/plain");
  9200. ssl_svr.stop();
  9201. });
  9202. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9203. thread t2 =
  9204. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9205. auto se = detail::scope_exit([&] {
  9206. t2.join();
  9207. t.join();
  9208. ASSERT_FALSE(svr.is_running());
  9209. });
  9210. svr.wait_until_ready();
  9211. ssl_svr.wait_until_ready();
  9212. Client cli("127.0.0.1", PORT);
  9213. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9214. cli.enable_server_certificate_verification(true);
  9215. cli.set_follow_location(true);
  9216. cli.set_connection_timeout(30);
  9217. auto res = cli.Get("/index");
  9218. ASSERT_TRUE(res);
  9219. ASSERT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. TEST(SSLClientRedirectTest, CertFile) {
  9222. auto ssl_port = PORT + 1;
  9223. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9224. ASSERT_TRUE(ssl_svr1.is_valid());
  9225. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9226. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9227. "/index");
  9228. ssl_svr1.stop();
  9229. });
  9230. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9231. ASSERT_TRUE(ssl_svr2.is_valid());
  9232. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9233. res.set_content("test", "text/plain");
  9234. ssl_svr2.stop();
  9235. });
  9236. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9237. thread t2 =
  9238. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9239. auto se = detail::scope_exit([&] {
  9240. t2.join();
  9241. t.join();
  9242. ASSERT_FALSE(ssl_svr1.is_running());
  9243. });
  9244. ssl_svr1.wait_until_ready();
  9245. ssl_svr2.wait_until_ready();
  9246. SSLClient cli("127.0.0.1", PORT);
  9247. std::string cert;
  9248. read_file(SERVER_CERT2_FILE, cert);
  9249. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9250. cli.enable_server_certificate_verification(true);
  9251. cli.set_follow_location(true);
  9252. cli.set_connection_timeout(30);
  9253. auto res = cli.Get("/index");
  9254. ASSERT_TRUE(res);
  9255. ASSERT_EQ(StatusCode::OK_200, res->status);
  9256. }
  9257. #endif
  9258. #ifdef CPPHTTPLIB_SSL_ENABLED
  9259. // Test that set_ca_cert_store() skips system certs (consistent with
  9260. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9261. // should be trusted - system certs should NOT be loaded.
  9262. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9263. // Load a specific cert that is NOT a system CA cert
  9264. std::string cert;
  9265. read_file(SERVER_CERT2_FILE, cert);
  9266. SSLClient cli("google.com");
  9267. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9268. cli.enable_server_certificate_verification(true);
  9269. // This should FAIL because:
  9270. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9271. // 2. System certs should NOT be loaded when custom store is set
  9272. // If system certs WERE loaded, this would succeed
  9273. auto res = cli.Get("/");
  9274. ASSERT_FALSE(res);
  9275. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9276. }
  9277. TEST(MultipartFormDataTest, LargeData) {
  9278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9279. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9280. const ContentReader &content_reader) {
  9281. if (req.is_multipart_form_data()) {
  9282. std::vector<FormData> items;
  9283. content_reader(
  9284. [&](const FormData &file) {
  9285. items.push_back(file);
  9286. return true;
  9287. },
  9288. [&](const char *data, size_t data_length) {
  9289. items.back().content.append(data, data_length);
  9290. return true;
  9291. });
  9292. EXPECT_TRUE(std::string(items[0].name) == "document");
  9293. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9294. EXPECT_TRUE(items[0].filename == "2MB_data");
  9295. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9296. EXPECT_TRUE(items[1].name == "hello");
  9297. EXPECT_TRUE(items[1].content == "world");
  9298. EXPECT_TRUE(items[1].filename == "");
  9299. EXPECT_TRUE(items[1].content_type == "");
  9300. } else {
  9301. std::string body;
  9302. content_reader([&](const char *data, size_t data_length) {
  9303. body.append(data, data_length);
  9304. return true;
  9305. });
  9306. }
  9307. });
  9308. auto port = svr.bind_to_any_port(HOST);
  9309. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9310. auto se = detail::scope_exit([&] {
  9311. svr.stop();
  9312. t.join();
  9313. ASSERT_FALSE(svr.is_running());
  9314. });
  9315. svr.wait_until_ready();
  9316. {
  9317. std::string data(1024 * 1024 * 2, '.');
  9318. std::stringstream buffer;
  9319. buffer << data;
  9320. SSLClient cli(HOST, port);
  9321. cli.enable_server_certificate_verification(false);
  9322. UploadFormDataItems items{
  9323. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9324. {"hello", "world", "", ""},
  9325. };
  9326. auto res = cli.Post("/post", items);
  9327. ASSERT_TRUE(res);
  9328. ASSERT_EQ(StatusCode::OK_200, res->status);
  9329. }
  9330. }
  9331. TEST(MultipartFormDataTest, DataProviderItems) {
  9332. std::random_device seed_gen;
  9333. std::mt19937 random(seed_gen());
  9334. std::string rand1;
  9335. rand1.resize(1000);
  9336. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9337. std::string rand2;
  9338. rand2.resize(3000);
  9339. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9341. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9342. const ContentReader &content_reader) {
  9343. ASSERT_FALSE(req.is_multipart_form_data());
  9344. std::string body;
  9345. content_reader([&](const char *data, size_t data_length) {
  9346. body.append(data, data_length);
  9347. return true;
  9348. });
  9349. EXPECT_EQ(body, "");
  9350. });
  9351. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9352. const ContentReader &content_reader) {
  9353. ASSERT_TRUE(req.is_multipart_form_data());
  9354. std::vector<FormData> items;
  9355. content_reader(
  9356. [&](const FormData &file) {
  9357. items.push_back(file);
  9358. return true;
  9359. },
  9360. [&](const char *data, size_t data_length) {
  9361. items.back().content.append(data, data_length);
  9362. return true;
  9363. });
  9364. ASSERT_TRUE(items.size() == 2);
  9365. EXPECT_EQ(std::string(items[0].name), "name1");
  9366. EXPECT_EQ(items[0].content, "Testing123");
  9367. EXPECT_EQ(items[0].filename, "filename1");
  9368. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9369. EXPECT_EQ(items[1].name, "name2");
  9370. EXPECT_EQ(items[1].content, "Testing456");
  9371. EXPECT_EQ(items[1].filename, "");
  9372. EXPECT_EQ(items[1].content_type, "");
  9373. });
  9374. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9375. const ContentReader &content_reader) {
  9376. ASSERT_TRUE(req.is_multipart_form_data());
  9377. std::vector<FormData> items;
  9378. content_reader(
  9379. [&](const FormData &file) {
  9380. items.push_back(file);
  9381. return true;
  9382. },
  9383. [&](const char *data, size_t data_length) {
  9384. items.back().content.append(data, data_length);
  9385. return true;
  9386. });
  9387. ASSERT_TRUE(items.size() == 2);
  9388. EXPECT_EQ(items[0].name, "name3");
  9389. EXPECT_EQ(items[0].content, rand1);
  9390. EXPECT_EQ(items[0].filename, "filename3");
  9391. EXPECT_EQ(items[0].content_type, "");
  9392. EXPECT_EQ(items[1].name, "name4");
  9393. EXPECT_EQ(items[1].content, rand2);
  9394. EXPECT_EQ(items[1].filename, "filename4");
  9395. EXPECT_EQ(items[1].content_type, "");
  9396. });
  9397. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9398. const ContentReader &content_reader) {
  9399. ASSERT_TRUE(req.is_multipart_form_data());
  9400. std::vector<FormData> items;
  9401. content_reader(
  9402. [&](const FormData &file) {
  9403. items.push_back(file);
  9404. return true;
  9405. },
  9406. [&](const char *data, size_t data_length) {
  9407. items.back().content.append(data, data_length);
  9408. return true;
  9409. });
  9410. ASSERT_TRUE(items.size() == 4);
  9411. EXPECT_EQ(std::string(items[0].name), "name1");
  9412. EXPECT_EQ(items[0].content, "Testing123");
  9413. EXPECT_EQ(items[0].filename, "filename1");
  9414. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9415. EXPECT_EQ(items[1].name, "name2");
  9416. EXPECT_EQ(items[1].content, "Testing456");
  9417. EXPECT_EQ(items[1].filename, "");
  9418. EXPECT_EQ(items[1].content_type, "");
  9419. EXPECT_EQ(items[2].name, "name3");
  9420. EXPECT_EQ(items[2].content, rand1);
  9421. EXPECT_EQ(items[2].filename, "filename3");
  9422. EXPECT_EQ(items[2].content_type, "");
  9423. EXPECT_EQ(items[3].name, "name4");
  9424. EXPECT_EQ(items[3].content, rand2);
  9425. EXPECT_EQ(items[3].filename, "filename4");
  9426. EXPECT_EQ(items[3].content_type, "");
  9427. });
  9428. auto port = svr.bind_to_any_port("localhost");
  9429. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9430. auto se = detail::scope_exit([&] {
  9431. svr.stop();
  9432. t.join();
  9433. ASSERT_FALSE(svr.is_running());
  9434. });
  9435. svr.wait_until_ready();
  9436. {
  9437. SSLClient cli("localhost", port);
  9438. cli.enable_server_certificate_verification(false);
  9439. UploadFormDataItems items{
  9440. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9441. {"name2", "Testing456", "", ""}, // not a file
  9442. };
  9443. {
  9444. auto res = cli.Post("/post-none", {}, {}, {});
  9445. ASSERT_TRUE(res);
  9446. ASSERT_EQ(StatusCode::OK_200, res->status);
  9447. }
  9448. FormDataProviderItems providers;
  9449. {
  9450. auto res =
  9451. cli.Post("/post-items", {}, items, providers); // empty providers
  9452. ASSERT_TRUE(res);
  9453. ASSERT_EQ(StatusCode::OK_200, res->status);
  9454. }
  9455. providers.push_back({"name3",
  9456. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9457. // test the offset is given correctly at each step
  9458. if (!offset)
  9459. sink.os.write(rand1.data(), 30);
  9460. else if (offset == 30)
  9461. sink.os.write(rand1.data() + 30, 300);
  9462. else if (offset == 330)
  9463. sink.os.write(rand1.data() + 330, 670);
  9464. else if (offset == rand1.size())
  9465. sink.done();
  9466. return true;
  9467. },
  9468. "filename3",
  9469. {}});
  9470. providers.push_back({"name4",
  9471. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9472. // test the offset is given correctly at each step
  9473. if (!offset)
  9474. sink.os.write(rand2.data(), 2000);
  9475. else if (offset == 2000)
  9476. sink.os.write(rand2.data() + 2000, 1);
  9477. else if (offset == 2001)
  9478. sink.os.write(rand2.data() + 2001, 999);
  9479. else if (offset == rand2.size())
  9480. sink.done();
  9481. return true;
  9482. },
  9483. "filename4",
  9484. {}});
  9485. {
  9486. auto res = cli.Post("/post-providers", {}, {}, providers);
  9487. ASSERT_TRUE(res);
  9488. ASSERT_EQ(StatusCode::OK_200, res->status);
  9489. }
  9490. {
  9491. auto res = cli.Post("/post-both", {}, items, providers);
  9492. ASSERT_TRUE(res);
  9493. ASSERT_EQ(StatusCode::OK_200, res->status);
  9494. }
  9495. }
  9496. }
  9497. TEST(MultipartFormDataTest, BadHeader) {
  9498. Server svr;
  9499. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9500. res.set_content("ok", "text/plain");
  9501. });
  9502. thread t = thread([&] { svr.listen(HOST, PORT); });
  9503. auto se = detail::scope_exit([&] {
  9504. svr.stop();
  9505. t.join();
  9506. ASSERT_FALSE(svr.is_running());
  9507. });
  9508. svr.wait_until_ready();
  9509. const std::string body =
  9510. "This is the preamble. It is to be ignored, though it\r\n"
  9511. "is a handy place for composition agents to include an\r\n"
  9512. "explanatory note to non-MIME conformant readers.\r\n"
  9513. "\r\n"
  9514. "\r\n"
  9515. "--simple boundary\r\n"
  9516. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9517. ": BAD...\r\n"
  9518. "\r\n"
  9519. "value1\r\n"
  9520. "--simple boundary\r\n"
  9521. "Content-Disposition: form-data; name=\"field2\"; "
  9522. "filename=\"example.txt\"\r\n"
  9523. "\r\n"
  9524. "value2\r\n"
  9525. "--simple boundary--\r\n"
  9526. "This is the epilogue. It is also to be ignored.\r\n";
  9527. std::string content_type =
  9528. R"(multipart/form-data; boundary="simple boundary")";
  9529. Client cli(HOST, PORT);
  9530. auto res = cli.Post("/post", body, content_type.c_str());
  9531. ASSERT_TRUE(res);
  9532. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9533. }
  9534. TEST(MultipartFormDataTest, WithPreamble) {
  9535. Server svr;
  9536. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9537. res.set_content("ok", "text/plain");
  9538. });
  9539. thread t = thread([&] { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. const std::string body =
  9547. "This is the preamble. It is to be ignored, though it\r\n"
  9548. "is a handy place for composition agents to include an\r\n"
  9549. "explanatory note to non-MIME conformant readers.\r\n"
  9550. "\r\n"
  9551. "\r\n"
  9552. "--simple boundary\r\n"
  9553. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9554. "\r\n"
  9555. "value1\r\n"
  9556. "--simple boundary\r\n"
  9557. "Content-Disposition: form-data; name=\"field2\"; "
  9558. "filename=\"example.txt\"\r\n"
  9559. "\r\n"
  9560. "value2\r\n"
  9561. "--simple boundary--\r\n"
  9562. "This is the epilogue. It is also to be ignored.\r\n";
  9563. std::string content_type =
  9564. R"(multipart/form-data; boundary="simple boundary")";
  9565. Client cli(HOST, PORT);
  9566. auto res = cli.Post("/post", body, content_type.c_str());
  9567. ASSERT_TRUE(res);
  9568. EXPECT_EQ(StatusCode::OK_200, res->status);
  9569. }
  9570. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9572. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9573. const ContentReader &content_reader) {
  9574. if (req.is_multipart_form_data()) {
  9575. std::vector<FormData> items;
  9576. content_reader(
  9577. [&](const FormData &file) {
  9578. items.push_back(file);
  9579. return true;
  9580. },
  9581. [&](const char *data, size_t data_length) {
  9582. items.back().content.append(data, data_length);
  9583. return true;
  9584. });
  9585. EXPECT_TRUE(std::string(items[0].name) == "document");
  9586. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9587. EXPECT_TRUE(items[0].filename == "2MB_data");
  9588. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9589. EXPECT_TRUE(items[1].name == "hello");
  9590. EXPECT_TRUE(items[1].content == "world");
  9591. EXPECT_TRUE(items[1].filename == "");
  9592. EXPECT_TRUE(items[1].content_type == "");
  9593. } else {
  9594. std::string body;
  9595. content_reader([&](const char *data, size_t data_length) {
  9596. body.append(data, data_length);
  9597. return true;
  9598. });
  9599. }
  9600. });
  9601. auto port = svr.bind_to_any_port("localhost");
  9602. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. ASSERT_FALSE(svr.is_running());
  9607. });
  9608. svr.wait_until_ready();
  9609. {
  9610. std::string data(1024 * 1024 * 2, '.');
  9611. std::stringstream buffer;
  9612. buffer << data;
  9613. SSLClient cli("localhost", port);
  9614. cli.enable_server_certificate_verification(false);
  9615. UploadFormDataItems items{
  9616. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9617. {"hello", "world", "", ""},
  9618. };
  9619. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9620. ASSERT_TRUE(res);
  9621. ASSERT_EQ(StatusCode::OK_200, res->status);
  9622. }
  9623. }
  9624. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9625. std::string data(1024 * 1024 * 2, '&');
  9626. std::stringstream buffer;
  9627. buffer << data;
  9628. Client cli("https://localhost:8080");
  9629. UploadFormDataItems items{
  9630. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9631. {"hello", "world", "", ""},
  9632. };
  9633. for (const char &c : " \t\r\n") {
  9634. auto res =
  9635. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9636. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9637. ASSERT_FALSE(res);
  9638. }
  9639. }
  9640. TEST(MultipartFormDataTest, PutFormData) {
  9641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9642. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9643. const ContentReader &content_reader) {
  9644. if (req.is_multipart_form_data()) {
  9645. std::vector<FormData> items;
  9646. content_reader(
  9647. [&](const FormData &file) {
  9648. items.push_back(file);
  9649. return true;
  9650. },
  9651. [&](const char *data, size_t data_length) {
  9652. items.back().content.append(data, data_length);
  9653. return true;
  9654. });
  9655. EXPECT_TRUE(std::string(items[0].name) == "document");
  9656. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9657. EXPECT_TRUE(items[0].filename == "2MB_data");
  9658. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9659. EXPECT_TRUE(items[1].name == "hello");
  9660. EXPECT_TRUE(items[1].content == "world");
  9661. EXPECT_TRUE(items[1].filename == "");
  9662. EXPECT_TRUE(items[1].content_type == "");
  9663. } else {
  9664. std::string body;
  9665. content_reader([&](const char *data, size_t data_length) {
  9666. body.append(data, data_length);
  9667. return true;
  9668. });
  9669. }
  9670. });
  9671. auto port = svr.bind_to_any_port("localhost");
  9672. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9673. auto se = detail::scope_exit([&] {
  9674. svr.stop();
  9675. t.join();
  9676. ASSERT_FALSE(svr.is_running());
  9677. });
  9678. svr.wait_until_ready();
  9679. {
  9680. std::string data(1024 * 1024 * 2, '&');
  9681. std::stringstream buffer;
  9682. buffer << data;
  9683. SSLClient cli("localhost", port);
  9684. cli.enable_server_certificate_verification(false);
  9685. UploadFormDataItems items{
  9686. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9687. {"hello", "world", "", ""},
  9688. };
  9689. auto res = cli.Put("/put", items);
  9690. ASSERT_TRUE(res);
  9691. ASSERT_EQ(StatusCode::OK_200, res->status);
  9692. }
  9693. }
  9694. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9696. svr.Put("/put_customboundary",
  9697. [&](const Request &req, const Response & /*res*/,
  9698. const ContentReader &content_reader) {
  9699. if (req.is_multipart_form_data()) {
  9700. std::vector<FormData> items;
  9701. content_reader(
  9702. [&](const FormData &file) {
  9703. items.push_back(file);
  9704. return true;
  9705. },
  9706. [&](const char *data, size_t data_length) {
  9707. items.back().content.append(data, data_length);
  9708. return true;
  9709. });
  9710. EXPECT_TRUE(std::string(items[0].name) == "document");
  9711. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9712. EXPECT_TRUE(items[0].filename == "2MB_data");
  9713. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9714. EXPECT_TRUE(items[1].name == "hello");
  9715. EXPECT_TRUE(items[1].content == "world");
  9716. EXPECT_TRUE(items[1].filename == "");
  9717. EXPECT_TRUE(items[1].content_type == "");
  9718. } else {
  9719. std::string body;
  9720. content_reader([&](const char *data, size_t data_length) {
  9721. body.append(data, data_length);
  9722. return true;
  9723. });
  9724. }
  9725. });
  9726. auto port = svr.bind_to_any_port("localhost");
  9727. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9728. auto se = detail::scope_exit([&] {
  9729. svr.stop();
  9730. t.join();
  9731. ASSERT_FALSE(svr.is_running());
  9732. });
  9733. svr.wait_until_ready();
  9734. {
  9735. std::string data(1024 * 1024 * 2, '&');
  9736. std::stringstream buffer;
  9737. buffer << data;
  9738. SSLClient cli("localhost", port);
  9739. cli.enable_server_certificate_verification(false);
  9740. UploadFormDataItems items{
  9741. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9742. {"hello", "world", "", ""},
  9743. };
  9744. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9745. ASSERT_TRUE(res);
  9746. ASSERT_EQ(StatusCode::OK_200, res->status);
  9747. }
  9748. }
  9749. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9750. std::string data(1024 * 1024 * 2, '&');
  9751. std::stringstream buffer;
  9752. buffer << data;
  9753. Client cli("https://localhost:8080");
  9754. cli.enable_server_certificate_verification(false);
  9755. UploadFormDataItems items{
  9756. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9757. {"hello", "world", "", ""},
  9758. };
  9759. for (const char &c : " \t\r\n") {
  9760. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9761. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9762. ASSERT_FALSE(res);
  9763. }
  9764. }
  9765. TEST(MultipartFormDataTest, AlternateFilename) {
  9766. auto handled = false;
  9767. Server svr;
  9768. svr.Post("/test", [&](const Request &req, Response &res) {
  9769. ASSERT_EQ(2u, req.form.files.size());
  9770. ASSERT_EQ(1u, req.form.fields.size());
  9771. // Test files
  9772. const auto &file1 = req.form.get_file("file1");
  9773. ASSERT_EQ("file1", file1.name);
  9774. ASSERT_EQ("A.txt", file1.filename);
  9775. ASSERT_EQ("text/plain", file1.content_type);
  9776. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9777. const auto &file2 = req.form.get_file("file2");
  9778. ASSERT_EQ("file2", file2.name);
  9779. ASSERT_EQ("a.html", file2.filename);
  9780. ASSERT_EQ("text/html", file2.content_type);
  9781. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9782. file2.content);
  9783. // Test text field
  9784. const auto &text = req.form.get_field("text");
  9785. ASSERT_EQ("text default", text);
  9786. res.set_content("ok", "text/plain");
  9787. handled = true;
  9788. });
  9789. thread t = thread([&] { svr.listen(HOST, PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. t.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. ASSERT_TRUE(handled);
  9795. });
  9796. svr.wait_until_ready();
  9797. auto req = "POST /test HTTP/1.1\r\n"
  9798. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9799. "Content-Length: 399\r\n"
  9800. "\r\n"
  9801. "----------\r\n"
  9802. "Content-Disposition: form-data; name=\"text\"\r\n"
  9803. "\r\n"
  9804. "text default\r\n"
  9805. "----------\r\n"
  9806. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9807. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9808. "Content-Type: text/plain\r\n"
  9809. "\r\n"
  9810. "Content of a.txt.\r\n"
  9811. "\r\n"
  9812. "----------\r\n"
  9813. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9814. "\"a.html\"\r\n"
  9815. "Content-Type: text/html\r\n"
  9816. "\r\n"
  9817. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9818. "\r\n"
  9819. "------------\r\n";
  9820. ASSERT_TRUE(send_request(1, req));
  9821. }
  9822. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9823. auto handled = false;
  9824. Server svr;
  9825. svr.Post("/test", [&](const Request &req, Response &res) {
  9826. // Case-insensitive "utf-8''" prefix with a long value
  9827. const auto &file = req.form.get_file("file1");
  9828. ASSERT_EQ("file1", file.name);
  9829. // 8000 chars exercises both the Content-Disposition parser and the
  9830. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9831. // Prior to the fix, std::regex_match on this header would cause O(N)
  9832. // stack recursion in libstdc++, leading to SIGSEGV.
  9833. std::string expected_filename(8000, 'A');
  9834. ASSERT_EQ(expected_filename, file.filename);
  9835. res.set_content("ok", "text/plain");
  9836. handled = true;
  9837. });
  9838. thread t = thread([&] { svr.listen(HOST, PORT); });
  9839. auto se = detail::scope_exit([&] {
  9840. svr.stop();
  9841. t.join();
  9842. ASSERT_FALSE(svr.is_running());
  9843. ASSERT_TRUE(handled);
  9844. });
  9845. svr.wait_until_ready();
  9846. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9847. // Regression test for GHSA-qq6v-r583-3h69
  9848. std::string long_filename(8000, 'A');
  9849. std::string body = "----------\r\n"
  9850. "Content-Disposition: form-data; name=\"file1\"; "
  9851. "filename*=\"Utf-8''" +
  9852. long_filename +
  9853. "\"\r\n"
  9854. "\r\n"
  9855. "hello\r\n"
  9856. "------------\r\n";
  9857. auto req = "POST /test HTTP/1.1\r\n"
  9858. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9859. "Content-Length: " +
  9860. std::to_string(body.size()) + "\r\n\r\n" + body;
  9861. ASSERT_TRUE(send_request(1, req));
  9862. }
  9863. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9864. auto handled = false;
  9865. Server svr;
  9866. svr.Post("/test", [&](const Request &req, Response &) {
  9867. ASSERT_EQ(2u, req.form.fields.size());
  9868. const auto &text1 = req.form.get_field("text1");
  9869. ASSERT_EQ("text1", text1);
  9870. const auto &text2 = req.form.get_field("text2");
  9871. ASSERT_EQ("text2", text2);
  9872. handled = true;
  9873. });
  9874. thread t = thread([&] { svr.listen(HOST, PORT); });
  9875. auto se = detail::scope_exit([&] {
  9876. svr.stop();
  9877. t.join();
  9878. ASSERT_FALSE(svr.is_running());
  9879. ASSERT_TRUE(handled);
  9880. });
  9881. svr.wait_until_ready();
  9882. auto req = "POST /test HTTP/1.1\r\n"
  9883. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9884. "Content-Length: 146\r\n"
  9885. "\r\n----------\r\n"
  9886. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9887. "\r\n"
  9888. "text1"
  9889. "\r\n----------\r\n"
  9890. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9891. "\r\n"
  9892. "text2"
  9893. "\r\n------------";
  9894. std::string response;
  9895. ASSERT_TRUE(send_request(1, req, &response));
  9896. ASSERT_EQ("200", response.substr(9, 3));
  9897. }
  9898. TEST(MultipartFormDataTest, ContentLength) {
  9899. auto handled = false;
  9900. Server svr;
  9901. svr.Post("/test", [&](const Request &req, Response &) {
  9902. ASSERT_EQ(2u, req.form.fields.size());
  9903. const auto &text1 = req.form.get_field("text1");
  9904. ASSERT_EQ("text1", text1);
  9905. const auto &text2 = req.form.get_field("text2");
  9906. ASSERT_EQ("text2", text2);
  9907. handled = true;
  9908. });
  9909. thread t = thread([&] { svr.listen(HOST, PORT); });
  9910. auto se = detail::scope_exit([&] {
  9911. svr.stop();
  9912. t.join();
  9913. ASSERT_FALSE(svr.is_running());
  9914. ASSERT_TRUE(handled);
  9915. });
  9916. svr.wait_until_ready();
  9917. auto req = "POST /test HTTP/1.1\r\n"
  9918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9919. "Content-Length: 167\r\n"
  9920. "\r\n----------\r\n"
  9921. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9922. "Content-Length: 5\r\n"
  9923. "\r\n"
  9924. "text1"
  9925. "\r\n----------\r\n"
  9926. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9927. "\r\n"
  9928. "text2"
  9929. "\r\n------------\r\n";
  9930. std::string response;
  9931. ASSERT_TRUE(send_request(1, req, &response));
  9932. ASSERT_EQ("200", response.substr(9, 3));
  9933. }
  9934. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9935. auto handled = false;
  9936. Server svr;
  9937. svr.Post("/test", [&](const Request &req, Response &) {
  9938. ASSERT_EQ(2u, req.form.fields.size());
  9939. const auto &text1 = req.form.get_field("text1");
  9940. ASSERT_EQ("text1", text1);
  9941. // TODO: Add header access for text fields if needed
  9942. const auto &text2 = req.form.get_field("text2");
  9943. ASSERT_EQ("text2", text2);
  9944. // TODO: Header access for text fields needs to be implemented
  9945. // auto &headers = it->second.headers;
  9946. // ASSERT_EQ(3U, headers.size());
  9947. // auto custom_header = headers.find("x-whatever");
  9948. // ASSERT_TRUE(custom_header != headers.end());
  9949. // ASSERT_NE("customvalue", custom_header->second);
  9950. // ASSERT_EQ("CustomValue", custom_header->second);
  9951. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9952. handled = true;
  9953. });
  9954. thread t = thread([&] { svr.listen(HOST, PORT); });
  9955. auto se = detail::scope_exit([&] {
  9956. svr.stop();
  9957. t.join();
  9958. ASSERT_FALSE(svr.is_running());
  9959. ASSERT_TRUE(handled);
  9960. });
  9961. svr.wait_until_ready();
  9962. auto req = "POST /test HTTP/1.1\r\n"
  9963. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9964. "Content-Length: 232\r\n"
  9965. "\r\n----------\r\n"
  9966. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9967. "Content-Length: 5\r\n"
  9968. "X-Test: 1\r\n"
  9969. "\r\n"
  9970. "text1"
  9971. "\r\n----------\r\n"
  9972. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9973. "Content-Type: text/plain\r\n"
  9974. "X-Whatever: CustomValue\r\n"
  9975. "\r\n"
  9976. "text2"
  9977. "\r\n------------\r\n"
  9978. "That should be disregarded. Not even read";
  9979. std::string response;
  9980. ASSERT_TRUE(send_request(1, req, &response));
  9981. ASSERT_EQ("200", response.substr(9, 3));
  9982. }
  9983. TEST(MultipartFormDataTest, LargeHeader) {
  9984. auto handled = false;
  9985. Server svr;
  9986. svr.Post("/test", [&](const Request &req, Response &) {
  9987. ASSERT_EQ(1u, req.form.fields.size());
  9988. const auto &text = req.form.get_field("name1");
  9989. ASSERT_EQ("text1", text);
  9990. handled = true;
  9991. });
  9992. thread t = thread([&] { svr.listen(HOST, PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. t.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. ASSERT_TRUE(handled);
  9998. });
  9999. svr.wait_until_ready();
  10000. auto boundary = std::string("cpp-httplib-multipart-data");
  10001. std::string content = "--" + boundary +
  10002. "\r\n"
  10003. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10004. "\r\n"
  10005. "text1\r\n"
  10006. "--" +
  10007. boundary + "--\r\n";
  10008. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10009. "Content-Type: multipart/form-data;boundary=" +
  10010. boundary +
  10011. "\r\n"
  10012. "Content-Length: " +
  10013. std::to_string(content.size()) +
  10014. "\r\n"
  10015. "Dummy-Header: ";
  10016. std::string header_suffix = "\r\n"
  10017. "\r\n";
  10018. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10019. size_t header_dummy_size =
  10020. read_buff_size -
  10021. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10022. auto header_dummy = std::string(header_dummy_size, '@');
  10023. auto req = header_prefix + header_dummy + header_suffix + content;
  10024. std::string response;
  10025. ASSERT_TRUE(send_request(1, req, &response));
  10026. ASSERT_EQ("200", response.substr(9, 3));
  10027. }
  10028. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10029. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10030. // (not chunked Transfer-Encoding) after the streaming refactor.
  10031. auto handled = false;
  10032. Server svr;
  10033. svr.Post("/upload", [&](const Request &req, Response &res) {
  10034. auto cl_it = req.headers.find("Content-Length");
  10035. EXPECT_TRUE(cl_it != req.headers.end());
  10036. auto te_it = req.headers.find("Transfer-Encoding");
  10037. EXPECT_TRUE(te_it == req.headers.end());
  10038. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10039. res.set_content("ok", "text/plain");
  10040. handled = true;
  10041. });
  10042. auto port = svr.bind_to_any_port(HOST);
  10043. auto t = thread([&] { svr.listen_after_bind(); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. t.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. ASSERT_TRUE(handled);
  10049. });
  10050. svr.wait_until_ready();
  10051. UploadFormDataItems items = {
  10052. {"field1", "hello", "", "text/plain"},
  10053. {"file1", "world", "test.txt", "application/octet-stream"},
  10054. };
  10055. Client cli(HOST, port);
  10056. auto res = cli.Post("/upload", {}, items);
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::OK_200, res->status);
  10059. }
  10060. TEST(MultipartFormDataTest, MakeFileProvider) {
  10061. // Verify make_file_provider sends a file's contents correctly.
  10062. const std::string file_content(4096, 'Z');
  10063. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10064. {
  10065. std::ofstream ofs(tmp_path, std::ios::binary);
  10066. ofs.write(file_content.data(),
  10067. static_cast<std::streamsize>(file_content.size()));
  10068. }
  10069. auto handled = false;
  10070. Server svr;
  10071. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10072. const ContentReader &content_reader) {
  10073. ASSERT_TRUE(req.is_multipart_form_data());
  10074. std::vector<FormData> items;
  10075. content_reader(
  10076. [&](const FormData &file) {
  10077. items.push_back(file);
  10078. return true;
  10079. },
  10080. [&](const char *data, size_t data_length) {
  10081. items.back().content.append(data, data_length);
  10082. return true;
  10083. });
  10084. ASSERT_EQ(1u, items.size());
  10085. EXPECT_EQ("myfile", items[0].name);
  10086. EXPECT_EQ("data.bin", items[0].filename);
  10087. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10088. EXPECT_EQ(file_content, items[0].content);
  10089. handled = true;
  10090. });
  10091. auto port = svr.bind_to_any_port(HOST);
  10092. auto t = thread([&] { svr.listen_after_bind(); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. t.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. ASSERT_TRUE(handled);
  10098. std::remove(tmp_path.c_str());
  10099. });
  10100. svr.wait_until_ready();
  10101. FormDataProviderItems providers;
  10102. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10103. "application/octet-stream"));
  10104. Client cli(HOST, port);
  10105. auto res = cli.Post("/upload", {}, {}, providers);
  10106. ASSERT_TRUE(res);
  10107. EXPECT_EQ(StatusCode::OK_200, res->status);
  10108. }
  10109. TEST(MakeFileBodyTest, Basic) {
  10110. const std::string file_content(4096, 'Z');
  10111. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10112. {
  10113. std::ofstream ofs(tmp_path, std::ios::binary);
  10114. ofs.write(file_content.data(),
  10115. static_cast<std::streamsize>(file_content.size()));
  10116. }
  10117. auto handled = false;
  10118. Server svr;
  10119. svr.Post("/upload", [&](const Request &req, Response &res) {
  10120. EXPECT_EQ(file_content, req.body);
  10121. handled = true;
  10122. res.status = StatusCode::OK_200;
  10123. });
  10124. auto port = svr.bind_to_any_port(HOST);
  10125. auto t = thread([&] { svr.listen_after_bind(); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. ASSERT_TRUE(handled);
  10131. std::remove(tmp_path.c_str());
  10132. });
  10133. svr.wait_until_ready();
  10134. auto fb = make_file_body(tmp_path);
  10135. ASSERT_GT(fb.first, 0u);
  10136. Client cli(HOST, port);
  10137. auto res =
  10138. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10139. ASSERT_TRUE(res);
  10140. EXPECT_EQ(StatusCode::OK_200, res->status);
  10141. }
  10142. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10143. static constexpr unsigned int number_of_tasks{1000000};
  10144. std::atomic_uint count{0};
  10145. std::unique_ptr<TaskQueue> task_queue{
  10146. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10147. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10148. auto queued = task_queue->enqueue(
  10149. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10150. EXPECT_TRUE(queued);
  10151. }
  10152. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10153. task_queue->shutdown();
  10154. #else
  10155. EXPECT_NO_THROW(task_queue->shutdown());
  10156. #endif
  10157. EXPECT_EQ(number_of_tasks, count.load());
  10158. }
  10159. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10160. static constexpr unsigned int number_of_tasks{1000000};
  10161. static constexpr unsigned int qlimit{2};
  10162. unsigned int queued_count{0};
  10163. std::atomic_uint count{0};
  10164. std::unique_ptr<TaskQueue> task_queue{
  10165. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10166. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10167. if (task_queue->enqueue(
  10168. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10169. queued_count++;
  10170. }
  10171. }
  10172. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10173. task_queue->shutdown();
  10174. #else
  10175. EXPECT_NO_THROW(task_queue->shutdown());
  10176. #endif
  10177. EXPECT_EQ(queued_count, count.load());
  10178. EXPECT_TRUE(queued_count <= number_of_tasks);
  10179. EXPECT_TRUE(queued_count >= qlimit);
  10180. }
  10181. TEST(TaskQueueTest, MaxQueuedRequests) {
  10182. static constexpr unsigned int qlimit{3};
  10183. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10184. std::condition_variable sem_cv;
  10185. std::mutex sem_mtx;
  10186. int credits = 0;
  10187. bool queued;
  10188. /* Fill up the queue with tasks that will block until we give them credits to
  10189. * complete. */
  10190. for (unsigned int n = 0; n <= qlimit;) {
  10191. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10192. std::unique_lock<std::mutex> lock(sem_mtx);
  10193. while (credits <= 0) {
  10194. sem_cv.wait(lock);
  10195. }
  10196. /* Consume the credit and signal the test code if they are all gone. */
  10197. if (--credits == 0) { sem_cv.notify_one(); }
  10198. });
  10199. if (n < qlimit) {
  10200. /* The first qlimit enqueues must succeed. */
  10201. EXPECT_TRUE(queued);
  10202. } else {
  10203. /* The last one will succeed only when the worker thread
  10204. * starts and dequeues the first blocking task. Although
  10205. * not necessary for the correctness of this test, we sleep for
  10206. * a short while to avoid busy waiting. */
  10207. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10208. }
  10209. if (queued) { n++; }
  10210. }
  10211. /* Further enqueues must fail since the queue is full. */
  10212. for (auto i = 0; i < 4; i++) {
  10213. queued = task_queue->enqueue([] {});
  10214. EXPECT_FALSE(queued);
  10215. }
  10216. /* Give the credits to allow the previous tasks to complete. */
  10217. {
  10218. std::unique_lock<std::mutex> lock(sem_mtx);
  10219. credits += qlimit + 1;
  10220. }
  10221. sem_cv.notify_all();
  10222. /* Wait for all the credits to be consumed. */
  10223. {
  10224. std::unique_lock<std::mutex> lock(sem_mtx);
  10225. while (credits > 0) {
  10226. sem_cv.wait(lock);
  10227. }
  10228. }
  10229. /* Check that we are able again to enqueue at least qlimit tasks. */
  10230. for (unsigned int i = 0; i < qlimit; i++) {
  10231. queued = task_queue->enqueue([] {});
  10232. EXPECT_TRUE(queued);
  10233. }
  10234. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10235. task_queue->shutdown();
  10236. #else
  10237. EXPECT_NO_THROW(task_queue->shutdown());
  10238. #endif
  10239. }
  10240. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10241. Server svr;
  10242. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10243. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10244. });
  10245. svr.Get("/hello", [](const Request &req, Response &res) {
  10246. res.set_content(req.get_param_value("key"), "text/plain");
  10247. });
  10248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. thread.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. {
  10256. Client cli(HOST, PORT);
  10257. cli.set_follow_location(true);
  10258. auto res = cli.Get("/");
  10259. ASSERT_TRUE(res);
  10260. EXPECT_EQ(StatusCode::OK_200, res->status);
  10261. EXPECT_EQ("val&key2=val2", res->body);
  10262. }
  10263. }
  10264. #endif
  10265. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10266. Server svr;
  10267. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10268. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10269. });
  10270. svr.Get("/hello", [](const Request &req, Response &res) {
  10271. res.set_content(req.get_param_value("key"), "text/plain");
  10272. });
  10273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10274. auto se = detail::scope_exit([&] {
  10275. svr.stop();
  10276. thread.join();
  10277. ASSERT_FALSE(svr.is_running());
  10278. });
  10279. svr.wait_until_ready();
  10280. {
  10281. Client cli(HOST, PORT);
  10282. cli.set_follow_location(true);
  10283. auto res = cli.Get("/");
  10284. ASSERT_TRUE(res);
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10287. }
  10288. }
  10289. #ifdef CPPHTTPLIB_SSL_ENABLED
  10290. TEST(RedirectTest, Issue2185_Online) {
  10291. SSLClient client("github.com");
  10292. client.set_follow_location(true);
  10293. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10294. "Coollab-Windows.zip");
  10295. ASSERT_TRUE(res);
  10296. EXPECT_EQ(StatusCode::OK_200, res->status);
  10297. EXPECT_EQ(9920427U, res->body.size());
  10298. }
  10299. #endif
  10300. TEST(VulnerabilityTest, CRLFInjection) {
  10301. Server svr;
  10302. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10303. res.set_content("Hello 1", "text/plain");
  10304. });
  10305. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10306. res.set_content("Hello 2", "text/plain");
  10307. });
  10308. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10309. res.set_content("Hello 3", "text/plain");
  10310. });
  10311. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10312. res.set_content("Hello 4", "text/plain");
  10313. });
  10314. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10315. for (const auto &x : req.headers) {
  10316. auto key = x.first;
  10317. EXPECT_STRNE("evil", key.c_str());
  10318. }
  10319. });
  10320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10321. auto se = detail::scope_exit([&] {
  10322. svr.stop();
  10323. thread.join();
  10324. ASSERT_FALSE(svr.is_running());
  10325. });
  10326. svr.wait_until_ready();
  10327. {
  10328. Client cli(HOST, PORT);
  10329. cli.Post("/test1", "A=B",
  10330. "application/x-www-form-urlencoded\r\nevil: hello1");
  10331. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10332. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10333. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10334. }
  10335. }
  10336. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10337. auto server_thread = std::thread([] {
  10338. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10339. default_socket_options(srv);
  10340. sockaddr_in addr{};
  10341. addr.sin_family = AF_INET;
  10342. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10343. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10344. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10345. ::listen(srv, 1);
  10346. sockaddr_in cli_addr{};
  10347. socklen_t cli_len = sizeof(cli_addr);
  10348. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10349. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10350. std::string buf_all;
  10351. char buf[2048];
  10352. ssize_t n;
  10353. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10354. buf_all.append(buf, static_cast<size_t>(n));
  10355. size_t pos;
  10356. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10357. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10358. auto e = request_block.find("\r\n");
  10359. if (e != std::string::npos) {
  10360. auto request_line = request_block.substr(0, e);
  10361. std::string msg =
  10362. "CRLF injection detected in request line: '" + request_line + "'";
  10363. EXPECT_FALSE(true) << msg;
  10364. }
  10365. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10366. ::send(cli,
  10367. #ifdef _WIN32
  10368. static_cast<const char *>(resp.c_str()),
  10369. static_cast<int>(resp.size()),
  10370. #else
  10371. resp.c_str(), resp.size(),
  10372. #endif
  10373. 0);
  10374. buf_all.erase(0, pos + 4);
  10375. }
  10376. }
  10377. detail::close_socket(cli);
  10378. detail::close_socket(srv);
  10379. });
  10380. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10381. auto cli = Client("127.0.0.1", PORT + 1);
  10382. auto headers = Headers{
  10383. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10384. {"Connection", "keep-alive"}};
  10385. auto res = cli.Get("/hi", headers);
  10386. EXPECT_FALSE(res);
  10387. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10388. server_thread.join();
  10389. }
  10390. TEST(PathParamsTest, StaticMatch) {
  10391. const auto pattern = "/users/all";
  10392. detail::PathParamsMatcher matcher(pattern);
  10393. Request request;
  10394. request.path = "/users/all";
  10395. ASSERT_TRUE(matcher.match(request));
  10396. std::unordered_map<std::string, std::string> expected_params = {};
  10397. EXPECT_EQ(request.path_params, expected_params);
  10398. }
  10399. TEST(PathParamsTest, StaticMismatch) {
  10400. const auto pattern = "/users/all";
  10401. detail::PathParamsMatcher matcher(pattern);
  10402. Request request;
  10403. request.path = "/users/1";
  10404. ASSERT_FALSE(matcher.match(request));
  10405. }
  10406. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10407. const auto pattern = "/users/:id/subscriptions";
  10408. detail::PathParamsMatcher matcher(pattern);
  10409. Request request;
  10410. request.path = "/users/42/subscriptions";
  10411. ASSERT_TRUE(matcher.match(request));
  10412. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10413. EXPECT_EQ(request.path_params, expected_params);
  10414. }
  10415. TEST(PathParamsTest, SingleParamInTheEnd) {
  10416. const auto pattern = "/users/:id";
  10417. detail::PathParamsMatcher matcher(pattern);
  10418. Request request;
  10419. request.path = "/users/24";
  10420. ASSERT_TRUE(matcher.match(request));
  10421. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10422. EXPECT_EQ(request.path_params, expected_params);
  10423. }
  10424. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10425. const auto pattern = "/users/:id/";
  10426. detail::PathParamsMatcher matcher(pattern);
  10427. Request request;
  10428. request.path = "/users/42/";
  10429. ASSERT_TRUE(matcher.match(request));
  10430. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10431. EXPECT_EQ(request.path_params, expected_params);
  10432. }
  10433. TEST(PathParamsTest, EmptyParam) {
  10434. const auto pattern = "/users/:id/";
  10435. detail::PathParamsMatcher matcher(pattern);
  10436. Request request;
  10437. request.path = "/users//";
  10438. ASSERT_TRUE(matcher.match(request));
  10439. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10440. EXPECT_EQ(request.path_params, expected_params);
  10441. }
  10442. TEST(PathParamsTest, FragmentMismatch) {
  10443. const auto pattern = "/users/:id/";
  10444. detail::PathParamsMatcher matcher(pattern);
  10445. Request request;
  10446. request.path = "/admins/24/";
  10447. ASSERT_FALSE(matcher.match(request));
  10448. }
  10449. TEST(PathParamsTest, ExtraFragments) {
  10450. const auto pattern = "/users/:id";
  10451. detail::PathParamsMatcher matcher(pattern);
  10452. Request request;
  10453. request.path = "/users/42/subscriptions";
  10454. ASSERT_FALSE(matcher.match(request));
  10455. }
  10456. TEST(PathParamsTest, MissingTrailingParam) {
  10457. const auto pattern = "/users/:id";
  10458. detail::PathParamsMatcher matcher(pattern);
  10459. Request request;
  10460. request.path = "/users";
  10461. ASSERT_FALSE(matcher.match(request));
  10462. }
  10463. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10464. const auto pattern = "/users/:id/subscriptions";
  10465. detail::PathParamsMatcher matcher(pattern);
  10466. Request request;
  10467. request.path = "/users/subscriptions";
  10468. ASSERT_FALSE(matcher.match(request));
  10469. }
  10470. TEST(PathParamsTest, MultipleParams) {
  10471. const auto pattern = "/users/:userid/subscriptions/:subid";
  10472. detail::PathParamsMatcher matcher(pattern);
  10473. Request request;
  10474. request.path = "/users/42/subscriptions/2";
  10475. ASSERT_TRUE(matcher.match(request));
  10476. std::unordered_map<std::string, std::string> expected_params = {
  10477. {"userid", "42"}, {"subid", "2"}};
  10478. EXPECT_EQ(request.path_params, expected_params);
  10479. }
  10480. TEST(PathParamsTest, SequenceOfParams) {
  10481. const auto pattern = "/values/:x/:y/:z";
  10482. detail::PathParamsMatcher matcher(pattern);
  10483. Request request;
  10484. request.path = "/values/1/2/3";
  10485. ASSERT_TRUE(matcher.match(request));
  10486. std::unordered_map<std::string, std::string> expected_params = {
  10487. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10488. EXPECT_EQ(request.path_params, expected_params);
  10489. }
  10490. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10491. const auto pattern = "/prefix:suffix";
  10492. detail::PathParamsMatcher matcher(pattern);
  10493. Request request;
  10494. request.path = "/prefix:suffix";
  10495. ASSERT_TRUE(matcher.match(request));
  10496. const std::unordered_map<std::string, std::string> expected_params = {};
  10497. EXPECT_EQ(request.path_params, expected_params);
  10498. }
  10499. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10500. // If ipv6 regex working, regex match codepath is taken.
  10501. // else port will default to 80 in Client impl
  10502. int clientImplMagicPort = 80;
  10503. int port = 4321;
  10504. // above ports must be different to avoid false negative
  10505. EXPECT_NE(clientImplMagicPort, port);
  10506. std::string ipV6TestURL = "http://[ff06::c3]";
  10507. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10508. CLIENT_PRIVATE_KEY_FILE);
  10509. EXPECT_EQ(cli.port(), port);
  10510. }
  10511. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10512. auto file_path = "./www/dir/index.html";
  10513. auto dir_path = "./www/dir";
  10514. detail::FileStat stat_file(file_path);
  10515. EXPECT_TRUE(stat_file.is_file());
  10516. EXPECT_FALSE(stat_file.is_dir());
  10517. detail::FileStat stat_dir(dir_path);
  10518. EXPECT_FALSE(stat_dir.is_file());
  10519. EXPECT_TRUE(stat_dir.is_dir());
  10520. }
  10521. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10522. // IPv4 with default HTTP port (80)
  10523. EXPECT_EQ("example.com",
  10524. detail::make_host_and_port_string("example.com", 80, false));
  10525. // IPv4 with default HTTPS port (443)
  10526. EXPECT_EQ("example.com",
  10527. detail::make_host_and_port_string("example.com", 443, true));
  10528. // IPv4 with non-default HTTP port
  10529. EXPECT_EQ("example.com:8080",
  10530. detail::make_host_and_port_string("example.com", 8080, false));
  10531. // IPv4 with non-default HTTPS port
  10532. EXPECT_EQ("example.com:8443",
  10533. detail::make_host_and_port_string("example.com", 8443, true));
  10534. // IPv6 with default HTTP port (80)
  10535. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10536. // IPv6 with default HTTPS port (443)
  10537. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10538. // IPv6 with non-default HTTP port
  10539. EXPECT_EQ("[::1]:8080",
  10540. detail::make_host_and_port_string("::1", 8080, false));
  10541. // IPv6 with non-default HTTPS port
  10542. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10543. // IPv6 full address with default port
  10544. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10545. detail::make_host_and_port_string(
  10546. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10547. // IPv6 full address with non-default port
  10548. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10549. detail::make_host_and_port_string(
  10550. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10551. // IPv6 localhost with non-default port
  10552. EXPECT_EQ("[::1]:3000",
  10553. detail::make_host_and_port_string("::1", 3000, false));
  10554. // IPv6 with zone ID (link-local address) with default port
  10555. EXPECT_EQ("[fe80::1%eth0]",
  10556. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10557. // IPv6 with zone ID (link-local address) with non-default port
  10558. EXPECT_EQ("[fe80::1%eth0]:8080",
  10559. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10560. // Edge case: Port 443 with is_ssl=false (should add port)
  10561. EXPECT_EQ("example.com:443",
  10562. detail::make_host_and_port_string("example.com", 443, false));
  10563. // Edge case: Port 80 with is_ssl=true (should add port)
  10564. EXPECT_EQ("example.com:80",
  10565. detail::make_host_and_port_string("example.com", 80, true));
  10566. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10567. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10568. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10569. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10570. // Security fix: Already bracketed IPv6 should not get double brackets
  10571. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10572. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10573. EXPECT_EQ("[::1]:8080",
  10574. detail::make_host_and_port_string("[::1]", 8080, false));
  10575. EXPECT_EQ("[2001:db8::1]:8080",
  10576. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10577. EXPECT_EQ("[fe80::1%eth0]",
  10578. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10579. EXPECT_EQ("[fe80::1%eth0]:8080",
  10580. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10581. // Edge case: Empty host (should return as-is)
  10582. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10583. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10584. // This is a known limitation but shouldn't crash
  10585. EXPECT_EQ("[host:name]",
  10586. detail::make_host_and_port_string("host:name", 80, false));
  10587. // Port number edge cases (no validation, but should not crash)
  10588. EXPECT_EQ("example.com:0",
  10589. detail::make_host_and_port_string("example.com", 0, false));
  10590. EXPECT_EQ("example.com:-1",
  10591. detail::make_host_and_port_string("example.com", -1, false));
  10592. EXPECT_EQ("example.com:65535",
  10593. detail::make_host_and_port_string("example.com", 65535, false));
  10594. EXPECT_EQ("example.com:65536",
  10595. detail::make_host_and_port_string("example.com", 65536, false));
  10596. }
  10597. #ifdef CPPHTTPLIB_SSL_ENABLED
  10598. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10599. httplib::SSLClient cli("roblox.com", 443);
  10600. cli.set_follow_location(true);
  10601. auto res = cli.Get("/");
  10602. ASSERT_TRUE(res);
  10603. EXPECT_EQ(StatusCode::OK_200, res->status);
  10604. }
  10605. #endif
  10606. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10607. Server svr;
  10608. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10609. EXPECT_EQ(res.status, 400);
  10610. });
  10611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10612. auto se = detail::scope_exit([&] {
  10613. svr.stop();
  10614. thread.join();
  10615. ASSERT_FALSE(svr.is_running());
  10616. });
  10617. svr.wait_until_ready();
  10618. Client cli(HOST, PORT);
  10619. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10620. }
  10621. TEST(InvalidHeaderCharsTest, is_field_name) {
  10622. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10623. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10624. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10625. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10626. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10627. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10628. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10629. EXPECT_FALSE(detail::fields::is_field_name(""));
  10630. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10631. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10632. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10633. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10634. }
  10635. TEST(InvalidHeaderCharsTest, is_field_value) {
  10636. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10637. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10638. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10639. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10640. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10641. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10642. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10643. EXPECT_TRUE(detail::fields::is_field_value(""));
  10644. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10645. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10646. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10647. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10648. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10649. }
  10650. TEST(InvalidHeaderCharsTest, OnServer) {
  10651. Server svr;
  10652. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10653. std::string header = "Not Set";
  10654. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10655. res.set_header(header, "value");
  10656. res.set_content("Page Content Page Content", "text/plain");
  10657. });
  10658. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10659. std::string header = "Not Set";
  10660. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10661. res.set_header("X-Test", header);
  10662. res.set_content("Page Content Page Content", "text/plain");
  10663. });
  10664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10665. auto se = detail::scope_exit([&] {
  10666. svr.stop();
  10667. thread.join();
  10668. ASSERT_FALSE(svr.is_running());
  10669. });
  10670. svr.wait_until_ready();
  10671. Client cli(HOST, PORT);
  10672. {
  10673. auto res = cli.Get(
  10674. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10675. ASSERT_TRUE(res);
  10676. EXPECT_EQ("Page Content Page Content", res->body);
  10677. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10678. }
  10679. {
  10680. auto res = cli.Get(
  10681. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10682. ASSERT_TRUE(res);
  10683. EXPECT_EQ("Page Content Page Content", res->body);
  10684. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10685. }
  10686. }
  10687. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10688. auto handled = false;
  10689. Server svr;
  10690. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10691. thread t = thread([&] { svr.listen(HOST, PORT); });
  10692. auto se = detail::scope_exit([&] {
  10693. svr.stop();
  10694. t.join();
  10695. ASSERT_FALSE(svr.is_running());
  10696. ASSERT_FALSE(handled);
  10697. });
  10698. svr.wait_until_ready();
  10699. auto req = "POST /test HTTP/1.1\r\n"
  10700. "Content-Length: x\r\n"
  10701. "\r\n";
  10702. std::string response;
  10703. ASSERT_TRUE(send_request(1, req, &response));
  10704. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10705. response.substr(0, response.find("\r\n")));
  10706. }
  10707. #ifndef _WIN32
  10708. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10709. static constexpr char reject[] = "Unauthorized";
  10710. static constexpr char accept[] = "Upload accepted";
  10711. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10712. Server svr;
  10713. svr.set_expect_100_continue_handler(
  10714. [](const Request & /*req*/, Response &res) {
  10715. res.status = StatusCode::Unauthorized_401;
  10716. res.set_content(reject, "text/plain");
  10717. return res.status;
  10718. });
  10719. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10720. res.set_content(accept, "text/plain");
  10721. });
  10722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10723. auto se = detail::scope_exit([&] {
  10724. svr.stop();
  10725. thread.join();
  10726. ASSERT_FALSE(svr.is_running());
  10727. });
  10728. svr.wait_until_ready();
  10729. {
  10730. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10731. curl_easy_init(), &curl_easy_cleanup};
  10732. ASSERT_NE(curl, nullptr);
  10733. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10734. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10735. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10736. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10737. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10738. &curl_slist_free_all};
  10739. ASSERT_NE(list, nullptr);
  10740. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10741. struct read_data {
  10742. size_t read_size;
  10743. size_t total_size;
  10744. } data = {0, total_size};
  10745. using read_callback_t =
  10746. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10747. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10748. void *userdata) -> size_t {
  10749. read_data *data = (read_data *)userdata;
  10750. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10751. std::fill_n(ptr, size * nmemb, 'A');
  10752. data->read_size += size * nmemb;
  10753. return size * nmemb;
  10754. };
  10755. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10756. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10757. std::vector<char> buffer;
  10758. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10759. using write_callback_t =
  10760. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10761. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10762. void *userdata) -> size_t {
  10763. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10764. buffer->reserve(buffer->size() + size * nmemb + 1);
  10765. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10766. return size * nmemb;
  10767. };
  10768. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10769. {
  10770. const auto res = curl_easy_perform(curl.get());
  10771. ASSERT_EQ(res, CURLE_OK);
  10772. }
  10773. {
  10774. auto response_code = long{};
  10775. const auto res =
  10776. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10777. ASSERT_EQ(res, CURLE_OK);
  10778. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10779. }
  10780. {
  10781. auto dl = curl_off_t{};
  10782. const auto res =
  10783. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10784. ASSERT_EQ(res, CURLE_OK);
  10785. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10786. }
  10787. {
  10788. buffer.push_back('\0');
  10789. ASSERT_STRCASEEQ(buffer.data(), reject);
  10790. }
  10791. }
  10792. }
  10793. #endif
  10794. template <typename S, typename C>
  10795. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10796. svr.Get("/stream", [&](const Request &, Response &res) {
  10797. auto data = new std::string("01234567890123456789");
  10798. res.set_content_provider(
  10799. data->size(), "text/plain",
  10800. [&, data](size_t offset, size_t length, DataSink &sink) {
  10801. const size_t DATA_CHUNK_SIZE = 4;
  10802. const auto &d = *data;
  10803. std::this_thread::sleep_for(std::chrono::seconds(1));
  10804. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10805. return true;
  10806. },
  10807. [data](bool success) {
  10808. EXPECT_FALSE(success);
  10809. delete data;
  10810. });
  10811. });
  10812. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10813. auto i = new size_t(0);
  10814. res.set_content_provider(
  10815. "text/plain",
  10816. [i](size_t, DataSink &sink) {
  10817. if (*i < 5) {
  10818. std::this_thread::sleep_for(std::chrono::seconds(1));
  10819. sink.write("abcd", 4);
  10820. (*i)++;
  10821. } else {
  10822. sink.done();
  10823. }
  10824. return true;
  10825. },
  10826. [i](bool success) {
  10827. EXPECT_FALSE(success);
  10828. delete i;
  10829. });
  10830. });
  10831. svr.Get("/chunked", [&](const Request &, Response &res) {
  10832. auto i = new size_t(0);
  10833. res.set_chunked_content_provider(
  10834. "text/plain",
  10835. [i](size_t, DataSink &sink) {
  10836. if (*i < 5) {
  10837. std::this_thread::sleep_for(std::chrono::seconds(1));
  10838. sink.os << "abcd";
  10839. (*i)++;
  10840. } else {
  10841. sink.done();
  10842. }
  10843. return true;
  10844. },
  10845. [i](bool success) {
  10846. EXPECT_FALSE(success);
  10847. delete i;
  10848. });
  10849. });
  10850. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. listen_thread.join();
  10854. ASSERT_FALSE(svr.is_running());
  10855. });
  10856. svr.wait_until_ready();
  10857. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10858. {
  10859. auto start = std::chrono::steady_clock::now();
  10860. auto res = cli.Get("/stream");
  10861. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10862. std::chrono::steady_clock::now() - start)
  10863. .count();
  10864. ASSERT_FALSE(res);
  10865. EXPECT_EQ(Error::Read, res.error());
  10866. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10867. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10868. }
  10869. {
  10870. auto start = std::chrono::steady_clock::now();
  10871. auto res = cli.Get("/stream_without_length");
  10872. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10873. std::chrono::steady_clock::now() - start)
  10874. .count();
  10875. ASSERT_FALSE(res);
  10876. EXPECT_EQ(Error::Read, res.error());
  10877. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10878. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10879. }
  10880. {
  10881. auto start = std::chrono::steady_clock::now();
  10882. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10883. EXPECT_EQ("abcd", string(data, data_length));
  10884. return true;
  10885. });
  10886. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10887. std::chrono::steady_clock::now() - start)
  10888. .count();
  10889. ASSERT_FALSE(res);
  10890. EXPECT_EQ(Error::Read, res.error());
  10891. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10892. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10893. }
  10894. }
  10895. TEST(MaxTimeoutTest, ContentStream) {
  10896. time_t timeout = 2000;
  10897. time_t threshold = 200;
  10898. Server svr;
  10899. Client cli("localhost", PORT);
  10900. max_timeout_test(svr, cli, timeout, threshold);
  10901. }
  10902. #ifdef CPPHTTPLIB_SSL_ENABLED
  10903. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10904. time_t timeout = 2000;
  10905. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10907. SSLClient cli("localhost", PORT);
  10908. cli.enable_server_certificate_verification(false);
  10909. max_timeout_test(svr, cli, timeout, threshold);
  10910. }
  10911. #endif
  10912. class EventDispatcher {
  10913. public:
  10914. EventDispatcher() {}
  10915. bool wait_event(DataSink *sink) {
  10916. unique_lock<mutex> lk(m_);
  10917. int id = id_;
  10918. // Wait with timeout to prevent hanging if client disconnects
  10919. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10920. [&] { return cid_ == id; })) {
  10921. return false; // Timeout occurred
  10922. }
  10923. sink->write(message_.data(), message_.size());
  10924. return true;
  10925. }
  10926. void send_event(const string &message) {
  10927. lock_guard<mutex> lk(m_);
  10928. cid_ = id_++;
  10929. message_ = message;
  10930. cv_.notify_all();
  10931. }
  10932. private:
  10933. mutex m_;
  10934. condition_variable cv_;
  10935. atomic_int id_{0};
  10936. atomic_int cid_{-1};
  10937. string message_;
  10938. };
  10939. TEST(ClientInThreadTest, Issue2068) {
  10940. EventDispatcher ed;
  10941. Server svr;
  10942. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10943. res.set_chunked_content_provider("text/event-stream",
  10944. [&](size_t /*offset*/, DataSink &sink) {
  10945. return ed.wait_event(&sink);
  10946. });
  10947. });
  10948. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10949. svr.wait_until_ready();
  10950. thread event_thread([&] {
  10951. int id = 0;
  10952. while (svr.is_running()) {
  10953. this_thread::sleep_for(chrono::milliseconds(500));
  10954. std::stringstream ss;
  10955. ss << "data: " << id << "\n\n";
  10956. ed.send_event(ss.str());
  10957. id++;
  10958. }
  10959. });
  10960. auto se = detail::scope_exit([&] {
  10961. svr.stop();
  10962. listen_thread.join();
  10963. event_thread.join();
  10964. ASSERT_FALSE(svr.is_running());
  10965. });
  10966. {
  10967. auto client = detail::make_unique<Client>(HOST, PORT);
  10968. client->set_read_timeout(std::chrono::minutes(10));
  10969. std::atomic<bool> stop{false};
  10970. std::thread t([&] {
  10971. client->Get("/event1",
  10972. [&](const char *, size_t) -> bool { return !stop; });
  10973. });
  10974. std::this_thread::sleep_for(std::chrono::seconds(2));
  10975. stop = true;
  10976. client->stop();
  10977. t.join();
  10978. // Reset client after thread has finished
  10979. client.reset();
  10980. }
  10981. }
  10982. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10983. auto handled = false;
  10984. Server svr;
  10985. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10986. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. t.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. ASSERT_FALSE(handled);
  10992. });
  10993. svr.wait_until_ready();
  10994. // Two Content-Length headers with different values — must be rejected
  10995. auto req = "POST /test HTTP/1.1\r\n"
  10996. "Content-Length: 5\r\n"
  10997. "Content-Length: 10\r\n"
  10998. "\r\n"
  10999. "hello";
  11000. std::string response;
  11001. ASSERT_TRUE(send_request(1, req, &response));
  11002. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11003. response.substr(0, response.find("\r\n")));
  11004. }
  11005. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11006. auto handled = false;
  11007. Server svr;
  11008. svr.Post("/test", [&](const Request &, Response &res) {
  11009. handled = true;
  11010. res.set_content("ok", "text/plain");
  11011. });
  11012. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. t.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. ASSERT_TRUE(handled);
  11018. });
  11019. svr.wait_until_ready();
  11020. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11021. auto req = "POST /test HTTP/1.1\r\n"
  11022. "Content-Length: 5\r\n"
  11023. "Content-Length: 5\r\n"
  11024. "\r\n"
  11025. "hello";
  11026. std::string response;
  11027. ASSERT_TRUE(send_request(1, req, &response));
  11028. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11029. }
  11030. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11031. Server svr;
  11032. svr.Get("/", [](const Request &req, Response &res) {
  11033. EXPECT_EQ(2U, req.trailers.size());
  11034. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11035. // Denied
  11036. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11037. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11038. // Accepted
  11039. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11040. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11041. EXPECT_TRUE(req.has_trailer("X-World"));
  11042. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11043. res.set_content("ok", "text/plain");
  11044. });
  11045. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11046. auto se = detail::scope_exit([&] {
  11047. svr.stop();
  11048. t.join();
  11049. ASSERT_FALSE(svr.is_running());
  11050. });
  11051. svr.wait_until_ready();
  11052. const std::string req = "GET / HTTP/1.1\r\n"
  11053. "Transfer-Encoding: chunked\r\n"
  11054. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11055. "\r\n"
  11056. "0\r\n"
  11057. "Content-Length: 10\r\n"
  11058. "Host: internal.local\r\n"
  11059. "Content-Type: malicious/content\r\n"
  11060. "Cookie: any\r\n"
  11061. "Set-Cookie: any\r\n"
  11062. "X-Forwarded-For: attacker.com\r\n"
  11063. "X-Real-Ip: 1.1.1.1\r\n"
  11064. "X-Hello: hello\r\n"
  11065. "X-World: world\r\n"
  11066. "\r\n";
  11067. std::string res;
  11068. ASSERT_TRUE(send_request(1, req, &res));
  11069. }
  11070. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11071. Server svr;
  11072. std::string observed_remote_addr;
  11073. std::string observed_xff;
  11074. svr.Get("/ip", [&](const Request &req, Response &res) {
  11075. observed_remote_addr = req.remote_addr;
  11076. observed_xff = req.get_header_value("X-Forwarded-For");
  11077. res.set_content("ok", "text/plain");
  11078. });
  11079. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. t.join();
  11083. ASSERT_FALSE(svr.is_running());
  11084. });
  11085. svr.wait_until_ready();
  11086. Client cli(HOST, PORT);
  11087. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11088. ASSERT_TRUE(res);
  11089. EXPECT_EQ(StatusCode::OK_200, res->status);
  11090. EXPECT_EQ(observed_xff, "203.0.113.66");
  11091. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11092. observed_remote_addr == "127.0.0.1");
  11093. }
  11094. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11095. Server svr;
  11096. svr.set_trusted_proxies({"203.0.113.66"});
  11097. std::string observed_remote_addr;
  11098. std::string observed_xff;
  11099. svr.Get("/ip", [&](const Request &req, Response &res) {
  11100. observed_remote_addr = req.remote_addr;
  11101. observed_xff = req.get_header_value("X-Forwarded-For");
  11102. res.set_content("ok", "text/plain");
  11103. });
  11104. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11105. auto se = detail::scope_exit([&] {
  11106. svr.stop();
  11107. t.join();
  11108. ASSERT_FALSE(svr.is_running());
  11109. });
  11110. svr.wait_until_ready();
  11111. Client cli(HOST, PORT);
  11112. auto res = cli.Get("/ip");
  11113. ASSERT_TRUE(res);
  11114. EXPECT_EQ(StatusCode::OK_200, res->status);
  11115. EXPECT_EQ(observed_xff, "");
  11116. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11117. observed_remote_addr == "127.0.0.1");
  11118. }
  11119. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11120. Server svr;
  11121. svr.set_trusted_proxies({"203.0.113.66"});
  11122. std::string observed_remote_addr;
  11123. std::string observed_xff;
  11124. svr.Get("/ip", [&](const Request &req, Response &res) {
  11125. observed_remote_addr = req.remote_addr;
  11126. observed_xff = req.get_header_value("X-Forwarded-For");
  11127. res.set_content("ok", "text/plain");
  11128. });
  11129. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11130. auto se = detail::scope_exit([&] {
  11131. svr.stop();
  11132. t.join();
  11133. ASSERT_FALSE(svr.is_running());
  11134. });
  11135. svr.wait_until_ready();
  11136. Client cli(HOST, PORT);
  11137. auto res =
  11138. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11139. ASSERT_TRUE(res);
  11140. EXPECT_EQ(StatusCode::OK_200, res->status);
  11141. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11142. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11143. }
  11144. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11145. Server svr;
  11146. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11147. std::string observed_remote_addr;
  11148. std::string observed_xff;
  11149. svr.Get("/ip", [&](const Request &req, Response &res) {
  11150. observed_remote_addr = req.remote_addr;
  11151. observed_xff = req.get_header_value("X-Forwarded-For");
  11152. res.set_content("ok", "text/plain");
  11153. });
  11154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11155. auto se = detail::scope_exit([&] {
  11156. svr.stop();
  11157. t.join();
  11158. ASSERT_FALSE(svr.is_running());
  11159. });
  11160. svr.wait_until_ready();
  11161. Client cli(HOST, PORT);
  11162. auto res = cli.Get(
  11163. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11164. ASSERT_TRUE(res);
  11165. EXPECT_EQ(StatusCode::OK_200, res->status);
  11166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11168. }
  11169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11170. Server svr;
  11171. svr.set_trusted_proxies({"192.0.2.45"});
  11172. std::string observed_remote_addr;
  11173. std::string observed_xff;
  11174. svr.Get("/ip", [&](const Request &req, Response &res) {
  11175. observed_remote_addr = req.remote_addr;
  11176. observed_xff = req.get_header_value("X-Forwarded-For");
  11177. res.set_content("ok", "text/plain");
  11178. });
  11179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11180. auto se = detail::scope_exit([&] {
  11181. svr.stop();
  11182. t.join();
  11183. ASSERT_FALSE(svr.is_running());
  11184. });
  11185. svr.wait_until_ready();
  11186. Client cli(HOST, PORT);
  11187. auto res =
  11188. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11189. ASSERT_TRUE(res);
  11190. EXPECT_EQ(StatusCode::OK_200, res->status);
  11191. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11192. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11193. }
  11194. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11195. Server svr;
  11196. svr.set_trusted_proxies({"192.0.2.45"});
  11197. std::string observed_remote_addr;
  11198. std::string observed_xff;
  11199. svr.Get("/ip", [&](const Request &req, Response &res) {
  11200. observed_remote_addr = req.remote_addr;
  11201. observed_xff = req.get_header_value("X-Forwarded-For");
  11202. res.set_content("ok", "text/plain");
  11203. });
  11204. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11205. auto se = detail::scope_exit([&] {
  11206. svr.stop();
  11207. t.join();
  11208. ASSERT_FALSE(svr.is_running());
  11209. });
  11210. svr.wait_until_ready();
  11211. Client cli(HOST, PORT);
  11212. auto res = cli.Get(
  11213. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11214. ASSERT_TRUE(res);
  11215. EXPECT_EQ(StatusCode::OK_200, res->status);
  11216. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11217. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11218. }
  11219. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11220. Server svr;
  11221. svr.set_trusted_proxies({"192.0.2.45"});
  11222. std::string observed_remote_addr;
  11223. std::string observed_xff;
  11224. svr.Get("/ip", [&](const Request &req, Response &res) {
  11225. observed_remote_addr = req.remote_addr;
  11226. observed_xff = req.get_header_value("X-Forwarded-For");
  11227. res.set_content("ok", "text/plain");
  11228. });
  11229. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11230. auto se = detail::scope_exit([&] {
  11231. svr.stop();
  11232. t.join();
  11233. ASSERT_FALSE(svr.is_running());
  11234. });
  11235. svr.wait_until_ready();
  11236. std::string raw_req =
  11237. "GET /ip HTTP/1.1\r\n"
  11238. "Host: localhost\r\n"
  11239. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11240. "Connection: close\r\n"
  11241. "\r\n";
  11242. std::string out;
  11243. ASSERT_TRUE(send_request(5, raw_req, &out));
  11244. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11245. // Header parser trims surrounding whitespace of the header value
  11246. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11247. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11248. }
  11249. #ifndef _WIN32
  11250. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11251. Server svr;
  11252. svr.Post("/post", [&](const Request &req, Response &res) {
  11253. res.set_content(req.body, "text/plain");
  11254. });
  11255. svr.Put("/put", [&](const Request &req, Response &res) {
  11256. res.set_content(req.body, "text/plain");
  11257. });
  11258. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11259. res.set_content(req.body, "text/plain");
  11260. });
  11261. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11262. res.set_content(req.body, "text/plain");
  11263. });
  11264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11265. auto se = detail::scope_exit([&] {
  11266. svr.stop();
  11267. t.join();
  11268. ASSERT_FALSE(svr.is_running());
  11269. });
  11270. svr.wait_until_ready();
  11271. std::string resp;
  11272. // POST without Content-Length
  11273. ASSERT_TRUE(send_request(5,
  11274. "POST /post HTTP/1.1\r\n"
  11275. "Host: localhost\r\n"
  11276. "Connection: close\r\n"
  11277. "\r\n",
  11278. &resp));
  11279. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11280. // PUT without Content-Length
  11281. resp.clear();
  11282. ASSERT_TRUE(send_request(5,
  11283. "PUT /put HTTP/1.1\r\n"
  11284. "Host: localhost\r\n"
  11285. "Connection: close\r\n"
  11286. "\r\n",
  11287. &resp));
  11288. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11289. // PATCH without Content-Length
  11290. resp.clear();
  11291. ASSERT_TRUE(send_request(5,
  11292. "PATCH /patch HTTP/1.1\r\n"
  11293. "Host: localhost\r\n"
  11294. "Connection: close\r\n"
  11295. "\r\n",
  11296. &resp));
  11297. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11298. // DELETE without Content-Length
  11299. resp.clear();
  11300. ASSERT_TRUE(send_request(5,
  11301. "DELETE /delete HTTP/1.1\r\n"
  11302. "Host: localhost\r\n"
  11303. "Connection: close\r\n"
  11304. "\r\n",
  11305. &resp));
  11306. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11307. }
  11308. #endif
  11309. //==============================================================================
  11310. // open_stream() Tests
  11311. //==============================================================================
  11312. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11313. std::string result;
  11314. char buf[8192];
  11315. ssize_t n;
  11316. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11317. result.append(buf, static_cast<size_t>(n));
  11318. }
  11319. return result;
  11320. }
  11321. // Mock stream for unit tests
  11322. class MockStream : public Stream {
  11323. public:
  11324. std::string data;
  11325. size_t pos = 0;
  11326. ssize_t error_after = -1; // -1 = no error
  11327. explicit MockStream(const std::string &d, ssize_t err = -1)
  11328. : data(d), error_after(err) {}
  11329. bool is_readable() const override { return true; }
  11330. bool wait_readable() const override { return true; }
  11331. bool wait_writable() const override { return true; }
  11332. ssize_t read(char *ptr, size_t size) override {
  11333. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11334. if (pos >= data.size()) return 0;
  11335. size_t limit =
  11336. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11337. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11338. std::memcpy(ptr, data.data() + pos, to_read);
  11339. pos += to_read;
  11340. return static_cast<ssize_t>(to_read);
  11341. }
  11342. ssize_t write(const char *, size_t) override { return -1; }
  11343. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11344. ip = "127.0.0.1";
  11345. port = 0;
  11346. }
  11347. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11348. ip = "127.0.0.1";
  11349. port = 0;
  11350. }
  11351. socket_t socket() const override { return INVALID_SOCKET; }
  11352. time_t duration() const override { return 0; }
  11353. };
  11354. TEST(StreamHandleTest, Basic) {
  11355. ClientImpl::StreamHandle handle;
  11356. EXPECT_FALSE(handle.is_valid());
  11357. handle.response = detail::make_unique<Response>();
  11358. handle.error = Error::Connection;
  11359. EXPECT_FALSE(handle.is_valid());
  11360. handle.error = Error::Success;
  11361. EXPECT_TRUE(handle.is_valid());
  11362. }
  11363. TEST(BodyReaderTest, Basic) {
  11364. MockStream stream("Hello, World!");
  11365. detail::BodyReader reader;
  11366. reader.stream = &stream;
  11367. reader.content_length = 13;
  11368. char buf[32];
  11369. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11370. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11371. EXPECT_TRUE(reader.eof);
  11372. }
  11373. TEST(BodyReaderTest, NoStream) {
  11374. detail::BodyReader reader;
  11375. char buf[32];
  11376. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11377. EXPECT_EQ(Error::Connection, reader.last_error);
  11378. }
  11379. TEST(BodyReaderTest, Error) {
  11380. MockStream stream("Hello, World!", 5);
  11381. detail::BodyReader reader;
  11382. reader.stream = &stream;
  11383. reader.content_length = 13;
  11384. char buf[32];
  11385. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11386. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11387. EXPECT_EQ(Error::Read, reader.last_error);
  11388. }
  11389. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11390. // Mock-based StreamHandle tests relying on private internals are removed.
  11391. class OpenStreamTest : public ::testing::Test {
  11392. protected:
  11393. void SetUp() override {
  11394. svr_.Get("/hello", [](const Request &, Response &res) {
  11395. res.set_content("Hello World!", "text/plain");
  11396. });
  11397. svr_.Get("/large", [](const Request &, Response &res) {
  11398. res.set_content(std::string(10000, 'X'), "text/plain");
  11399. });
  11400. svr_.Get("/chunked", [](const Request &, Response &res) {
  11401. res.set_chunked_content_provider("text/plain",
  11402. [](size_t offset, DataSink &sink) {
  11403. if (offset < 15) {
  11404. sink.write("chunk", 5);
  11405. return true;
  11406. }
  11407. sink.done();
  11408. return true;
  11409. });
  11410. });
  11411. svr_.Get("/compressible", [](const Request &, Response &res) {
  11412. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11413. DataSink &sink) {
  11414. if (offset < 100 * 1024) {
  11415. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11416. sink.write(chunk.data(), chunk.size());
  11417. return true;
  11418. }
  11419. sink.done();
  11420. return true;
  11421. });
  11422. });
  11423. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11424. [](const Request & /*req*/, Response &res) {
  11425. auto i = new int(0);
  11426. res.set_header("Trailer", "Content-Length, X-Allowed");
  11427. res.set_chunked_content_provider(
  11428. "text/plain",
  11429. [i](size_t /*offset*/, DataSink &sink) {
  11430. switch (*i) {
  11431. case 0: sink.os << "123"; break;
  11432. case 1: sink.os << "456"; break;
  11433. case 2: sink.os << "789"; break;
  11434. case 3: {
  11435. sink.done_with_trailer(
  11436. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11437. } break;
  11438. }
  11439. (*i)++;
  11440. return true;
  11441. },
  11442. [i](bool success) {
  11443. EXPECT_TRUE(success);
  11444. delete i;
  11445. });
  11446. });
  11447. // Echo headers endpoint for header-related tests
  11448. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11449. std::string body;
  11450. for (const auto &h : req.headers) {
  11451. body.append(h.first);
  11452. body.push_back(':');
  11453. body.append(h.second);
  11454. body.push_back('\n');
  11455. }
  11456. res.set_content(body, "text/plain");
  11457. });
  11458. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11459. std::string body;
  11460. for (const auto &h : req.headers) {
  11461. body.append(h.first);
  11462. body.push_back(':');
  11463. body.append(h.second);
  11464. body.push_back('\n');
  11465. }
  11466. res.set_content(body, "text/plain");
  11467. });
  11468. port_ = svr_.bind_to_any_port("127.0.0.1");
  11469. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11470. svr_.wait_until_ready();
  11471. }
  11472. void TearDown() override {
  11473. svr_.stop();
  11474. if (thread_.joinable()) thread_.join();
  11475. }
  11476. Server svr_;
  11477. std::thread thread_;
  11478. int port_ = 0;
  11479. };
  11480. TEST_F(OpenStreamTest, Basic) {
  11481. Client cli("127.0.0.1", port_);
  11482. auto handle = cli.open_stream("GET", "/hello");
  11483. EXPECT_TRUE(handle.is_valid());
  11484. EXPECT_EQ("Hello World!", read_all(handle));
  11485. }
  11486. TEST_F(OpenStreamTest, SmallBuffer) {
  11487. Client cli("127.0.0.1", port_);
  11488. auto handle = cli.open_stream("GET", "/hello");
  11489. std::string result;
  11490. char buf[4];
  11491. ssize_t n;
  11492. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11493. result.append(buf, static_cast<size_t>(n));
  11494. EXPECT_EQ("Hello World!", result);
  11495. }
  11496. TEST_F(OpenStreamTest, DefaultHeaders) {
  11497. Client cli("127.0.0.1", port_);
  11498. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11499. {
  11500. auto handle = cli.open_stream("GET", "/echo-headers");
  11501. ASSERT_TRUE(handle.is_valid());
  11502. auto body = read_all(handle);
  11503. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11504. std::string::npos);
  11505. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11506. std::string::npos);
  11507. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11508. }
  11509. // open_stream POST with body and no explicit content_type should NOT add
  11510. // text/plain Content-Type (behavior differs from non-streaming path), but
  11511. // should include Content-Length
  11512. {
  11513. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11514. ASSERT_TRUE(handle.is_valid());
  11515. auto body = read_all(handle);
  11516. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11517. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11518. }
  11519. // open_stream POST with explicit Content-Type should preserve it
  11520. {
  11521. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11522. {{"Content-Type", "application/custom"}},
  11523. "{}", "application/custom");
  11524. ASSERT_TRUE(handle.is_valid());
  11525. auto body = read_all(handle);
  11526. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11527. }
  11528. // User-specified User-Agent must not be overwritten for stream API
  11529. {
  11530. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11531. {{"User-Agent", "MyAgent/1.2"}});
  11532. ASSERT_TRUE(handle.is_valid());
  11533. auto body = read_all(handle);
  11534. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11535. }
  11536. }
  11537. TEST_F(OpenStreamTest, Large) {
  11538. Client cli("127.0.0.1", port_);
  11539. auto handle = cli.open_stream("GET", "/large");
  11540. EXPECT_EQ(10000u, read_all(handle).size());
  11541. }
  11542. TEST_F(OpenStreamTest, ConnectionError) {
  11543. Client cli("127.0.0.1", 9999);
  11544. auto handle = cli.open_stream("GET", "/hello");
  11545. EXPECT_FALSE(handle.is_valid());
  11546. }
  11547. TEST_F(OpenStreamTest, Chunked) {
  11548. Client cli("127.0.0.1", port_);
  11549. auto handle = cli.open_stream("GET", "/chunked");
  11550. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11551. "Transfer-Encoding") == "chunked");
  11552. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11553. }
  11554. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11555. Client cli("127.0.0.1", port_);
  11556. auto handle =
  11557. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11558. ASSERT_TRUE(handle.is_valid());
  11559. // Consume body to allow trailers to be received/parsed
  11560. auto body = read_all(handle);
  11561. // Explicitly parse trailers (ensure trailers are available for assertion)
  11562. handle.parse_trailers_if_needed();
  11563. EXPECT_EQ(std::string("123456789"), body);
  11564. // The response should include a Trailer header declaring both names
  11565. ASSERT_TRUE(handle.response);
  11566. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11567. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11568. handle.response->get_header_value("Trailer"));
  11569. // Prohibited trailer must not be present
  11570. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11571. // Allowed trailer should be present
  11572. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11573. EXPECT_EQ(std::string("yes"),
  11574. handle.response->get_trailer_value("X-Allowed"));
  11575. // Verify trailers are NOT present as regular headers
  11576. EXPECT_EQ(std::string(""),
  11577. handle.response->get_header_value("Content-Length"));
  11578. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11579. }
  11580. static std::thread serve_single_response(std::promise<int> &port_promise,
  11581. const std::string &response) {
  11582. return std::thread([&port_promise, response] {
  11583. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11584. default_socket_options(srv);
  11585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11586. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11587. sockaddr_in addr{};
  11588. addr.sin_family = AF_INET;
  11589. addr.sin_port = htons(0); // Let OS assign a free port
  11590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11591. int opt = 1;
  11592. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11593. #ifdef _WIN32
  11594. reinterpret_cast<const char *>(&opt),
  11595. #else
  11596. &opt,
  11597. #endif
  11598. sizeof(opt));
  11599. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11600. ::listen(srv, 1) != 0) {
  11601. port_promise.set_value(-1);
  11602. detail::close_socket(srv);
  11603. return;
  11604. }
  11605. socklen_t addr_len = sizeof(addr);
  11606. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11607. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11608. sockaddr_in cli_addr{};
  11609. socklen_t cli_len = sizeof(cli_addr);
  11610. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11611. if (cli != INVALID_SOCKET) {
  11612. char buf[4096];
  11613. ::recv(cli, buf, sizeof(buf), 0);
  11614. ::send(cli,
  11615. #ifdef _WIN32
  11616. static_cast<const char *>(response.c_str()),
  11617. static_cast<int>(response.size()),
  11618. #else
  11619. response.c_str(), response.size(),
  11620. #endif
  11621. 0);
  11622. detail::close_socket(cli);
  11623. }
  11624. detail::close_socket(srv);
  11625. });
  11626. }
  11627. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11628. #ifndef _WIN32
  11629. signal(SIGPIPE, SIG_IGN);
  11630. #endif
  11631. std::promise<int> port_promise;
  11632. auto port_future = port_promise.get_future();
  11633. auto server_thread =
  11634. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11635. "Content-Type: text/plain\r\n"
  11636. "Content-Length: not-a-number\r\n"
  11637. "Connection: close\r\n"
  11638. "\r\n"
  11639. "hello");
  11640. auto port = port_future.get();
  11641. ASSERT_GT(port, 0);
  11642. Client cli("127.0.0.1", port);
  11643. auto handle = cli.open_stream("GET", "/");
  11644. EXPECT_FALSE(handle.is_valid());
  11645. server_thread.join();
  11646. }
  11647. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11648. #ifndef _WIN32
  11649. signal(SIGPIPE, SIG_IGN);
  11650. #endif
  11651. std::promise<int> port_promise;
  11652. auto port_future = port_promise.get_future();
  11653. auto server_thread = serve_single_response(
  11654. port_promise, "HTTP/1.1 200 OK\r\n"
  11655. "Content-Type: text/plain\r\n"
  11656. "Content-Length: 99999999999999999999999999\r\n"
  11657. "Connection: close\r\n"
  11658. "\r\n"
  11659. "hello");
  11660. auto port = port_future.get();
  11661. ASSERT_GT(port, 0);
  11662. // Before the fix, std::stoull would throw std::out_of_range here and
  11663. // crash the process. After the fix, strtoull silently clamps to
  11664. // ULLONG_MAX so the stream opens without crashing. The important thing
  11665. // is that the process does NOT terminate.
  11666. Client cli("127.0.0.1", port);
  11667. auto handle = cli.open_stream("GET", "/");
  11668. EXPECT_TRUE(handle.is_valid());
  11669. server_thread.join();
  11670. }
  11671. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11672. TEST_F(OpenStreamTest, Gzip) {
  11673. Client cli("127.0.0.1", port_);
  11674. auto handle = cli.open_stream("GET", "/compressible", {},
  11675. {{"Accept-Encoding", "gzip"}});
  11676. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11677. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11678. }
  11679. #endif
  11680. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11681. TEST_F(OpenStreamTest, Brotli) {
  11682. Client cli("127.0.0.1", port_);
  11683. auto handle =
  11684. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11685. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11686. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11687. }
  11688. #endif
  11689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11690. TEST_F(OpenStreamTest, Zstd) {
  11691. Client cli("127.0.0.1", port_);
  11692. auto handle = cli.open_stream("GET", "/compressible", {},
  11693. {{"Accept-Encoding", "zstd"}});
  11694. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11695. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11696. }
  11697. #endif
  11698. #ifdef CPPHTTPLIB_SSL_ENABLED
  11699. class SSLOpenStreamTest : public ::testing::Test {
  11700. protected:
  11701. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11702. void SetUp() override {
  11703. svr_.Get("/hello", [](const Request &, Response &res) {
  11704. res.set_content("Hello SSL World!", "text/plain");
  11705. });
  11706. svr_.Get("/chunked", [](const Request &, Response &res) {
  11707. res.set_chunked_content_provider("text/plain",
  11708. [](size_t offset, DataSink &sink) {
  11709. if (offset < 15) {
  11710. sink.write("chunk", 5);
  11711. return true;
  11712. }
  11713. sink.done();
  11714. return true;
  11715. });
  11716. });
  11717. svr_.Post("/echo", [](const Request &req, Response &res) {
  11718. res.set_content(req.body, req.get_header_value("Content-Type"));
  11719. });
  11720. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11721. std::string body = req.body;
  11722. res.set_chunked_content_provider(
  11723. "text/plain", [body](size_t offset, DataSink &sink) {
  11724. if (offset < body.size()) {
  11725. sink.write(body.data() + offset, body.size() - offset);
  11726. }
  11727. sink.done();
  11728. return true;
  11729. });
  11730. });
  11731. port_ = svr_.bind_to_any_port("127.0.0.1");
  11732. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11733. svr_.wait_until_ready();
  11734. }
  11735. void TearDown() override {
  11736. svr_.stop();
  11737. if (thread_.joinable()) thread_.join();
  11738. }
  11739. SSLServer svr_;
  11740. std::thread thread_;
  11741. int port_ = 0;
  11742. };
  11743. TEST_F(SSLOpenStreamTest, Basic) {
  11744. SSLClient cli("127.0.0.1", port_);
  11745. cli.enable_server_certificate_verification(false);
  11746. auto handle = cli.open_stream("GET", "/hello");
  11747. ASSERT_TRUE(handle.is_valid());
  11748. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11749. }
  11750. TEST_F(SSLOpenStreamTest, Chunked) {
  11751. SSLClient cli("127.0.0.1", port_);
  11752. cli.enable_server_certificate_verification(false);
  11753. auto handle = cli.open_stream("GET", "/chunked");
  11754. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11755. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11756. "Transfer-Encoding") == "chunked");
  11757. auto body = read_all(handle);
  11758. EXPECT_EQ("chunkchunkchunk", body);
  11759. }
  11760. TEST_F(SSLOpenStreamTest, Post) {
  11761. SSLClient cli("127.0.0.1", port_);
  11762. cli.enable_server_certificate_verification(false);
  11763. auto handle =
  11764. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11765. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11766. EXPECT_EQ(200, handle.response->status);
  11767. auto body = read_all(handle);
  11768. EXPECT_EQ("Hello SSL POST", body);
  11769. }
  11770. TEST_F(SSLOpenStreamTest, PostChunked) {
  11771. SSLClient cli("127.0.0.1", port_);
  11772. cli.enable_server_certificate_verification(false);
  11773. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11774. "Chunked SSL Data", "text/plain");
  11775. ASSERT_TRUE(handle.is_valid());
  11776. EXPECT_EQ(200, handle.response->status);
  11777. auto body = read_all(handle);
  11778. EXPECT_EQ("Chunked SSL Data", body);
  11779. }
  11780. #endif // CPPHTTPLIB_SSL_ENABLED
  11781. //==============================================================================
  11782. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11783. // results for various scenarios.
  11784. //==============================================================================
  11785. TEST(ParityTest, GetVsOpenStream) {
  11786. Server svr;
  11787. const std::string path = "/parity";
  11788. const std::string content = "Parity test content: hello world";
  11789. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11790. res.set_content(content, "text/plain");
  11791. });
  11792. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11793. auto se = detail::scope_exit([&] {
  11794. svr.stop();
  11795. t.join();
  11796. ASSERT_FALSE(svr.is_running());
  11797. });
  11798. svr.wait_until_ready();
  11799. Client cli(HOST, PORT);
  11800. // Non-stream path
  11801. auto r1 = cli.Get(path);
  11802. ASSERT_TRUE(r1);
  11803. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11804. // Stream path
  11805. auto h = cli.open_stream("GET", path);
  11806. ASSERT_TRUE(h.is_valid());
  11807. EXPECT_EQ(r1->body, read_all(h));
  11808. }
  11809. // Helper to compress data with provided compressor type T
  11810. template <typename Compressor>
  11811. static std::string compress_payload_for_parity(const std::string &in) {
  11812. std::string out;
  11813. Compressor compressor;
  11814. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11815. [&](const char *data, size_t n) {
  11816. out.append(data, n);
  11817. return true;
  11818. });
  11819. EXPECT_TRUE(ok);
  11820. return out;
  11821. }
  11822. // Helper function for compression parity tests
  11823. template <typename Compressor>
  11824. static void test_compression_parity(const std::string &original,
  11825. const std::string &path,
  11826. const std::string &encoding) {
  11827. const std::string compressed =
  11828. compress_payload_for_parity<Compressor>(original);
  11829. Server svr;
  11830. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11831. res.set_content(compressed, "application/octet-stream");
  11832. res.set_header("Content-Encoding", encoding);
  11833. });
  11834. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11835. auto se = detail::scope_exit([&] {
  11836. svr.stop();
  11837. t.join();
  11838. ASSERT_FALSE(svr.is_running());
  11839. });
  11840. svr.wait_until_ready();
  11841. Client cli(HOST, PORT);
  11842. // Non-streaming
  11843. {
  11844. auto res = cli.Get(path);
  11845. ASSERT_TRUE(res);
  11846. EXPECT_EQ(StatusCode::OK_200, res->status);
  11847. EXPECT_EQ(original, res->body);
  11848. }
  11849. // Streaming
  11850. {
  11851. auto h = cli.open_stream("GET", path);
  11852. ASSERT_TRUE(h.is_valid());
  11853. EXPECT_EQ(original, read_all(h));
  11854. }
  11855. }
  11856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11857. TEST(ParityTest, Gzip) {
  11858. test_compression_parity<detail::gzip_compressor>(
  11859. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11860. }
  11861. #endif
  11862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11863. TEST(ParityTest, Brotli) {
  11864. test_compression_parity<detail::brotli_compressor>(
  11865. "Hello, brotli parity test payload", "/parity-br", "br");
  11866. }
  11867. #endif
  11868. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11869. TEST(ParityTest, Zstd) {
  11870. test_compression_parity<detail::zstd_compressor>(
  11871. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11872. }
  11873. #endif
  11874. //==============================================================================
  11875. // New Stream API Tests
  11876. //==============================================================================
  11877. inline std::string read_body(httplib::stream::Result &result) {
  11878. std::string body;
  11879. while (result.next()) {
  11880. body.append(result.data(), result.size());
  11881. }
  11882. return body;
  11883. }
  11884. TEST(ClientConnectionTest, Basic) {
  11885. httplib::ClientConnection conn;
  11886. EXPECT_FALSE(conn.is_open());
  11887. conn.sock = 1;
  11888. EXPECT_TRUE(conn.is_open());
  11889. httplib::ClientConnection conn2(std::move(conn));
  11890. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11891. conn2.sock = INVALID_SOCKET;
  11892. }
  11893. // Unified test server for all stream::* tests
  11894. class StreamApiTest : public ::testing::Test {
  11895. protected:
  11896. void SetUp() override {
  11897. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11898. res.set_content("Hello World!", "text/plain");
  11899. });
  11900. svr_.Get("/echo-params",
  11901. [](const httplib::Request &req, httplib::Response &res) {
  11902. std::string r;
  11903. for (const auto &p : req.params) {
  11904. if (!r.empty()) r += "&";
  11905. r += p.first + "=" + p.second;
  11906. }
  11907. res.set_content(r, "text/plain");
  11908. });
  11909. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11910. res.set_content(req.body, req.get_header_value("Content-Type"));
  11911. });
  11912. svr_.Post("/echo-headers",
  11913. [](const httplib::Request &req, httplib::Response &res) {
  11914. std::string r;
  11915. for (const auto &h : req.headers)
  11916. r += h.first + ": " + h.second + "\n";
  11917. res.set_content(r, "text/plain");
  11918. });
  11919. svr_.Post("/echo-params",
  11920. [](const httplib::Request &req, httplib::Response &res) {
  11921. std::string r = "params:";
  11922. for (const auto &p : req.params)
  11923. r += p.first + "=" + p.second + ";";
  11924. res.set_content(r + " body:" + req.body, "text/plain");
  11925. });
  11926. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11927. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11928. });
  11929. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11930. res.set_content("PUT:" + req.body, "text/plain");
  11931. });
  11932. svr_.Patch("/echo",
  11933. [](const httplib::Request &req, httplib::Response &res) {
  11934. res.set_content("PATCH:" + req.body, "text/plain");
  11935. });
  11936. svr_.Delete(
  11937. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11938. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11939. "text/plain");
  11940. });
  11941. svr_.Get("/head-test",
  11942. [](const httplib::Request &, httplib::Response &res) {
  11943. res.set_content("body for HEAD", "text/plain");
  11944. });
  11945. svr_.Options("/options",
  11946. [](const httplib::Request &, httplib::Response &res) {
  11947. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11948. });
  11949. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11950. svr_.wait_until_ready();
  11951. }
  11952. void TearDown() override {
  11953. svr_.stop();
  11954. if (thread_.joinable()) thread_.join();
  11955. }
  11956. httplib::Server svr_;
  11957. std::thread thread_;
  11958. };
  11959. // stream::Get tests
  11960. TEST_F(StreamApiTest, GetBasic) {
  11961. httplib::Client cli(HOST, PORT);
  11962. auto result = httplib::stream::Get(cli, "/hello");
  11963. ASSERT_TRUE(result.is_valid());
  11964. EXPECT_EQ(200, result.status());
  11965. EXPECT_EQ("Hello World!", read_body(result));
  11966. }
  11967. TEST_F(StreamApiTest, GetWithParams) {
  11968. httplib::Client cli(HOST, PORT);
  11969. httplib::Params params{{"foo", "bar"}};
  11970. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11971. ASSERT_TRUE(result.is_valid());
  11972. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11973. }
  11974. TEST_F(StreamApiTest, GetConnectionError) {
  11975. httplib::Client cli(HOST, 9999);
  11976. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11977. }
  11978. TEST_F(StreamApiTest, Get404) {
  11979. httplib::Client cli(HOST, PORT);
  11980. auto result = httplib::stream::Get(cli, "/nonexistent");
  11981. EXPECT_TRUE(result.is_valid());
  11982. EXPECT_EQ(404, result.status());
  11983. }
  11984. // stream::Post tests
  11985. TEST_F(StreamApiTest, PostBasic) {
  11986. httplib::Client cli(HOST, PORT);
  11987. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11988. "application/json");
  11989. ASSERT_TRUE(result.is_valid());
  11990. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11991. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11992. }
  11993. TEST_F(StreamApiTest, PostWithHeaders) {
  11994. httplib::Client cli(HOST, PORT);
  11995. httplib::Headers headers{{"X-Custom", "value"}};
  11996. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11997. "text/plain");
  11998. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11999. }
  12000. TEST_F(StreamApiTest, PostWithParams) {
  12001. httplib::Client cli(HOST, PORT);
  12002. httplib::Params params{{"k", "v"}};
  12003. auto result =
  12004. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12005. auto body = read_body(result);
  12006. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12007. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12008. }
  12009. TEST_F(StreamApiTest, PostLarge) {
  12010. httplib::Client cli(HOST, PORT);
  12011. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12012. size_t total = 0;
  12013. while (result.next()) {
  12014. total += result.size();
  12015. }
  12016. EXPECT_EQ(100u * 1024u, total);
  12017. }
  12018. // stream::Put/Patch tests
  12019. TEST_F(StreamApiTest, PutAndPatch) {
  12020. httplib::Client cli(HOST, PORT);
  12021. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12022. EXPECT_EQ("PUT:test", read_body(put));
  12023. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12024. EXPECT_EQ("PATCH:test", read_body(patch));
  12025. }
  12026. // stream::Delete tests
  12027. TEST_F(StreamApiTest, Delete) {
  12028. httplib::Client cli(HOST, PORT);
  12029. auto del1 = httplib::stream::Delete(cli, "/resource");
  12030. EXPECT_EQ("Deleted", read_body(del1));
  12031. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12032. EXPECT_EQ("Deleted:data", read_body(del2));
  12033. }
  12034. // stream::Head/Options tests
  12035. TEST_F(StreamApiTest, HeadAndOptions) {
  12036. httplib::Client cli(HOST, PORT);
  12037. auto head = httplib::stream::Head(cli, "/head-test");
  12038. EXPECT_TRUE(head.is_valid());
  12039. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12040. auto opts = httplib::stream::Options(cli, "/options");
  12041. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12042. }
  12043. // SSL stream::* tests
  12044. #ifdef CPPHTTPLIB_SSL_ENABLED
  12045. class SSLStreamApiTest : public ::testing::Test {
  12046. protected:
  12047. void SetUp() override {
  12048. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12049. res.set_content("Hello SSL!", "text/plain");
  12050. });
  12051. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12052. res.set_content(req.body, "text/plain");
  12053. });
  12054. port_ = svr_.bind_to_any_port("127.0.0.1");
  12055. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12056. svr_.wait_until_ready();
  12057. }
  12058. void TearDown() override {
  12059. svr_.stop();
  12060. if (thread_.joinable()) thread_.join();
  12061. }
  12062. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12063. std::thread thread_;
  12064. int port_ = 0;
  12065. };
  12066. TEST_F(SSLStreamApiTest, GetAndPost) {
  12067. httplib::SSLClient cli("127.0.0.1", port_);
  12068. cli.enable_server_certificate_verification(false);
  12069. auto get = httplib::stream::Get(cli, "/hello");
  12070. EXPECT_EQ("Hello SSL!", read_body(get));
  12071. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12072. EXPECT_EQ("test", read_body(post));
  12073. }
  12074. #endif
  12075. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12076. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12077. // BodyReader
  12078. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12079. // Test that read timeout during streaming is detected
  12080. // Use a large content-length response where server delays mid-stream
  12081. Server svr;
  12082. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12083. // Send a large response with delay in the middle
  12084. res.set_content_provider(
  12085. 1000, // content_length
  12086. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12087. if (offset < 100) {
  12088. // Send first 100 bytes immediately
  12089. std::string data(100, 'A');
  12090. sink.write(data.c_str(), data.size());
  12091. return true;
  12092. }
  12093. // Then delay longer than client timeout
  12094. std::this_thread::sleep_for(std::chrono::seconds(3));
  12095. std::string data(900, 'B');
  12096. sink.write(data.c_str(), data.size());
  12097. return true;
  12098. });
  12099. });
  12100. auto port = 8091;
  12101. std::thread t([&]() { svr.listen("localhost", port); });
  12102. svr.wait_until_ready();
  12103. Client cli("localhost", port);
  12104. cli.set_read_timeout(1, 0); // 1 second timeout
  12105. auto handle = cli.open_stream("GET", "/slow-stream");
  12106. ASSERT_TRUE(handle.is_valid());
  12107. char buf[256];
  12108. ssize_t total = 0;
  12109. ssize_t n;
  12110. bool got_error = false;
  12111. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12112. total += n;
  12113. }
  12114. if (n < 0) {
  12115. got_error = true;
  12116. // Should be timeout or read error
  12117. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12118. handle.get_read_error() == Error::Read)
  12119. << "Actual error: " << to_string(handle.get_read_error());
  12120. }
  12121. // Either we got an error, or we got less data than expected
  12122. EXPECT_TRUE(got_error || total < 1000)
  12123. << "Expected timeout but got all " << total << " bytes";
  12124. svr.stop();
  12125. t.join();
  12126. }
  12127. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12128. // Test connection closed detection via BodyReader
  12129. Server svr;
  12130. std::atomic<bool> close_now{false};
  12131. svr.Get("/will-close", [&](const Request &, Response &res) {
  12132. res.set_content_provider(
  12133. 10000, // Large content_length that we won't fully send
  12134. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12135. if (offset < 100) {
  12136. std::string data(100, 'X');
  12137. sink.write(data.c_str(), data.size());
  12138. return true;
  12139. }
  12140. // Wait for signal then abort
  12141. while (!close_now) {
  12142. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12143. }
  12144. return false; // Abort - server will close connection
  12145. });
  12146. });
  12147. auto port = 8092;
  12148. std::thread t([&]() { svr.listen("localhost", port); });
  12149. svr.wait_until_ready();
  12150. Client cli("localhost", port);
  12151. auto handle = cli.open_stream("GET", "/will-close");
  12152. ASSERT_TRUE(handle.is_valid());
  12153. char buf[256];
  12154. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12155. EXPECT_GT(n, 0) << "First read should succeed";
  12156. // Signal server to close
  12157. close_now = true;
  12158. // Keep reading until error or EOF
  12159. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12160. // Keep reading
  12161. }
  12162. // Should get an error since content_length wasn't satisfied
  12163. if (n < 0) {
  12164. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12165. handle.get_read_error() == Error::Read)
  12166. << "Actual error: " << to_string(handle.get_read_error());
  12167. }
  12168. svr.stop();
  12169. t.join();
  12170. }
  12171. #ifdef CPPHTTPLIB_SSL_ENABLED
  12172. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12173. // Test that read timeout during SSL streaming is detected
  12174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12175. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12176. res.set_content_provider(
  12177. 1000, "text/plain",
  12178. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12179. if (offset < 100) {
  12180. std::string data(100, 'A');
  12181. sink.write(data.c_str(), data.size());
  12182. return true;
  12183. }
  12184. std::this_thread::sleep_for(std::chrono::seconds(3));
  12185. std::string data(900, 'B');
  12186. sink.write(data.c_str(), data.size());
  12187. return true;
  12188. });
  12189. });
  12190. auto port = 8093;
  12191. std::thread t([&]() { svr.listen("localhost", port); });
  12192. svr.wait_until_ready();
  12193. SSLClient cli("localhost", port);
  12194. cli.enable_server_certificate_verification(false);
  12195. cli.set_read_timeout(1, 0); // 1 second timeout
  12196. auto handle = cli.open_stream("GET", "/slow-stream");
  12197. ASSERT_TRUE(handle.is_valid());
  12198. char buf[256];
  12199. ssize_t total = 0;
  12200. ssize_t n;
  12201. bool got_error = false;
  12202. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12203. total += n;
  12204. }
  12205. if (n < 0) {
  12206. got_error = true;
  12207. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12208. handle.get_read_error() == Error::Read)
  12209. << "Actual error: " << to_string(handle.get_read_error());
  12210. }
  12211. EXPECT_TRUE(got_error || total < 1000)
  12212. << "Expected timeout but got all " << total << " bytes";
  12213. svr.stop();
  12214. t.join();
  12215. }
  12216. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12217. // Test SSL connection closed detection
  12218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12219. std::atomic<bool> close_now{false};
  12220. svr.Get("/will-close", [&](const Request &, Response &res) {
  12221. res.set_content_provider(
  12222. 10000, "text/plain",
  12223. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12224. if (offset < 100) {
  12225. std::string data(100, 'X');
  12226. sink.write(data.c_str(), data.size());
  12227. return true;
  12228. }
  12229. while (!close_now) {
  12230. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12231. }
  12232. return false;
  12233. });
  12234. });
  12235. auto port = 8094;
  12236. std::thread t([&]() { svr.listen("localhost", port); });
  12237. svr.wait_until_ready();
  12238. SSLClient cli("localhost", port);
  12239. cli.enable_server_certificate_verification(false);
  12240. auto handle = cli.open_stream("GET", "/will-close");
  12241. ASSERT_TRUE(handle.is_valid());
  12242. char buf[256];
  12243. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12244. EXPECT_GT(n, 0);
  12245. // Signal server to close
  12246. close_now = true;
  12247. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12248. // Keep reading
  12249. }
  12250. if (n < 0) {
  12251. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12252. handle.get_read_error() == Error::Read)
  12253. << "Actual error: " << to_string(handle.get_read_error());
  12254. }
  12255. svr.stop();
  12256. t.join();
  12257. }
  12258. #endif
  12259. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12260. using namespace httplib;
  12261. // Create a test file
  12262. const char *fname = "etag_testfile.txt";
  12263. const char *content = "etag-content";
  12264. {
  12265. std::ofstream ofs(fname);
  12266. ofs << content;
  12267. ASSERT_TRUE(ofs.good());
  12268. }
  12269. Server svr;
  12270. svr.set_mount_point("/static", ".");
  12271. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12272. svr.wait_until_ready();
  12273. Client cli(HOST, PORT);
  12274. // First request: should get 200 with ETag header
  12275. auto res1 = cli.Get("/static/etag_testfile.txt");
  12276. ASSERT_TRUE(res1);
  12277. ASSERT_EQ(200, res1->status);
  12278. ASSERT_TRUE(res1->has_header("ETag"));
  12279. std::string etag = res1->get_header_value("ETag");
  12280. EXPECT_FALSE(etag.empty());
  12281. // Verify ETag format: W/"hex-hex"
  12282. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12283. EXPECT_EQ('W', etag[0]);
  12284. EXPECT_EQ('/', etag[1]);
  12285. EXPECT_EQ('"', etag[2]);
  12286. EXPECT_EQ('"', etag.back());
  12287. // Exact match: expect 304 Not Modified
  12288. Headers h2 = {{"If-None-Match", etag}};
  12289. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12290. ASSERT_TRUE(res2);
  12291. EXPECT_EQ(304, res2->status);
  12292. // Wildcard match: expect 304 Not Modified
  12293. Headers h3 = {{"If-None-Match", "*"}};
  12294. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12295. ASSERT_TRUE(res3);
  12296. EXPECT_EQ(304, res3->status);
  12297. // Non-matching ETag: expect 200
  12298. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12299. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12300. ASSERT_TRUE(res4);
  12301. EXPECT_EQ(200, res4->status);
  12302. // Multiple ETags with one matching: expect 304
  12303. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12304. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12305. ASSERT_TRUE(res5);
  12306. EXPECT_EQ(304, res5->status);
  12307. svr.stop();
  12308. t.join();
  12309. std::remove(fname);
  12310. }
  12311. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12312. using namespace httplib;
  12313. Server svr;
  12314. svr.set_mount_point("/static", ".");
  12315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12316. svr.wait_until_ready();
  12317. Client cli(HOST, PORT);
  12318. // Send If-None-Match: * to a non-existent file
  12319. Headers h = {{"If-None-Match", "*"}};
  12320. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12321. ASSERT_TRUE(res);
  12322. EXPECT_EQ(404, res->status);
  12323. svr.stop();
  12324. t.join();
  12325. }
  12326. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12327. using namespace httplib;
  12328. // Create a test file
  12329. const char *fname = "etag_boundary_testfile.txt";
  12330. const char *content = "boundary-test";
  12331. {
  12332. std::ofstream ofs(fname);
  12333. ofs << content;
  12334. ASSERT_TRUE(ofs.good());
  12335. }
  12336. Server svr;
  12337. svr.set_mount_point("/static", ".");
  12338. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12339. svr.wait_until_ready();
  12340. Client cli(HOST, PORT);
  12341. // Get the actual ETag
  12342. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12343. ASSERT_TRUE(res1);
  12344. ASSERT_EQ(200, res1->status);
  12345. ASSERT_TRUE(res1->has_header("ETag"));
  12346. std::string etag = res1->get_header_value("ETag");
  12347. // Test 1: Very long ETag value (longer than actual ETag)
  12348. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12349. Headers h1 = {{"If-None-Match", "W/"
  12350. "\"very-long-etag-value-that-is-much-longer-"
  12351. "than-the-actual-etag-value\""}};
  12352. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12353. ASSERT_TRUE(res2);
  12354. EXPECT_EQ(200, res2->status); // Should not match
  12355. // Test 2: Long string followed by wildcard
  12356. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12357. // string)
  12358. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12359. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12360. ASSERT_TRUE(res3);
  12361. EXPECT_EQ(304, res3->status); // Should match on "*"
  12362. // Test 3: Wildcard followed by long string
  12363. // Should match on "*" immediately and return 304
  12364. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12365. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12366. ASSERT_TRUE(res4);
  12367. EXPECT_EQ(304, res4->status); // Should match on "*"
  12368. // Test 4: Multiple long non-matching values
  12369. // Should NOT match and return 200 (test that all comparisons are safe)
  12370. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12371. "W/\"second-long-non-matching-value\", "
  12372. "W/\"third-long-non-matching-value\""}};
  12373. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12374. ASSERT_TRUE(res5);
  12375. EXPECT_EQ(200, res5->status); // Should not match
  12376. // Test 5: Single character that is not "*" (edge case)
  12377. Headers h5 = {{"If-None-Match", "X"}};
  12378. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12379. ASSERT_TRUE(res6);
  12380. EXPECT_EQ(200, res6->status); // Should not match
  12381. svr.stop();
  12382. t.join();
  12383. std::remove(fname);
  12384. }
  12385. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12386. using namespace httplib;
  12387. // Create a test file
  12388. const char *fname = "ims_testfile.txt";
  12389. const char *content = "if-modified-since-test";
  12390. {
  12391. std::ofstream ofs(fname);
  12392. ofs << content;
  12393. ASSERT_TRUE(ofs.good());
  12394. }
  12395. Server svr;
  12396. svr.set_mount_point("/static", ".");
  12397. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12398. svr.wait_until_ready();
  12399. Client cli(HOST, PORT);
  12400. // First request: should get 200 with Last-Modified header
  12401. auto res1 = cli.Get("/static/ims_testfile.txt");
  12402. ASSERT_TRUE(res1);
  12403. ASSERT_EQ(200, res1->status);
  12404. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12405. std::string last_modified = res1->get_header_value("Last-Modified");
  12406. EXPECT_FALSE(last_modified.empty());
  12407. // If-Modified-Since with same time: expect 304
  12408. Headers h2 = {{"If-Modified-Since", last_modified}};
  12409. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12410. ASSERT_TRUE(res2);
  12411. EXPECT_EQ(304, res2->status);
  12412. // If-Modified-Since with future time: expect 304
  12413. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12414. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12415. ASSERT_TRUE(res3);
  12416. EXPECT_EQ(304, res3->status);
  12417. // If-Modified-Since with past time: expect 200
  12418. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12419. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12420. ASSERT_TRUE(res4);
  12421. EXPECT_EQ(200, res4->status);
  12422. // If-None-Match takes precedence over If-Modified-Since
  12423. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12424. ASSERT_TRUE(res1->has_header("ETag"));
  12425. std::string etag = res1->get_header_value("ETag");
  12426. Headers h5 = {{"If-None-Match", etag},
  12427. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12428. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12429. ASSERT_TRUE(res5);
  12430. EXPECT_EQ(304, res5->status);
  12431. svr.stop();
  12432. t.join();
  12433. std::remove(fname);
  12434. }
  12435. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12436. using namespace httplib;
  12437. Server svr;
  12438. // Endpoint that returns compressible content
  12439. svr.Get("/compressible", [](const Request &, Response &res) {
  12440. // Return a large enough body to trigger compression
  12441. std::string body(1000, 'a');
  12442. res.set_content(body, "text/plain");
  12443. });
  12444. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12445. svr.wait_until_ready();
  12446. Client cli(HOST, PORT);
  12447. // Request with gzip support: should get Vary header when compressed
  12448. cli.set_compress(true);
  12449. auto res1 = cli.Get("/compressible");
  12450. ASSERT_TRUE(res1);
  12451. EXPECT_EQ(200, res1->status);
  12452. // If Content-Encoding is set, Vary should also be set
  12453. if (res1->has_header("Content-Encoding")) {
  12454. EXPECT_TRUE(res1->has_header("Vary"));
  12455. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12456. }
  12457. // Request without Accept-Encoding header: should not have compression
  12458. Headers h_no_compress;
  12459. auto res2 = cli.Get("/compressible", h_no_compress);
  12460. ASSERT_TRUE(res2);
  12461. EXPECT_EQ(200, res2->status);
  12462. // Verify Vary header is present when compression is applied
  12463. // (the exact behavior depends on server configuration)
  12464. svr.stop();
  12465. t.join();
  12466. }
  12467. TEST(ETagTest, IfRangeWithETag) {
  12468. using namespace httplib;
  12469. // Create a test file with known content
  12470. const char *fname = "if_range_testfile.txt";
  12471. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12472. {
  12473. std::ofstream ofs(fname);
  12474. ofs << content;
  12475. ASSERT_TRUE(ofs.good());
  12476. }
  12477. Server svr;
  12478. svr.set_mount_point("/static", ".");
  12479. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12480. svr.wait_until_ready();
  12481. Client cli(HOST, PORT);
  12482. // First request: get ETag
  12483. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12484. ASSERT_TRUE(res1);
  12485. ASSERT_EQ(200, res1->status);
  12486. ASSERT_TRUE(res1->has_header("ETag"));
  12487. std::string etag = res1->get_header_value("ETag");
  12488. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12489. // Since our server generates weak ETags (W/"..."), If-Range with our
  12490. // ETag should NOT result in partial content - it should return full content.
  12491. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12492. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12493. ASSERT_TRUE(res2);
  12494. // Weak ETag in If-Range -> full content (200), not partial (206)
  12495. EXPECT_EQ(200, res2->status);
  12496. EXPECT_EQ(content, res2->body);
  12497. EXPECT_FALSE(res2->has_header("Content-Range"));
  12498. // Range request with non-matching If-Range (ETag): should get 200 (full
  12499. // content)
  12500. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12501. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12502. ASSERT_TRUE(res3);
  12503. EXPECT_EQ(200, res3->status);
  12504. EXPECT_EQ(content, res3->body);
  12505. EXPECT_FALSE(res3->has_header("Content-Range"));
  12506. // Range request with strong ETag (hypothetical - our server doesn't generate
  12507. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12508. // should return full content)
  12509. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12510. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12511. ASSERT_TRUE(res4);
  12512. EXPECT_EQ(200, res4->status);
  12513. EXPECT_EQ(content, res4->body);
  12514. EXPECT_FALSE(res4->has_header("Content-Range"));
  12515. svr.stop();
  12516. t.join();
  12517. std::remove(fname);
  12518. }
  12519. TEST(ETagTest, IfRangeWithDate) {
  12520. using namespace httplib;
  12521. // Create a test file
  12522. const char *fname = "if_range_date_testfile.txt";
  12523. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12524. {
  12525. std::ofstream ofs(fname);
  12526. ofs << content;
  12527. ASSERT_TRUE(ofs.good());
  12528. }
  12529. Server svr;
  12530. svr.set_mount_point("/static", ".");
  12531. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12532. svr.wait_until_ready();
  12533. Client cli(HOST, PORT);
  12534. // First request: get Last-Modified
  12535. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12536. ASSERT_TRUE(res1);
  12537. ASSERT_EQ(200, res1->status);
  12538. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12539. std::string last_modified = res1->get_header_value("Last-Modified");
  12540. // Range request with matching If-Range (date): should get 206
  12541. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12542. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12543. ASSERT_TRUE(res2);
  12544. EXPECT_EQ(206, res2->status);
  12545. EXPECT_EQ("FGHIJ", res2->body);
  12546. // Range request with old If-Range date: should get 200 (full content)
  12547. Headers h3 = {{"Range", "bytes=5-9"},
  12548. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12549. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12550. ASSERT_TRUE(res3);
  12551. EXPECT_EQ(200, res3->status);
  12552. EXPECT_EQ(content, res3->body);
  12553. // Range request with future If-Range date: should get 206
  12554. Headers h4 = {{"Range", "bytes=0-4"},
  12555. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12556. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12557. ASSERT_TRUE(res4);
  12558. EXPECT_EQ(206, res4->status);
  12559. EXPECT_EQ("ABCDE", res4->body);
  12560. svr.stop();
  12561. t.join();
  12562. std::remove(fname);
  12563. }
  12564. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12565. using namespace httplib;
  12566. const char *fname = "etag_malformed.txt";
  12567. const char *content = "malformed-etag";
  12568. {
  12569. std::ofstream ofs(fname);
  12570. ofs << content;
  12571. ASSERT_TRUE(ofs.good());
  12572. }
  12573. Server svr;
  12574. svr.set_mount_point("/static", ".");
  12575. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12576. svr.wait_until_ready();
  12577. Client cli(HOST, PORT);
  12578. // baseline: should get 200 and an ETag
  12579. auto res1 = cli.Get("/static/etag_malformed.txt");
  12580. ASSERT_TRUE(res1);
  12581. ASSERT_EQ(200, res1->status);
  12582. ASSERT_TRUE(res1->has_header("ETag"));
  12583. // Malformed ETag value (missing quotes) should be treated as non-matching
  12584. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12585. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12586. ASSERT_TRUE(res_bad);
  12587. EXPECT_EQ(200, res_bad->status);
  12588. // Whitespace-only header value should be considered invalid / non-matching
  12589. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12590. "Host: localhost\r\n"
  12591. "If-None-Match: \r\n"
  12592. "Connection: close\r\n"
  12593. "\r\n";
  12594. std::string out;
  12595. ASSERT_TRUE(send_request(5, raw_req, &out));
  12596. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12597. svr.stop();
  12598. t.join();
  12599. std::remove(fname);
  12600. }
  12601. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12602. using namespace httplib;
  12603. const char *fname = "ims_invalid_format.txt";
  12604. const char *content = "ims-bad-format";
  12605. {
  12606. std::ofstream ofs(fname);
  12607. ofs << content;
  12608. ASSERT_TRUE(ofs.good());
  12609. }
  12610. Server svr;
  12611. svr.set_mount_point("/static", ".");
  12612. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12613. svr.wait_until_ready();
  12614. Client cli(HOST, PORT);
  12615. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12616. ASSERT_TRUE(res1);
  12617. ASSERT_EQ(200, res1->status);
  12618. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12619. // If-Modified-Since with invalid format should not result in 304
  12620. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12621. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12622. ASSERT_TRUE(res_bad);
  12623. EXPECT_EQ(200, res_bad->status);
  12624. // If-Range with invalid date format should be treated as mismatch -> full
  12625. // content (200)
  12626. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12627. {"If-Range", "invalid-date"}};
  12628. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12629. ASSERT_TRUE(res_ifrange);
  12630. EXPECT_EQ(200, res_ifrange->status);
  12631. svr.stop();
  12632. t.join();
  12633. std::remove(fname);
  12634. }
  12635. TEST(ETagTest, IfRangeWithMalformedETag) {
  12636. using namespace httplib;
  12637. const char *fname = "ifrange_malformed.txt";
  12638. const std::string content = "0123456789";
  12639. {
  12640. std::ofstream ofs(fname);
  12641. ofs << content;
  12642. ASSERT_TRUE(ofs.good());
  12643. }
  12644. Server svr;
  12645. svr.set_mount_point("/static", ".");
  12646. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12647. svr.wait_until_ready();
  12648. Client cli(HOST, PORT);
  12649. // First request: get ETag
  12650. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12651. ASSERT_TRUE(res1);
  12652. ASSERT_EQ(200, res1->status);
  12653. ASSERT_TRUE(res1->has_header("ETag"));
  12654. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12655. // full content (200)
  12656. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12657. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12658. ASSERT_TRUE(res2);
  12659. EXPECT_EQ(200, res2->status);
  12660. EXPECT_EQ(content, res2->body);
  12661. svr.stop();
  12662. t.join();
  12663. std::remove(fname);
  12664. }
  12665. TEST(ETagTest, ExtremeLargeDateValues) {
  12666. using namespace httplib;
  12667. const char *fname = "ims_extreme_date.txt";
  12668. const char *content = "ims-extreme-date";
  12669. {
  12670. std::ofstream ofs(fname);
  12671. ofs << content;
  12672. ASSERT_TRUE(ofs.good());
  12673. }
  12674. Server svr;
  12675. svr.set_mount_point("/static", ".");
  12676. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12677. svr.wait_until_ready();
  12678. Client cli(HOST, PORT);
  12679. auto res1 = cli.Get(std::string("/static/") + fname);
  12680. ASSERT_TRUE(res1);
  12681. ASSERT_EQ(200, res1->status);
  12682. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12683. // Extremely large year that may overflow date parsing routines.
  12684. Headers h_large_date = {
  12685. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12686. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12687. ASSERT_TRUE(res_bad);
  12688. // Expect server to treat this as invalid/mismatch and return full content
  12689. EXPECT_EQ(200, res_bad->status);
  12690. // If-Range with extremely large date should be treated as mismatch -> full
  12691. // content (200)
  12692. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12693. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12694. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12695. ASSERT_TRUE(res_ifrange);
  12696. EXPECT_EQ(200, res_ifrange->status);
  12697. svr.stop();
  12698. t.join();
  12699. std::remove(fname);
  12700. }
  12701. TEST(ETagTest, NegativeFileModificationTime) {
  12702. using namespace httplib;
  12703. const char *fname = "ims_negative_mtime.txt";
  12704. const std::string content = "negative-mtime";
  12705. {
  12706. std::ofstream ofs(fname);
  12707. ofs << content;
  12708. ASSERT_TRUE(ofs.good());
  12709. }
  12710. // Try to set file mtime to a negative value. This may fail on some
  12711. // platforms/filesystems; if it fails, the test will still verify server
  12712. // behaves safely by performing a regular conditional request.
  12713. #if defined(__APPLE__) || defined(__linux__)
  12714. bool set_negative = false;
  12715. do {
  12716. struct timeval times[2];
  12717. // access time: now
  12718. times[0].tv_sec = time(nullptr);
  12719. times[0].tv_usec = 0;
  12720. // modification time: negative (e.g., -1)
  12721. times[1].tv_sec = -1;
  12722. times[1].tv_usec = 0;
  12723. if (utimes(fname, times) == 0) { set_negative = true; }
  12724. } while (0);
  12725. #else
  12726. bool set_negative = false;
  12727. #endif
  12728. Server svr;
  12729. svr.set_mount_point("/static", ".");
  12730. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12731. svr.wait_until_ready();
  12732. Client cli(HOST, PORT);
  12733. auto res1 = cli.Get(std::string("/static/") + fname);
  12734. ASSERT_TRUE(res1);
  12735. ASSERT_EQ(200, res1->status);
  12736. bool has_last_modified = res1->has_header("Last-Modified");
  12737. std::string last_modified;
  12738. if (has_last_modified) {
  12739. last_modified = res1->get_header_value("Last-Modified");
  12740. }
  12741. if (set_negative) {
  12742. // If we successfully set a negative mtime, ensure server returns a
  12743. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12744. // with an old date and ensure server handles it without crash.
  12745. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12746. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12747. ASSERT_TRUE(res2);
  12748. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12749. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12750. } else {
  12751. // Could not set negative mtime on this platform; fall back to verifying
  12752. // that normal invalid/malformed dates are treated safely (non-304).
  12753. Headers h_bad_date = {
  12754. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12755. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12756. ASSERT_TRUE(res_bad);
  12757. EXPECT_EQ(200, res_bad->status);
  12758. }
  12759. svr.stop();
  12760. t.join();
  12761. std::remove(fname);
  12762. }
  12763. //==============================================================================
  12764. // SSE Parsing Tests
  12765. //==============================================================================
  12766. class SSEParsingTest : public ::testing::Test {
  12767. protected:
  12768. // Test helper that mimics SSE parsing behavior
  12769. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12770. int &retry_ms) {
  12771. // Blank line signals end of event
  12772. if (line.empty() || line == "\r") { return true; }
  12773. // Lines starting with ':' are comments (ignored)
  12774. if (!line.empty() && line[0] == ':') { return false; }
  12775. // Find the colon separator
  12776. auto colon_pos = line.find(':');
  12777. if (colon_pos == std::string::npos) {
  12778. // Line with no colon is treated as field name with empty value
  12779. return false;
  12780. }
  12781. std::string field = line.substr(0, colon_pos);
  12782. std::string value;
  12783. // Value starts after colon, skip optional single space
  12784. if (colon_pos + 1 < line.size()) {
  12785. size_t value_start = colon_pos + 1;
  12786. if (line[value_start] == ' ') { value_start++; }
  12787. value = line.substr(value_start);
  12788. // Remove trailing \r if present
  12789. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12790. }
  12791. // Handle known fields
  12792. if (field == "event") {
  12793. msg.event = value;
  12794. } else if (field == "data") {
  12795. // Multiple data lines are concatenated with newlines
  12796. if (!msg.data.empty()) { msg.data += "\n"; }
  12797. msg.data += value;
  12798. } else if (field == "id") {
  12799. // Empty id is valid (clears the last event ID)
  12800. msg.id = value;
  12801. } else if (field == "retry") {
  12802. // Parse retry interval in milliseconds
  12803. {
  12804. int v = 0;
  12805. auto res =
  12806. detail::from_chars(value.data(), value.data() + value.size(), v);
  12807. if (res.ec == std::errc{}) { retry_ms = v; }
  12808. }
  12809. }
  12810. // Unknown fields are ignored per SSE spec
  12811. return false;
  12812. }
  12813. };
  12814. // Test: Single-line data
  12815. TEST_F(SSEParsingTest, SingleLineData) {
  12816. sse::SSEMessage msg;
  12817. int retry_ms = 3000;
  12818. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12819. EXPECT_EQ(msg.data, "hello");
  12820. EXPECT_EQ(msg.event, "message");
  12821. // Blank line ends event
  12822. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12823. }
  12824. // Test: Multi-line data
  12825. TEST_F(SSEParsingTest, MultiLineData) {
  12826. sse::SSEMessage msg;
  12827. int retry_ms = 3000;
  12828. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12829. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12830. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12831. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12832. }
  12833. // Test: Custom event types
  12834. TEST_F(SSEParsingTest, CustomEventType) {
  12835. sse::SSEMessage msg;
  12836. int retry_ms = 3000;
  12837. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12838. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12839. EXPECT_EQ(msg.event, "update");
  12840. EXPECT_EQ(msg.data, "payload");
  12841. }
  12842. // Test: Event ID handling
  12843. TEST_F(SSEParsingTest, EventIdHandling) {
  12844. sse::SSEMessage msg;
  12845. int retry_ms = 3000;
  12846. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12847. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12848. EXPECT_EQ(msg.id, "12345");
  12849. }
  12850. // Test: Empty event ID (clears last event ID)
  12851. TEST_F(SSEParsingTest, EmptyEventId) {
  12852. sse::SSEMessage msg;
  12853. msg.id = "previous";
  12854. int retry_ms = 3000;
  12855. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12856. EXPECT_EQ(msg.id, "");
  12857. }
  12858. // Test: Retry field parsing
  12859. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12860. sse::SSEMessage msg;
  12861. int retry_ms = 3000;
  12862. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12863. EXPECT_EQ(retry_ms, 5000);
  12864. }
  12865. // Test: Invalid retry value
  12866. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12867. sse::SSEMessage msg;
  12868. int retry_ms = 3000;
  12869. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12870. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12871. }
  12872. // Test: Comments (lines starting with :)
  12873. TEST_F(SSEParsingTest, CommentsIgnored) {
  12874. sse::SSEMessage msg;
  12875. int retry_ms = 3000;
  12876. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12877. EXPECT_EQ(msg.data, "");
  12878. EXPECT_EQ(msg.event, "message");
  12879. }
  12880. // Test: Colon in value
  12881. TEST_F(SSEParsingTest, ColonInValue) {
  12882. sse::SSEMessage msg;
  12883. int retry_ms = 3000;
  12884. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12885. EXPECT_EQ(msg.data, "hello:world:test");
  12886. }
  12887. // Test: Line with no colon (field name only)
  12888. TEST_F(SSEParsingTest, FieldNameOnly) {
  12889. sse::SSEMessage msg;
  12890. int retry_ms = 3000;
  12891. // According to SSE spec, this is treated as field name with empty value
  12892. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12893. // Since we don't recognize "data" without colon, data should be empty
  12894. EXPECT_EQ(msg.data, "");
  12895. }
  12896. // Test: Trailing \r handling
  12897. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12898. sse::SSEMessage msg;
  12899. int retry_ms = 3000;
  12900. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12901. EXPECT_EQ(msg.data, "hello");
  12902. }
  12903. // Test: Unknown fields ignored
  12904. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12905. sse::SSEMessage msg;
  12906. int retry_ms = 3000;
  12907. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12908. EXPECT_EQ(msg.data, "");
  12909. EXPECT_EQ(msg.event, "message");
  12910. }
  12911. // Test: Space after colon is optional
  12912. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12913. sse::SSEMessage msg1, msg2;
  12914. int retry_ms = 3000;
  12915. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12916. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12917. EXPECT_EQ(msg1.data, "hello");
  12918. EXPECT_EQ(msg2.data, "hello");
  12919. }
  12920. // Test: SSEMessage clear
  12921. TEST_F(SSEParsingTest, MessageClear) {
  12922. sse::SSEMessage msg;
  12923. msg.event = "custom";
  12924. msg.data = "some data";
  12925. msg.id = "123";
  12926. msg.clear();
  12927. EXPECT_EQ(msg.event, "message");
  12928. EXPECT_EQ(msg.data, "");
  12929. EXPECT_EQ(msg.id, "");
  12930. }
  12931. // Test: Complete event parsing
  12932. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12933. sse::SSEMessage msg;
  12934. int retry_ms = 3000;
  12935. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12936. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12937. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12938. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12939. // Blank line ends event
  12940. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12941. EXPECT_EQ(msg.event, "notification");
  12942. EXPECT_EQ(msg.id, "evt-42");
  12943. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12944. EXPECT_EQ(retry_ms, 1000);
  12945. }
  12946. //==============================================================================
  12947. // Integration Tests with Server
  12948. //==============================================================================
  12949. class SSEIntegrationTest : public ::testing::Test {
  12950. protected:
  12951. void SetUp() override {
  12952. stop_server_.store(false);
  12953. events_.clear();
  12954. server_ = httplib::detail::make_unique<Server>();
  12955. setup_server();
  12956. start_server();
  12957. }
  12958. void TearDown() override {
  12959. stop_server_.store(true);
  12960. event_cv_.notify_all();
  12961. server_->stop();
  12962. if (server_thread_.joinable()) { server_thread_.join(); }
  12963. }
  12964. void setup_server() {
  12965. // Simple SSE endpoint
  12966. server_->Get("/events", [this](const Request &req, Response &res) {
  12967. auto last_id = req.get_header_value("Last-Event-ID");
  12968. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12969. res.set_chunked_content_provider(
  12970. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12971. std::unique_lock<std::mutex> lock(event_mutex_);
  12972. if (event_cv_.wait_for(
  12973. lock, std::chrono::milliseconds(200), [this] {
  12974. return !events_.empty() || stop_server_.load();
  12975. })) {
  12976. if (stop_server_.load()) { return false; }
  12977. if (!events_.empty()) {
  12978. std::string event = events_.front();
  12979. events_.erase(events_.begin());
  12980. sink.write(event.data(), event.size());
  12981. return true;
  12982. }
  12983. }
  12984. return !stop_server_.load();
  12985. });
  12986. });
  12987. // Endpoint that returns error
  12988. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12989. res.status = 500;
  12990. res.set_content("Internal Server Error", "text/plain");
  12991. });
  12992. // Endpoint for custom event types
  12993. server_->Get("/custom-events", [](const Request &, Response &res) {
  12994. res.set_chunked_content_provider(
  12995. "text/event-stream", [](size_t offset, DataSink &sink) {
  12996. if (offset == 0) {
  12997. std::string event = "event: update\ndata: updated\n\n"
  12998. "event: delete\ndata: deleted\n\n";
  12999. sink.write(event.data(), event.size());
  13000. }
  13001. return false; // End stream after sending
  13002. });
  13003. });
  13004. }
  13005. void start_server() {
  13006. port_ = server_->bind_to_any_port(HOST);
  13007. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13008. // Wait for server to start
  13009. while (!server_->is_running()) {
  13010. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13011. }
  13012. }
  13013. int get_port() const { return port_; }
  13014. void send_event(const std::string &event) {
  13015. std::lock_guard<std::mutex> lock(event_mutex_);
  13016. events_.push_back(event);
  13017. event_cv_.notify_all();
  13018. }
  13019. std::unique_ptr<Server> server_;
  13020. std::thread server_thread_;
  13021. std::mutex event_mutex_;
  13022. std::condition_variable event_cv_;
  13023. std::vector<std::string> events_;
  13024. std::atomic<bool> stop_server_{false};
  13025. std::string last_received_event_id_;
  13026. int port_ = 0;
  13027. };
  13028. // Test: Successful connection and on_open callback
  13029. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13030. // Add a simple endpoint that sends one event and closes
  13031. server_->Get("/simple-event", [](const Request &, Response &res) {
  13032. res.set_chunked_content_provider(
  13033. "text/event-stream", [](size_t offset, DataSink &sink) {
  13034. if (offset == 0) {
  13035. std::string event = "data: hello\n\n";
  13036. sink.write(event.data(), event.size());
  13037. }
  13038. return false; // Close stream after sending
  13039. });
  13040. });
  13041. Client client("localhost", get_port());
  13042. sse::SSEClient sse(client, "/simple-event");
  13043. std::atomic<bool> open_called{false};
  13044. std::atomic<bool> message_received{false};
  13045. sse.on_open([&open_called]() { open_called.store(true); });
  13046. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13047. if (msg.data == "hello") { message_received.store(true); }
  13048. });
  13049. sse.set_reconnect_interval(100);
  13050. sse.set_max_reconnect_attempts(1);
  13051. // Start async
  13052. sse.start_async();
  13053. // Wait for message to be processed
  13054. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13055. sse.stop();
  13056. EXPECT_TRUE(open_called.load());
  13057. EXPECT_TRUE(message_received.load());
  13058. }
  13059. // Test: on_message callback
  13060. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13061. // Endpoint that sends multiple events then closes
  13062. server_->Get("/multi-event", [](const Request &, Response &res) {
  13063. res.set_chunked_content_provider(
  13064. "text/event-stream", [](size_t offset, DataSink &sink) {
  13065. if (offset == 0) {
  13066. std::string events = "data: message1\n\ndata: message2\n\n";
  13067. sink.write(events.data(), events.size());
  13068. }
  13069. return false;
  13070. });
  13071. });
  13072. Client client("localhost", get_port());
  13073. sse::SSEClient sse(client, "/multi-event");
  13074. std::vector<std::string> received_messages;
  13075. std::mutex messages_mutex;
  13076. sse.on_message([&](const sse::SSEMessage &msg) {
  13077. std::lock_guard<std::mutex> lock(messages_mutex);
  13078. received_messages.push_back(msg.data);
  13079. });
  13080. sse.set_reconnect_interval(100);
  13081. sse.set_max_reconnect_attempts(1);
  13082. sse.start_async();
  13083. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13084. sse.stop();
  13085. std::lock_guard<std::mutex> lock(messages_mutex);
  13086. EXPECT_GE(received_messages.size(), 2u);
  13087. if (received_messages.size() >= 2) {
  13088. EXPECT_EQ(received_messages[0], "message1");
  13089. EXPECT_EQ(received_messages[1], "message2");
  13090. }
  13091. }
  13092. // Test: on_event for specific types
  13093. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13094. Client client("localhost", get_port());
  13095. sse::SSEClient sse(client, "/custom-events");
  13096. std::atomic<bool> update_received{false};
  13097. std::atomic<bool> delete_received{false};
  13098. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13099. if (msg.data == "updated") { update_received.store(true); }
  13100. });
  13101. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13102. if (msg.data == "deleted") { delete_received.store(true); }
  13103. });
  13104. sse.set_max_reconnect_attempts(1);
  13105. sse.start_async();
  13106. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13107. sse.stop();
  13108. EXPECT_TRUE(update_received.load());
  13109. EXPECT_TRUE(delete_received.load());
  13110. }
  13111. // Test: on_error callback on connection failure
  13112. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13113. // Connect to a non-existent port
  13114. Client client("localhost", 59999);
  13115. sse::SSEClient sse(client, "/events");
  13116. std::atomic<bool> error_called{false};
  13117. Error received_error = Error::Success;
  13118. sse.on_error([&](Error err) {
  13119. error_called.store(true);
  13120. received_error = err;
  13121. });
  13122. sse.set_reconnect_interval(50);
  13123. sse.set_max_reconnect_attempts(1);
  13124. sse.start_async();
  13125. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13126. sse.stop();
  13127. EXPECT_TRUE(error_called.load());
  13128. EXPECT_NE(received_error, Error::Success);
  13129. }
  13130. // Test: Last-Event-ID header sent on reconnect
  13131. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13132. // Endpoint that sends event with ID
  13133. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13134. res.set_chunked_content_provider(
  13135. "text/event-stream", [](size_t offset, DataSink &sink) {
  13136. if (offset == 0) {
  13137. std::string event = "id: evt-123\ndata: test\n\n";
  13138. sink.write(event.data(), event.size());
  13139. }
  13140. return false;
  13141. });
  13142. });
  13143. Client client("localhost", get_port());
  13144. sse::SSEClient sse(client, "/event-with-id");
  13145. std::atomic<bool> id_received{false};
  13146. sse.on_message([&](const sse::SSEMessage &msg) {
  13147. if (!msg.id.empty()) { id_received.store(true); }
  13148. });
  13149. sse.set_reconnect_interval(100);
  13150. sse.set_max_reconnect_attempts(1);
  13151. sse.start_async();
  13152. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13153. sse.stop();
  13154. EXPECT_TRUE(id_received.load());
  13155. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13156. }
  13157. // Test: Manual stop
  13158. TEST_F(SSEIntegrationTest, ManualStop) {
  13159. // Endpoint that sends one event and stays open briefly
  13160. std::atomic<bool> handler_running{true};
  13161. server_->Get("/stay-open", [&handler_running](const Request &,
  13162. Response &res) {
  13163. res.set_chunked_content_provider(
  13164. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13165. if (offset == 0) {
  13166. std::string event = "data: connected\n\n";
  13167. sink.write(event.data(), event.size());
  13168. }
  13169. // Keep connection open while handler_running is true
  13170. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13171. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13172. }
  13173. return false;
  13174. });
  13175. });
  13176. Client client("localhost", get_port());
  13177. sse::SSEClient sse(client, "/stay-open");
  13178. std::atomic<bool> connected{false};
  13179. sse.on_open([&connected]() { connected.store(true); });
  13180. sse.set_reconnect_interval(100);
  13181. sse.set_max_reconnect_attempts(1);
  13182. sse.start_async();
  13183. // Wait for connection to establish
  13184. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13185. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13186. }
  13187. EXPECT_TRUE(connected.load());
  13188. EXPECT_TRUE(sse.is_connected());
  13189. // Signal handler to stop
  13190. handler_running.store(false);
  13191. // Stop SSE client
  13192. sse.stop();
  13193. EXPECT_FALSE(sse.is_connected());
  13194. }
  13195. // Test: SSEClient with custom headers
  13196. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13197. // Setup a server endpoint that checks for custom header
  13198. std::atomic<bool> header_received{false};
  13199. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13200. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13201. header_received.store(true);
  13202. }
  13203. res.set_chunked_content_provider("text/event-stream",
  13204. [](size_t, DataSink &) { return false; });
  13205. });
  13206. Client client("localhost", get_port());
  13207. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13208. sse::SSEClient sse(client, "/header-check", headers);
  13209. sse.set_max_reconnect_attempts(1);
  13210. sse.start_async();
  13211. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13212. sse.stop();
  13213. EXPECT_TRUE(header_received.load());
  13214. }
  13215. // Test: Reconnect interval configuration
  13216. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13217. Client client("localhost", get_port());
  13218. sse::SSEClient sse(client, "/events");
  13219. auto &result = sse.set_reconnect_interval(500);
  13220. // Builder pattern should return reference to self
  13221. EXPECT_EQ(&result, &sse);
  13222. }
  13223. // Test: Max reconnect attempts
  13224. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13225. // Connect to non-existent port to force reconnects
  13226. Client client("localhost", 59998);
  13227. sse::SSEClient sse(client, "/events");
  13228. std::atomic<int> error_count{0};
  13229. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13230. sse.set_reconnect_interval(50);
  13231. sse.set_max_reconnect_attempts(2);
  13232. auto start = std::chrono::steady_clock::now();
  13233. sse.start(); // Blocking call
  13234. auto end = std::chrono::steady_clock::now();
  13235. // Should have stopped after 2 failed attempts
  13236. EXPECT_GE(error_count.load(), 2);
  13237. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13238. auto duration =
  13239. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13240. #ifdef _WIN32
  13241. // Windows is much slower for socket connection failures
  13242. EXPECT_LT(duration.count(), 7000);
  13243. #else
  13244. EXPECT_LT(duration.count(), 1000);
  13245. #endif
  13246. }
  13247. // Test: Multi-line data in integration
  13248. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13249. // Endpoint with multi-line data
  13250. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13251. res.set_chunked_content_provider(
  13252. "text/event-stream", [](size_t offset, DataSink &sink) {
  13253. if (offset == 0) {
  13254. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13255. sink.write(event.data(), event.size());
  13256. }
  13257. return false;
  13258. });
  13259. });
  13260. Client client("localhost", get_port());
  13261. sse::SSEClient sse(client, "/multiline-data");
  13262. std::string received_data;
  13263. std::mutex data_mutex;
  13264. sse.on_message([&](const sse::SSEMessage &msg) {
  13265. std::lock_guard<std::mutex> lock(data_mutex);
  13266. received_data = msg.data;
  13267. });
  13268. sse.set_reconnect_interval(100);
  13269. sse.set_max_reconnect_attempts(1);
  13270. sse.start_async();
  13271. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13272. sse.stop();
  13273. std::lock_guard<std::mutex> lock(data_mutex);
  13274. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13275. }
  13276. // Test: Auto-reconnect after server disconnection
  13277. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13278. std::atomic<int> connection_count{0};
  13279. std::atomic<int> message_count{0};
  13280. // Endpoint that sends one event and closes, forcing reconnect
  13281. server_->Get("/reconnect-test",
  13282. [&connection_count](const Request &, Response &res) {
  13283. connection_count.fetch_add(1);
  13284. res.set_chunked_content_provider(
  13285. "text/event-stream", [](size_t offset, DataSink &sink) {
  13286. if (offset == 0) {
  13287. std::string event = "data: hello\n\n";
  13288. sink.write(event.data(), event.size());
  13289. }
  13290. return false; // Close connection after sending
  13291. });
  13292. });
  13293. Client client("localhost", get_port());
  13294. sse::SSEClient sse(client, "/reconnect-test");
  13295. sse.on_message([&message_count](const sse::SSEMessage &) {
  13296. message_count.fetch_add(1);
  13297. });
  13298. sse.set_reconnect_interval(100);
  13299. sse.set_max_reconnect_attempts(3);
  13300. sse.start_async();
  13301. // Wait long enough for multiple reconnects
  13302. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13303. sse.stop();
  13304. // Should have connected multiple times (initial + reconnects)
  13305. EXPECT_GE(connection_count.load(), 2);
  13306. // Should have received messages from multiple connections
  13307. EXPECT_GE(message_count.load(), 2);
  13308. }
  13309. // Test: Last-Event-ID sent on reconnect
  13310. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13311. std::atomic<int> connection_count{0};
  13312. std::vector<std::string> received_last_event_ids;
  13313. std::mutex id_mutex;
  13314. // Endpoint that checks Last-Event-ID header and sends event with ID
  13315. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13316. int conn = connection_count.fetch_add(1);
  13317. // Capture the Last-Event-ID header from each connection
  13318. {
  13319. std::lock_guard<std::mutex> lock(id_mutex);
  13320. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13321. }
  13322. res.set_chunked_content_provider(
  13323. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13324. if (offset == 0) {
  13325. std::string event =
  13326. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13327. sink.write(event.data(), event.size());
  13328. }
  13329. return false;
  13330. });
  13331. });
  13332. Client client("localhost", get_port());
  13333. sse::SSEClient sse(client, "/reconnect-with-id");
  13334. sse.set_reconnect_interval(100);
  13335. sse.set_max_reconnect_attempts(3);
  13336. sse.start_async();
  13337. // Wait for at least 2 connections
  13338. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13339. sse.stop();
  13340. // Verify behavior
  13341. std::lock_guard<std::mutex> lock(id_mutex);
  13342. EXPECT_GE(received_last_event_ids.size(), 2u);
  13343. // First connection should have no Last-Event-ID
  13344. if (!received_last_event_ids.empty()) {
  13345. EXPECT_EQ(received_last_event_ids[0], "");
  13346. }
  13347. // Second connection should have Last-Event-ID from first connection
  13348. if (received_last_event_ids.size() >= 2) {
  13349. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13350. }
  13351. }
  13352. // Test: set_headers updates headers used on reconnect
  13353. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13354. std::vector<std::string> received_tokens;
  13355. std::mutex token_mutex;
  13356. // Endpoint that captures Authorization header
  13357. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13358. {
  13359. std::lock_guard<std::mutex> lock(token_mutex);
  13360. received_tokens.push_back(req.get_header_value("Authorization"));
  13361. }
  13362. res.set_chunked_content_provider(
  13363. "text/event-stream", [](size_t offset, DataSink &sink) {
  13364. if (offset == 0) {
  13365. std::string event = "data: hello\n\n";
  13366. sink.write(event.data(), event.size());
  13367. }
  13368. return false; // Close connection to trigger reconnect
  13369. });
  13370. });
  13371. Client client("localhost", get_port());
  13372. Headers headers = {{"Authorization", "Bearer old-token"}};
  13373. sse::SSEClient sse(client, "/auth-check", headers);
  13374. // Update headers on each successful connection
  13375. sse.on_open(
  13376. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13377. sse.set_reconnect_interval(100);
  13378. sse.set_max_reconnect_attempts(3);
  13379. sse.start_async();
  13380. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13381. sse.stop();
  13382. std::lock_guard<std::mutex> lock(token_mutex);
  13383. ASSERT_GE(received_tokens.size(), 2u);
  13384. // First connection uses original header
  13385. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13386. // Second connection uses updated header from set_headers
  13387. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13388. }
  13389. // Test: 401 allows reconnection (so on_error can refresh headers)
  13390. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13391. std::atomic<int> connection_count{0};
  13392. // Endpoint: returns 401 on first attempt, 200 on second
  13393. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13394. int conn = connection_count.fetch_add(1);
  13395. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13396. res.status = StatusCode::Unauthorized_401;
  13397. res.set_content("Unauthorized", "text/plain");
  13398. return;
  13399. }
  13400. res.set_chunked_content_provider(
  13401. "text/event-stream", [](size_t offset, DataSink &sink) {
  13402. if (offset == 0) {
  13403. std::string event = "data: authenticated\n\n";
  13404. sink.write(event.data(), event.size());
  13405. }
  13406. return false;
  13407. });
  13408. });
  13409. Client client("localhost", get_port());
  13410. Headers headers = {{"Authorization", "Bearer expired"}};
  13411. sse::SSEClient sse(client, "/auth-retry", headers);
  13412. std::atomic<bool> message_received{false};
  13413. // Refresh token on error
  13414. sse.on_error(
  13415. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13416. sse.on_message([&](const sse::SSEMessage &msg) {
  13417. if (msg.data == "authenticated") { message_received.store(true); }
  13418. });
  13419. sse.set_reconnect_interval(100);
  13420. sse.set_max_reconnect_attempts(3);
  13421. sse.start_async();
  13422. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13423. sse.stop();
  13424. // Should have reconnected after 401 and succeeded with new token
  13425. EXPECT_GE(connection_count.load(), 2);
  13426. EXPECT_TRUE(message_received.load());
  13427. }
  13428. TEST(Issue2318Test, EmptyHostString) {
  13429. {
  13430. httplib::Client cli_empty("", PORT);
  13431. auto res = cli_empty.Get("/");
  13432. ASSERT_FALSE(res);
  13433. EXPECT_EQ(httplib::Error::Connection, res.error());
  13434. }
  13435. {
  13436. httplib::Client cli(" ", PORT);
  13437. auto res = cli.Get("/");
  13438. ASSERT_FALSE(res);
  13439. EXPECT_EQ(httplib::Error::Connection, res.error());
  13440. }
  13441. }
  13442. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13443. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13444. Server svr;
  13445. // Set a small payload limit (1KB)
  13446. svr.set_payload_max_length(1024);
  13447. svr.Post("/test", [&](const Request &req, Response &res) {
  13448. res.set_content("Body size: " + std::to_string(req.body.size()),
  13449. "text/plain");
  13450. });
  13451. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13452. auto se = detail::scope_exit([&] {
  13453. svr.stop();
  13454. listen_thread.join();
  13455. });
  13456. svr.wait_until_ready();
  13457. // Create data that compresses well but exceeds limit when decompressed
  13458. // 8KB of repeated null bytes compresses to a very small size
  13459. std::string original_data(8 * 1024, '\0');
  13460. // Compress the data using gzip
  13461. std::string compressed_data;
  13462. detail::gzip_compressor compressor;
  13463. compressor.compress(original_data.data(), original_data.size(), true,
  13464. [&](const char *data, size_t size) {
  13465. compressed_data.append(data, size);
  13466. return true;
  13467. });
  13468. // Verify compression worked (compressed should be much smaller)
  13469. ASSERT_LT(compressed_data.size(), original_data.size());
  13470. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13471. // Send compressed data with Content-Encoding: gzip
  13472. Client cli(HOST, PORT);
  13473. Headers headers = {{"Content-Encoding", "gzip"}};
  13474. auto res =
  13475. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13476. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13477. ASSERT_TRUE(res);
  13478. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13479. }
  13480. #endif
  13481. // ============================================================================
  13482. // OpenSSL-Specific Tests
  13483. // ============================================================================
  13484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13485. X509 *readCertificate(const std::string &strFileName) {
  13486. std::ifstream inStream(strFileName);
  13487. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13488. std::istreambuf_iterator<char>());
  13489. if (strCertPEM.empty()) return (nullptr);
  13490. BIO *pbCert = BIO_new(BIO_s_mem());
  13491. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13492. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13493. BIO_free(pbCert);
  13494. return (pCert);
  13495. }
  13496. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13497. std::ifstream inStream(strFileName);
  13498. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13499. std::istreambuf_iterator<char>());
  13500. if (strPrivateKeyPEM.empty()) return (nullptr);
  13501. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13502. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13503. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13504. BIO_free(pbPrivKey);
  13505. return (pPrivateKey);
  13506. }
  13507. TEST(BindServerTest, UpdateCerts) {
  13508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13509. int port = svr.bind_to_any_port("0.0.0.0");
  13510. ASSERT_TRUE(svr.is_valid());
  13511. ASSERT_TRUE(port > 0);
  13512. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13513. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13514. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13515. ASSERT_TRUE(cert != nullptr);
  13516. ASSERT_TRUE(ca_cert != nullptr);
  13517. ASSERT_TRUE(key != nullptr);
  13518. X509_STORE *cert_store = X509_STORE_new();
  13519. X509_STORE_add_cert(cert_store, ca_cert);
  13520. // svr.update_certs(cert, key, cert_store); // deprecated
  13521. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13522. CLIENT_CA_CERT_FILE);
  13523. ASSERT_TRUE(svr.is_valid());
  13524. svr.stop();
  13525. X509_STORE_free(cert_store);
  13526. X509_free(cert);
  13527. X509_free(ca_cert);
  13528. EVP_PKEY_free(key);
  13529. }
  13530. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13531. // client CA list correctly for TLS handshake
  13532. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13533. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13534. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13535. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13536. ASSERT_TRUE(cert != nullptr);
  13537. ASSERT_TRUE(ca_cert != nullptr);
  13538. ASSERT_TRUE(key != nullptr);
  13539. X509_STORE *cert_store = X509_STORE_new();
  13540. X509_STORE_add_cert(cert_store, ca_cert);
  13541. // Use X509-based constructor (deprecated but should still work correctly)
  13542. #pragma GCC diagnostic push
  13543. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13544. SSLServer svr(cert, key, cert_store);
  13545. #pragma GCC diagnostic pop
  13546. ASSERT_TRUE(svr.is_valid());
  13547. // Verify that client CA list is set in SSL_CTX
  13548. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13549. ASSERT_TRUE(ssl_ctx != nullptr);
  13550. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13551. ASSERT_TRUE(ca_list != nullptr);
  13552. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13553. X509_free(cert);
  13554. X509_free(ca_cert);
  13555. EVP_PKEY_free(key);
  13556. }
  13557. // Test that update_certs() updates client CA list correctly
  13558. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13559. // Start with file-based constructor
  13560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13561. ASSERT_TRUE(svr.is_valid());
  13562. // Initially no client CA list should be set
  13563. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13564. ASSERT_TRUE(ssl_ctx != nullptr);
  13565. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13566. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13567. EXPECT_EQ(0, count_before);
  13568. // Now update with client CA (PEM string)
  13569. std::string cert_pem, key_pem, ca_pem;
  13570. read_file(SERVER_CERT_FILE, cert_pem);
  13571. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13572. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13573. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13574. ASSERT_TRUE(svr.is_valid());
  13575. // Now client CA list should be set
  13576. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13577. ASSERT_TRUE(ca_list_after != nullptr);
  13578. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13579. }
  13580. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13581. // Test that the file-path SSLServer constructor properly sets the client CA
  13582. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13584. ASSERT_TRUE(svr.is_valid());
  13585. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13586. ASSERT_TRUE(ssl_ctx != nullptr);
  13587. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13588. ASSERT_TRUE(ca_list != nullptr);
  13589. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13590. }
  13591. #endif
  13592. // ============================================================================
  13593. // MbedTLS-Specific Tests
  13594. // ============================================================================
  13595. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13596. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13597. using namespace httplib::tls;
  13598. // Track if callback was invoked
  13599. bool callback_invoked = false;
  13600. // The callback receives void* ctx which is actually MbedTlsContext*
  13601. // We can access the mbedtls_ssl_config via the context
  13602. auto setup_callback = [&callback_invoked](void *ctx) {
  13603. callback_invoked = true;
  13604. // Cast to MbedTlsContext* to access the ssl config
  13605. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13606. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13607. // Use static variables to hold certificate data (simplified for test)
  13608. static mbedtls_x509_crt own_cert;
  13609. static mbedtls_pk_context own_key;
  13610. static mbedtls_x509_crt ca_chain;
  13611. static bool initialized = false;
  13612. if (!initialized) {
  13613. mbedtls_x509_crt_init(&own_cert);
  13614. mbedtls_pk_init(&own_key);
  13615. mbedtls_x509_crt_init(&ca_chain);
  13616. // Load server certificate
  13617. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13618. return false;
  13619. }
  13620. // Load server private key
  13621. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13622. #if MBEDTLS_VERSION_MAJOR >= 3
  13623. ,
  13624. mbedtls_ctr_drbg_random, nullptr
  13625. #endif
  13626. ) != 0) {
  13627. return false;
  13628. }
  13629. // Load CA chain for client verification
  13630. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13631. return false;
  13632. }
  13633. initialized = true;
  13634. }
  13635. // Configure the SSL config
  13636. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13637. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13638. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13639. // Set minimum TLS version using mbedTLS native API
  13640. #if MBEDTLS_VERSION_MAJOR >= 3
  13641. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13642. #else
  13643. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13644. MBEDTLS_SSL_MINOR_VERSION_3);
  13645. #endif
  13646. return true;
  13647. };
  13648. SSLServer svr(setup_callback);
  13649. ASSERT_TRUE(svr.is_valid());
  13650. ASSERT_TRUE(callback_invoked);
  13651. svr.Get("/test", [&](const Request &req, Response &res) {
  13652. res.set_content("test", "text/plain");
  13653. auto cert = req.peer_cert();
  13654. ASSERT_TRUE(static_cast<bool>(cert));
  13655. auto common_name = cert.subject_cn();
  13656. EXPECT_EQ("Common Name", common_name);
  13657. });
  13658. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. t.join();
  13662. ASSERT_FALSE(svr.is_running());
  13663. });
  13664. svr.wait_until_ready();
  13665. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13666. cli.enable_server_certificate_verification(false);
  13667. cli.set_connection_timeout(30);
  13668. auto res = cli.Get("/test");
  13669. ASSERT_TRUE(res);
  13670. ASSERT_EQ(StatusCode::OK_200, res->status);
  13671. }
  13672. #endif
  13673. // WebSocket Tests
  13674. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13675. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13676. // defining the meaning of these bits has been negotiated.
  13677. auto make_frame = [](uint8_t first_byte) {
  13678. std::string frame;
  13679. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13680. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13681. frame += "Hello";
  13682. return frame;
  13683. };
  13684. // RSV1 set (0x40)
  13685. {
  13686. detail::BufferStream strm;
  13687. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13688. ws::Opcode opcode;
  13689. std::string payload;
  13690. bool fin;
  13691. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13692. false, 1024));
  13693. }
  13694. // RSV2 set (0x20)
  13695. {
  13696. detail::BufferStream strm;
  13697. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13698. ws::Opcode opcode;
  13699. std::string payload;
  13700. bool fin;
  13701. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13702. false, 1024));
  13703. }
  13704. // RSV3 set (0x10)
  13705. {
  13706. detail::BufferStream strm;
  13707. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13708. ws::Opcode opcode;
  13709. std::string payload;
  13710. bool fin;
  13711. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13712. false, 1024));
  13713. }
  13714. // No RSV bits set - should succeed
  13715. {
  13716. detail::BufferStream strm;
  13717. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13718. ws::Opcode opcode;
  13719. std::string payload;
  13720. bool fin;
  13721. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13722. false, 1024));
  13723. EXPECT_EQ(ws::Opcode::Text, opcode);
  13724. EXPECT_EQ("Hello", payload);
  13725. EXPECT_TRUE(fin);
  13726. }
  13727. }
  13728. TEST(WebSocketTest, ControlFrameValidation) {
  13729. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13730. // payload length <= 125.
  13731. // Ping with FIN=0 - must be rejected
  13732. {
  13733. detail::BufferStream strm;
  13734. std::string frame;
  13735. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13736. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13737. strm.write(frame.data(), frame.size());
  13738. ws::Opcode opcode;
  13739. std::string payload;
  13740. bool fin;
  13741. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13742. false, 1024));
  13743. }
  13744. // Close with FIN=0 - must be rejected
  13745. {
  13746. detail::BufferStream strm;
  13747. std::string frame;
  13748. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13749. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13750. strm.write(frame.data(), frame.size());
  13751. ws::Opcode opcode;
  13752. std::string payload;
  13753. bool fin;
  13754. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13755. false, 1024));
  13756. }
  13757. // Ping with payload_len=126 (extended length) - must be rejected
  13758. {
  13759. detail::BufferStream strm;
  13760. std::string frame;
  13761. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13762. frame += static_cast<char>(126); // payload_len=126 (>125)
  13763. frame += static_cast<char>(0x00); // extended length high byte
  13764. frame += static_cast<char>(126); // extended length low byte
  13765. frame += std::string(126, 'x');
  13766. strm.write(frame.data(), frame.size());
  13767. ws::Opcode opcode;
  13768. std::string payload;
  13769. bool fin;
  13770. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13771. false, 1024));
  13772. }
  13773. // Ping with FIN=1 and payload_len=125 - should succeed
  13774. {
  13775. detail::BufferStream strm;
  13776. std::string frame;
  13777. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13778. frame += static_cast<char>(125); // payload_len=125
  13779. frame += std::string(125, 'x');
  13780. strm.write(frame.data(), frame.size());
  13781. ws::Opcode opcode;
  13782. std::string payload;
  13783. bool fin;
  13784. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13785. false, 1024));
  13786. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13787. EXPECT_EQ(125u, payload.size());
  13788. EXPECT_TRUE(fin);
  13789. }
  13790. }
  13791. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13792. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13793. // length MUST be 0.
  13794. // MSB set - must be rejected
  13795. {
  13796. detail::BufferStream strm;
  13797. std::string frame;
  13798. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13799. frame += static_cast<char>(127); // 64-bit extended length
  13800. frame += static_cast<char>(0x80); // MSB set (invalid)
  13801. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13802. strm.write(frame.data(), frame.size());
  13803. ws::Opcode opcode;
  13804. std::string payload;
  13805. bool fin;
  13806. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13807. false, 1024));
  13808. }
  13809. // MSB clear - should pass length parsing (will be rejected by max_len,
  13810. // but that's a different check; use a small length to verify)
  13811. {
  13812. detail::BufferStream strm;
  13813. std::string frame;
  13814. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13815. frame += static_cast<char>(127); // 64-bit extended length
  13816. frame += std::string(7, '\0'); // high bytes = 0
  13817. frame += static_cast<char>(0x03); // length = 3
  13818. frame += "abc";
  13819. strm.write(frame.data(), frame.size());
  13820. ws::Opcode opcode;
  13821. std::string payload;
  13822. bool fin;
  13823. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13824. false, 1024));
  13825. EXPECT_EQ(ws::Opcode::Text, opcode);
  13826. EXPECT_EQ("abc", payload);
  13827. }
  13828. }
  13829. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13830. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13831. // Valid UTF-8
  13832. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13833. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13834. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13835. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13836. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13837. // Invalid UTF-8
  13838. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13839. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13840. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13841. EXPECT_FALSE(
  13842. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13843. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13844. }
  13845. TEST(WebSocketTest, ConnectAndDisconnect) {
  13846. Server svr;
  13847. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13848. std::string msg;
  13849. while (ws.read(msg)) {}
  13850. });
  13851. auto port = svr.bind_to_any_port(HOST);
  13852. std::thread t([&]() { svr.listen_after_bind(); });
  13853. svr.wait_until_ready();
  13854. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13855. ASSERT_TRUE(client.connect());
  13856. EXPECT_TRUE(client.is_open());
  13857. client.close();
  13858. EXPECT_FALSE(client.is_open());
  13859. svr.stop();
  13860. t.join();
  13861. }
  13862. TEST(WebSocketTest, ValidURL) {
  13863. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13864. EXPECT_TRUE(ws1.is_valid());
  13865. ws::WebSocketClient ws2("ws://example.com/path");
  13866. EXPECT_TRUE(ws2.is_valid());
  13867. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13868. EXPECT_TRUE(ws3.is_valid());
  13869. #ifdef CPPHTTPLIB_SSL_ENABLED
  13870. ws::WebSocketClient wss1("wss://example.com/path");
  13871. EXPECT_TRUE(wss1.is_valid());
  13872. ws::WebSocketClient wss2("wss://example.com:443/path");
  13873. EXPECT_TRUE(wss2.is_valid());
  13874. #endif
  13875. }
  13876. TEST(WebSocketTest, InvalidURL) {
  13877. // No scheme
  13878. ws::WebSocketClient ws1("localhost:8080/path");
  13879. EXPECT_FALSE(ws1.is_valid());
  13880. // No path
  13881. ws::WebSocketClient ws2("ws://localhost:8080");
  13882. EXPECT_FALSE(ws2.is_valid());
  13883. // Empty string
  13884. ws::WebSocketClient ws3("");
  13885. EXPECT_FALSE(ws3.is_valid());
  13886. // Missing host
  13887. ws::WebSocketClient ws4("ws://:8080/path");
  13888. EXPECT_FALSE(ws4.is_valid());
  13889. // Port number overflow — should not crash
  13890. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13891. EXPECT_FALSE(ws5.is_valid());
  13892. // Port out of range
  13893. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13894. EXPECT_FALSE(ws6.is_valid());
  13895. }
  13896. TEST(WebSocketTest, UnsupportedScheme) {
  13897. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13898. ws::WebSocketClient ws1("http://localhost:8080/path");
  13899. EXPECT_FALSE(ws1.is_valid());
  13900. ws::WebSocketClient ws2("https://localhost:8080/path");
  13901. EXPECT_FALSE(ws2.is_valid());
  13902. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13903. EXPECT_FALSE(ws3.is_valid());
  13904. #else
  13905. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13906. std::invalid_argument);
  13907. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13908. std::invalid_argument);
  13909. #endif
  13910. }
  13911. TEST(WebSocketTest, ConnectWhenInvalid) {
  13912. ws::WebSocketClient ws("not a valid url");
  13913. EXPECT_FALSE(ws.is_valid());
  13914. EXPECT_FALSE(ws.connect());
  13915. }
  13916. TEST(WebSocketTest, DefaultPort) {
  13917. ws::WebSocketClient ws1("ws://example.com/path");
  13918. EXPECT_TRUE(ws1.is_valid());
  13919. // ws:// defaults to port 80 (verified by successful parse)
  13920. #ifdef CPPHTTPLIB_SSL_ENABLED
  13921. ws::WebSocketClient ws2("wss://example.com/path");
  13922. EXPECT_TRUE(ws2.is_valid());
  13923. // wss:// defaults to port 443 (verified by successful parse)
  13924. #endif
  13925. }
  13926. TEST(WebSocketTest, IPv6LiteralAddress) {
  13927. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13928. EXPECT_TRUE(ws1.is_valid());
  13929. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13930. EXPECT_TRUE(ws2.is_valid());
  13931. }
  13932. TEST(WebSocketTest, ComplexPath) {
  13933. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13934. EXPECT_TRUE(ws1.is_valid());
  13935. ws::WebSocketClient ws2("ws://localhost:8080/");
  13936. EXPECT_TRUE(ws2.is_valid());
  13937. }
  13938. class WebSocketIntegrationTest : public ::testing::Test {
  13939. protected:
  13940. void SetUp() override {
  13941. server_ = httplib::detail::make_unique<Server>();
  13942. setup_server();
  13943. start_server();
  13944. }
  13945. void TearDown() override {
  13946. server_->stop();
  13947. if (server_thread_.joinable()) { server_thread_.join(); }
  13948. }
  13949. void setup_server() {
  13950. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13951. std::string msg;
  13952. ws::ReadResult ret;
  13953. while ((ret = ws.read(msg))) {
  13954. if (ret == ws::Binary) {
  13955. ws.send(msg.data(), msg.size());
  13956. } else {
  13957. ws.send(msg);
  13958. }
  13959. }
  13960. });
  13961. server_->WebSocket("/ws-echo-string",
  13962. [](const Request &, ws::WebSocket &ws) {
  13963. std::string msg;
  13964. while (ws.read(msg)) {
  13965. ws.send("echo: " + msg);
  13966. }
  13967. });
  13968. server_->WebSocket(
  13969. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13970. // Echo back request metadata
  13971. ws.send("path:" + req.path);
  13972. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13973. std::string msg;
  13974. while (ws.read(msg)) {}
  13975. });
  13976. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13977. std::string msg;
  13978. ws.read(msg); // wait for a message
  13979. ws.close();
  13980. });
  13981. server_->WebSocket("/ws-close-status",
  13982. [](const Request &, ws::WebSocket &ws) {
  13983. std::string msg;
  13984. ws.read(msg); // wait for a message
  13985. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13986. });
  13987. server_->WebSocket(
  13988. "/ws-subprotocol",
  13989. [](const Request &, ws::WebSocket &ws) {
  13990. std::string msg;
  13991. while (ws.read(msg)) {
  13992. ws.send(msg);
  13993. }
  13994. },
  13995. [](const std::vector<std::string> &protocols) -> std::string {
  13996. for (const auto &p : protocols) {
  13997. if (p == "graphql-ws") { return p; }
  13998. }
  13999. return "";
  14000. });
  14001. }
  14002. void start_server() {
  14003. port_ = server_->bind_to_any_port(HOST);
  14004. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14005. server_->wait_until_ready();
  14006. }
  14007. std::unique_ptr<Server> server_;
  14008. std::thread server_thread_;
  14009. int port_ = 0;
  14010. };
  14011. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14013. "/ws-echo");
  14014. ASSERT_TRUE(client.connect());
  14015. ASSERT_TRUE(client.is_open());
  14016. ASSERT_TRUE(client.send("Hello WebSocket"));
  14017. std::string msg;
  14018. EXPECT_EQ(ws::Text, client.read(msg));
  14019. EXPECT_EQ("Hello WebSocket", msg);
  14020. client.close();
  14021. }
  14022. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14024. "/ws-echo");
  14025. ASSERT_TRUE(client.connect());
  14026. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14027. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14028. std::string msg;
  14029. EXPECT_EQ(ws::Binary, client.read(msg));
  14030. EXPECT_EQ(binary_data, msg);
  14031. client.close();
  14032. }
  14033. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14035. "/ws-echo");
  14036. ASSERT_TRUE(client.connect());
  14037. for (int i = 0; i < 10; i++) {
  14038. auto text = "message " + std::to_string(i);
  14039. ASSERT_TRUE(client.send(text));
  14040. std::string msg;
  14041. ASSERT_TRUE(client.read(msg));
  14042. EXPECT_EQ(text, msg);
  14043. }
  14044. client.close();
  14045. }
  14046. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14048. "/ws-close");
  14049. ASSERT_TRUE(client.connect());
  14050. // Send a message to trigger the server to close
  14051. ASSERT_TRUE(client.send("trigger close"));
  14052. // The server will close, so read should return false
  14053. std::string msg;
  14054. EXPECT_FALSE(client.read(msg));
  14055. EXPECT_FALSE(client.is_open());
  14056. }
  14057. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14059. "/ws-echo");
  14060. ASSERT_TRUE(client.connect());
  14061. // 128KB message
  14062. std::string large_data(128 * 1024, 'X');
  14063. ASSERT_TRUE(client.send(large_data));
  14064. std::string msg;
  14065. ASSERT_TRUE(client.read(msg));
  14066. EXPECT_EQ(large_data, msg);
  14067. client.close();
  14068. }
  14069. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14070. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14071. "/ws-echo");
  14072. ASSERT_TRUE(client.connect());
  14073. const int num_threads = 4;
  14074. std::vector<std::thread> threads;
  14075. std::atomic<int> send_count{0};
  14076. for (int t = 0; t < num_threads; t++) {
  14077. threads.emplace_back([&client, &send_count, t]() {
  14078. for (int i = 0; i < 5; i++) {
  14079. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14080. if (client.send(text)) { send_count++; }
  14081. }
  14082. });
  14083. }
  14084. for (auto &th : threads) {
  14085. th.join();
  14086. }
  14087. int received = 0;
  14088. std::string msg;
  14089. while (received < send_count.load()) {
  14090. if (!client.read(msg)) { break; }
  14091. received++;
  14092. }
  14093. EXPECT_EQ(send_count.load(), received);
  14094. client.close();
  14095. }
  14096. TEST_F(WebSocketIntegrationTest, ReadString) {
  14097. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14098. "/ws-echo-string");
  14099. ASSERT_TRUE(client.connect());
  14100. ASSERT_TRUE(client.send("hello"));
  14101. std::string msg;
  14102. ASSERT_TRUE(client.read(msg));
  14103. EXPECT_EQ("echo: hello", msg);
  14104. ASSERT_TRUE(client.send("world"));
  14105. ASSERT_TRUE(client.read(msg));
  14106. EXPECT_EQ("echo: world", msg);
  14107. client.close();
  14108. }
  14109. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14110. Headers headers = {{"X-Test-Header", "test-value"}};
  14111. ws::WebSocketClient client(
  14112. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14113. ASSERT_TRUE(client.connect());
  14114. std::string msg;
  14115. ASSERT_TRUE(client.read(msg));
  14116. EXPECT_EQ("path:/ws-request-info", msg);
  14117. ASSERT_TRUE(client.read(msg));
  14118. EXPECT_EQ("header:test-value", msg);
  14119. client.close();
  14120. }
  14121. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14123. "/ws-echo");
  14124. client.set_read_timeout(1, 0); // 1 second
  14125. ASSERT_TRUE(client.connect());
  14126. // Don't send anything — server echo handler waits for a message,
  14127. // so read() should time out and return false.
  14128. std::string msg;
  14129. EXPECT_FALSE(client.read(msg));
  14130. }
  14131. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14132. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14133. "/ws-echo");
  14134. client.set_read_timeout(5, 0);
  14135. ASSERT_TRUE(client.connect());
  14136. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14137. // The server should reject it and close the connection.
  14138. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14139. client.send(oversized);
  14140. // The server's read() should have failed due to payload limit,
  14141. // so our read() should return false (connection closed).
  14142. std::string msg;
  14143. EXPECT_FALSE(client.read(msg));
  14144. }
  14145. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14147. "/ws-echo");
  14148. client.set_read_timeout(10, 0);
  14149. ASSERT_TRUE(client.connect());
  14150. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14151. // This should succeed.
  14152. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14153. ASSERT_TRUE(client.send(at_limit));
  14154. std::string msg;
  14155. ASSERT_TRUE(client.read(msg));
  14156. EXPECT_EQ(at_limit.size(), msg.size());
  14157. client.close();
  14158. }
  14159. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14161. "/nonexistent");
  14162. EXPECT_FALSE(client.connect());
  14163. EXPECT_FALSE(client.is_open());
  14164. }
  14165. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14166. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14167. "/ws-echo");
  14168. ASSERT_TRUE(client.connect());
  14169. ASSERT_TRUE(client.send(""));
  14170. std::string msg;
  14171. EXPECT_EQ(ws::Text, client.read(msg));
  14172. EXPECT_EQ("", msg);
  14173. client.close();
  14174. }
  14175. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14176. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14177. "/ws-echo");
  14178. // First connection
  14179. ASSERT_TRUE(client.connect());
  14180. ASSERT_TRUE(client.send("first"));
  14181. std::string msg;
  14182. ASSERT_TRUE(client.read(msg));
  14183. EXPECT_EQ("first", msg);
  14184. client.close();
  14185. EXPECT_FALSE(client.is_open());
  14186. // Reconnect using the same client object
  14187. ASSERT_TRUE(client.connect());
  14188. ASSERT_TRUE(client.is_open());
  14189. ASSERT_TRUE(client.send("second"));
  14190. ASSERT_TRUE(client.read(msg));
  14191. EXPECT_EQ("second", msg);
  14192. client.close();
  14193. }
  14194. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14196. "/ws-close-status");
  14197. ASSERT_TRUE(client.connect());
  14198. // Trigger the server to close with GoingAway status
  14199. ASSERT_TRUE(client.send("trigger"));
  14200. // read() should return false after receiving the close frame
  14201. std::string msg;
  14202. EXPECT_FALSE(client.read(msg));
  14203. EXPECT_FALSE(client.is_open());
  14204. }
  14205. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14207. "/ws-echo");
  14208. ASSERT_TRUE(client.connect());
  14209. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14210. EXPECT_FALSE(client.is_open());
  14211. }
  14212. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14213. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14214. ws::WebSocketClient client(
  14215. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14216. ASSERT_TRUE(client.connect());
  14217. // Server should have selected graphql-ws
  14218. EXPECT_EQ("graphql-ws", client.subprotocol());
  14219. client.close();
  14220. }
  14221. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14222. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14223. ws::WebSocketClient client(
  14224. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14225. ASSERT_TRUE(client.connect());
  14226. // Server should not have selected any subprotocol
  14227. EXPECT_TRUE(client.subprotocol().empty());
  14228. client.close();
  14229. }
  14230. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14231. // Connect without requesting any subprotocol
  14232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14233. "/ws-subprotocol");
  14234. ASSERT_TRUE(client.connect());
  14235. EXPECT_TRUE(client.subprotocol().empty());
  14236. client.close();
  14237. }
  14238. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14239. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14240. "/ws-echo");
  14241. client.set_tcp_nodelay(true);
  14242. client.set_address_family(AF_INET);
  14243. client.set_connection_timeout(3, 0);
  14244. bool socket_options_called = false;
  14245. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14246. ASSERT_TRUE(client.connect());
  14247. ASSERT_TRUE(client.is_open());
  14248. EXPECT_TRUE(socket_options_called);
  14249. ASSERT_TRUE(client.send("hello"));
  14250. std::string msg;
  14251. auto result = client.read(msg);
  14252. EXPECT_EQ(result, ws::ReadResult::Text);
  14253. EXPECT_EQ(msg, "hello");
  14254. client.close();
  14255. }
  14256. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14257. Server svr;
  14258. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14259. if (!req.has_header("Authorization")) {
  14260. res.status = StatusCode::Unauthorized_401;
  14261. res.set_content("Unauthorized", "text/plain");
  14262. return Server::HandlerResponse::Handled;
  14263. }
  14264. return Server::HandlerResponse::Unhandled;
  14265. });
  14266. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14267. std::string msg;
  14268. while (ws.read(msg)) {
  14269. ws.send(msg);
  14270. }
  14271. });
  14272. auto port = svr.bind_to_any_port("localhost");
  14273. std::thread t([&]() { svr.listen_after_bind(); });
  14274. svr.wait_until_ready();
  14275. // Without Authorization header - should be rejected before upgrade
  14276. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14277. EXPECT_FALSE(client1.connect());
  14278. // With Authorization header - should succeed
  14279. Headers headers = {{"Authorization", "Bearer token123"}};
  14280. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14281. headers);
  14282. ASSERT_TRUE(client2.connect());
  14283. ASSERT_TRUE(client2.send("hello"));
  14284. std::string msg;
  14285. ASSERT_TRUE(client2.read(msg));
  14286. EXPECT_EQ("hello", msg);
  14287. client2.close();
  14288. svr.stop();
  14289. t.join();
  14290. }
  14291. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14292. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14293. protected:
  14294. void SetUp() override {
  14295. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14296. SERVER_PRIVATE_KEY_FILE);
  14297. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14298. std::string msg;
  14299. ws::ReadResult ret;
  14300. while ((ret = ws.read(msg))) {
  14301. if (ret == ws::Binary) {
  14302. ws.send(msg.data(), msg.size());
  14303. } else {
  14304. ws.send(msg);
  14305. }
  14306. }
  14307. });
  14308. port_ = server_->bind_to_any_port(HOST);
  14309. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14310. server_->wait_until_ready();
  14311. }
  14312. void TearDown() override {
  14313. server_->stop();
  14314. if (server_thread_.joinable()) { server_thread_.join(); }
  14315. }
  14316. std::unique_ptr<SSLServer> server_;
  14317. std::thread server_thread_;
  14318. int port_ = 0;
  14319. };
  14320. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14321. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14322. "/ws-echo");
  14323. client.enable_server_certificate_verification(false);
  14324. ASSERT_TRUE(client.connect());
  14325. ASSERT_TRUE(client.is_open());
  14326. ASSERT_TRUE(client.send("Hello WSS"));
  14327. std::string msg;
  14328. EXPECT_EQ(ws::Text, client.read(msg));
  14329. EXPECT_EQ("Hello WSS", msg);
  14330. client.close();
  14331. }
  14332. #endif
  14333. #if !defined(_WIN32)
  14334. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14335. auto secret_dir = std::string("./symlink_test_secret");
  14336. auto served_dir = std::string("./symlink_test_served");
  14337. auto secret_file = secret_dir + "/secret.txt";
  14338. auto symlink_path = served_dir + "/escape";
  14339. // Setup: create directories and files
  14340. mkdir(secret_dir.c_str(), 0755);
  14341. mkdir(served_dir.c_str(), 0755);
  14342. {
  14343. std::ofstream ofs(secret_file);
  14344. ofs << "SECRET_DATA";
  14345. }
  14346. // Create symlink using absolute path so it resolves correctly
  14347. char abs_secret[PATH_MAX];
  14348. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14349. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14350. auto se = detail::scope_exit([&] {
  14351. unlink(symlink_path.c_str());
  14352. unlink(secret_file.c_str());
  14353. rmdir(served_dir.c_str());
  14354. rmdir(secret_dir.c_str());
  14355. });
  14356. Server svr;
  14357. svr.set_mount_point("/", served_dir);
  14358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14359. auto se2 = detail::scope_exit([&] {
  14360. svr.stop();
  14361. listen_thread.join();
  14362. });
  14363. svr.wait_until_ready();
  14364. Client cli("localhost", PORT);
  14365. // Symlink pointing outside base dir should be blocked
  14366. auto res = cli.Get("/escape/secret.txt");
  14367. ASSERT_TRUE(res);
  14368. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14369. }
  14370. #endif
  14371. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14372. // A GET request with Content-Length to a static file handler must have its
  14373. // body drained before the keep-alive connection is reused. Otherwise the
  14374. // unread body bytes are interpreted as the next HTTP request.
  14375. //
  14376. // The body is sent AFTER receiving the first response (as in the original
  14377. // PoC) so that the stream_line_reader cannot buffer it together with the
  14378. // headers of the first request.
  14379. Server svr;
  14380. svr.set_mount_point("/", "./www");
  14381. std::atomic<int> smuggled_count(0);
  14382. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14383. smuggled_count++;
  14384. res.set_content("oops", "text/plain");
  14385. });
  14386. auto port = svr.bind_to_any_port("localhost");
  14387. thread t = thread([&] { svr.listen_after_bind(); });
  14388. auto se = detail::scope_exit([&] {
  14389. svr.stop();
  14390. t.join();
  14391. });
  14392. svr.wait_until_ready();
  14393. auto error = Error::Success;
  14394. auto sock = detail::create_client_socket(
  14395. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14396. /*connection_timeout_sec=*/2, 0,
  14397. /*read_timeout_sec=*/2, 0,
  14398. /*write_timeout_sec=*/2, 0, std::string(), error);
  14399. ASSERT_NE(INVALID_SOCKET, sock);
  14400. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14401. // The "smuggled" request will be sent as the body of the outer GET
  14402. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14403. "Host: localhost\r\n"
  14404. "Connection: close\r\n"
  14405. "\r\n";
  14406. // Step 1: Send only the outer request headers (no body yet)
  14407. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14408. "Host: localhost\r\n"
  14409. "Content-Length: " +
  14410. std::to_string(smuggled.size()) +
  14411. "\r\n"
  14412. "\r\n";
  14413. auto sent =
  14414. send(sock, outer_headers.data(), outer_headers.size(), MSG_NOSIGNAL);
  14415. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14416. // Step 2: Read the first response (server serves file without reading body)
  14417. std::string first_response;
  14418. char buf[4096];
  14419. for (;;) {
  14420. auto n = recv(sock, buf, sizeof(buf), 0);
  14421. if (n <= 0) break;
  14422. first_response.append(buf, static_cast<size_t>(n));
  14423. // Stop once we have a complete response (headers + body)
  14424. auto hdr_end = first_response.find("\r\n\r\n");
  14425. if (hdr_end != std::string::npos) {
  14426. // Check for Content-Length to know when the body is complete
  14427. auto cl_pos = first_response.find("Content-Length:");
  14428. if (cl_pos != std::string::npos) {
  14429. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14430. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14431. auto cl = std::stoul(
  14432. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14433. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14434. } else {
  14435. break; // No Content-Length, assume headers-only response
  14436. }
  14437. }
  14438. }
  14439. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14440. // Step 3: Now send the body, which looks like a new HTTP request.
  14441. // On a vulnerable server the keep-alive loop reads this as a second request.
  14442. sent = send(sock, smuggled.data(), smuggled.size(), MSG_NOSIGNAL);
  14443. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14444. // Step 4: Try to read a second response (should NOT exist after fix)
  14445. std::string second_response;
  14446. for (;;) {
  14447. auto n = recv(sock, buf, sizeof(buf), 0);
  14448. if (n <= 0) break;
  14449. second_response.append(buf, static_cast<size_t>(n));
  14450. }
  14451. // The smuggled request must NOT have been processed
  14452. EXPECT_EQ(0, smuggled_count.load());
  14453. }
  14454. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14455. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14456. // must be rejected with 400 Bad Request.
  14457. Server svr;
  14458. svr.Post("/test", [&](const Request &, Response &res) {
  14459. res.set_content("ok", "text/plain");
  14460. });
  14461. thread t = thread([&] { svr.listen(HOST, PORT); });
  14462. auto se = detail::scope_exit([&] {
  14463. svr.stop();
  14464. t.join();
  14465. ASSERT_FALSE(svr.is_running());
  14466. });
  14467. svr.wait_until_ready();
  14468. // Exact "chunked"
  14469. {
  14470. auto req = "POST /test HTTP/1.1\r\n"
  14471. "Host: localhost\r\n"
  14472. "Content-Length: 5\r\n"
  14473. "Transfer-Encoding: chunked\r\n"
  14474. "Connection: close\r\n"
  14475. "\r\n"
  14476. "hello";
  14477. std::string response;
  14478. ASSERT_TRUE(send_request(1, req, &response));
  14479. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14480. response.substr(0, response.find("\r\n")));
  14481. }
  14482. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14483. {
  14484. auto req = "POST /test HTTP/1.1\r\n"
  14485. "Host: localhost\r\n"
  14486. "Content-Length: 5\r\n"
  14487. "Transfer-Encoding: gzip, chunked\r\n"
  14488. "Connection: close\r\n"
  14489. "\r\n"
  14490. "hello";
  14491. std::string response;
  14492. ASSERT_TRUE(send_request(1, req, &response));
  14493. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14494. response.substr(0, response.find("\r\n")));
  14495. }
  14496. }