test.cc 534 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(ClientTest, MoveConstructible) {
  269. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  270. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  271. }
  272. TEST(ClientTest, MoveAssignable) {
  273. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  274. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  275. }
  276. #ifdef _WIN32
  277. TEST(StartupTest, WSAStartup) {
  278. WSADATA wsaData;
  279. int ret = WSAStartup(0x0002, &wsaData);
  280. ASSERT_EQ(0, ret);
  281. }
  282. #endif
  283. TEST(DecodePathTest, PercentCharacter) {
  284. EXPECT_EQ(
  285. decode_path_component(
  286. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  287. U8("descrip=Gastos áéíóúñÑ 6"));
  288. }
  289. TEST(DecodePathTest, PercentCharacterNUL) {
  290. string expected;
  291. expected.push_back('x');
  292. expected.push_back('\0');
  293. expected.push_back('x');
  294. EXPECT_EQ(decode_path_component("x%00x"), expected);
  295. }
  296. TEST(DecodePathTest, UnicodeEncoding) {
  297. // %u0041 = 'A' (1-byte UTF-8)
  298. EXPECT_EQ("A", decode_path_component("%u0041"));
  299. // %u00E9 = 'é' (2-byte UTF-8)
  300. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  301. // %u3042 = 'あ' (3-byte UTF-8)
  302. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  303. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  304. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  305. // %uD800 = surrogate (invalid, silently dropped)
  306. EXPECT_EQ("", decode_path_component("%uD800"));
  307. }
  308. TEST(SanitizeFilenameTest, VariousPatterns) {
  309. // Path traversal
  310. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  311. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  312. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  313. // Normal and edge cases
  314. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  315. EXPECT_EQ("filename.txt",
  316. httplib::sanitize_filename("/path/to/filename.txt"));
  317. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  318. EXPECT_EQ("", httplib::sanitize_filename(".."));
  319. EXPECT_EQ("", httplib::sanitize_filename(""));
  320. // Null bytes stripped
  321. EXPECT_EQ("safe.txt",
  322. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  323. // Whitespace-only rejected
  324. EXPECT_EQ("", httplib::sanitize_filename(" "));
  325. }
  326. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  327. string unescapedCharacters = "-_.!~*'()";
  328. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  329. }
  330. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  331. string reservedCharacters = ";,/?:@&=+$";
  332. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  333. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  334. }
  335. TEST(ClientQueryOrder, PreserveOrder) {
  336. // This test reproduces Issue #2259: client may reorder query parameters
  337. // when sending a GET request. The expected behavior is that the client
  338. // preserves the original query string order when the caller supplied it
  339. // as part of the path.
  340. Server svr;
  341. svr.Get("/", [&](const Request &req, Response &res) {
  342. // Echo back the raw target so the test can assert ordering
  343. res.set_content(req.target, "text/plain");
  344. });
  345. std::thread t{[&] { svr.listen(HOST, PORT); }};
  346. auto se = detail::scope_exit([&] {
  347. svr.stop();
  348. t.join();
  349. ASSERT_FALSE(svr.is_running());
  350. });
  351. svr.wait_until_ready();
  352. Client cli(HOST, PORT);
  353. ASSERT_TRUE(cli.is_valid());
  354. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  355. auto res = cli.Get(original);
  356. ASSERT_TRUE(res);
  357. // Expect the echoed target to exactly match the original path (order
  358. // preserved)
  359. EXPECT_EQ(res->body, original);
  360. }
  361. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  362. string chineseCharacters = U8("中国語");
  363. string russianCharacters = U8("дом");
  364. string brazilianCharacters = U8("óculos");
  365. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  366. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  367. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  368. "%D0%B4%D0%BE%D0%BC");
  369. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  370. }
  371. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  372. string unescapedCharacters = "-_.!~*'()";
  373. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  374. }
  375. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  376. string reservedCharacters = ";,/?:@&=+$";
  377. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  378. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  379. }
  380. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  381. string chineseCharacters = U8("中国語");
  382. string russianCharacters = U8("дом");
  383. string brazilianCharacters = U8("óculos");
  384. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  385. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  386. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  387. "%D0%B4%D0%BE%D0%BC");
  388. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  389. }
  390. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  391. // Issue #2082 use case: encoding path component with ampersand
  392. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  393. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  394. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  395. }
  396. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  397. string unescapedCharacters = "-_.!~*'()";
  398. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  399. }
  400. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  401. string reservedCharacters = ";,/?:@&=+$#";
  402. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  403. }
  404. TEST(EncodeUriTest, TestUTF8Characters) {
  405. string chineseCharacters = U8("中国語");
  406. string russianCharacters = U8("дом");
  407. string brazilianCharacters = U8("óculos");
  408. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  409. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  410. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  411. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  412. }
  413. TEST(EncodeUriTest, TestCompleteUri) {
  414. string uri =
  415. "https://example.com/path/to/resource?query=value&param=test#fragment";
  416. EXPECT_EQ(
  417. httplib::encode_uri(uri),
  418. "https://example.com/path/to/resource?query=value&param=test#fragment");
  419. }
  420. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  421. string uri =
  422. "https://example.com/path with spaces/file name.html?q=hello world";
  423. EXPECT_EQ(httplib::encode_uri(uri),
  424. "https://example.com/path%20with%20spaces/"
  425. "file%20name.html?q=hello%20world");
  426. }
  427. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  428. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  429. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  430. }
  431. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  436. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  437. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  438. string encodedBrazilian = "%C3%B3culos";
  439. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  441. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  442. }
  443. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  444. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  445. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  446. "Piri Tommy Villiers - on & on");
  447. }
  448. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  449. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  450. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  451. }
  452. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  453. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  454. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  455. }
  456. TEST(DecodeUriTest, TestUTF8Characters) {
  457. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  458. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  459. string encodedBrazilian = "%C3%B3culos";
  460. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  461. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  462. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  463. }
  464. TEST(DecodeUriTest, TestCompleteUri) {
  465. string encodedUri = "https://example.com/path%20with%20spaces/"
  466. "file%20name.html?q=hello%20world";
  467. EXPECT_EQ(
  468. httplib::decode_uri(encodedUri),
  469. "https://example.com/path with spaces/file name.html?q=hello world");
  470. }
  471. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  472. string original =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. string encoded = httplib::encode_uri(original);
  475. string decoded = httplib::decode_uri(encoded);
  476. EXPECT_EQ(decoded, original);
  477. }
  478. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  479. string original = "Piri Tommy Villiers - on & on";
  480. string encoded = httplib::encode_uri_component(original);
  481. string decoded = httplib::decode_uri_component(encoded);
  482. EXPECT_EQ(decoded, original);
  483. }
  484. TEST(TrimTests, TrimStringTests) {
  485. EXPECT_EQ("abc", detail::trim_copy("abc"));
  486. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  487. EXPECT_TRUE(detail::trim_copy("").empty());
  488. }
  489. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  490. // Simple case without quality values
  491. std::vector<std::string> result1;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html,application/json,text/plain", result1));
  494. EXPECT_EQ(result1.size(), 3U);
  495. EXPECT_EQ(result1[0], "text/html");
  496. EXPECT_EQ(result1[1], "application/json");
  497. EXPECT_EQ(result1[2], "text/plain");
  498. // With quality values
  499. std::vector<std::string> result2;
  500. EXPECT_TRUE(detail::parse_accept_header(
  501. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  502. EXPECT_EQ(result2.size(), 3U);
  503. EXPECT_EQ(result2[0], "application/json"); // highest q value
  504. EXPECT_EQ(result2[1], "text/html");
  505. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  506. }
  507. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  508. // Mixed with and without quality values
  509. std::vector<std::string> result;
  510. EXPECT_TRUE(detail::parse_accept_header(
  511. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  512. EXPECT_EQ(result.size(), 3U);
  513. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  514. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  515. EXPECT_EQ(result[2], "application/json"); // q=0.5
  516. }
  517. TEST(ParseAcceptHeaderTest, EdgeCases) {
  518. // Empty header
  519. std::vector<std::string> empty_result;
  520. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  521. EXPECT_TRUE(empty_result.empty());
  522. // Single type
  523. std::vector<std::string> single_result;
  524. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  525. EXPECT_EQ(single_result.size(), 1U);
  526. EXPECT_EQ(single_result[0], "application/json");
  527. // Wildcard types
  528. std::vector<std::string> wildcard_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  531. EXPECT_EQ(wildcard_result.size(), 3U);
  532. EXPECT_EQ(wildcard_result[0], "application/json");
  533. EXPECT_EQ(wildcard_result[1], "text/*");
  534. EXPECT_EQ(wildcard_result[2], "*/*");
  535. }
  536. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  537. // Common browser Accept header
  538. std::vector<std::string> browser_result;
  539. EXPECT_TRUE(
  540. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  541. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  542. browser_result));
  543. EXPECT_EQ(browser_result.size(), 6U);
  544. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  548. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  549. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  550. // API client header
  551. std::vector<std::string> api_result;
  552. EXPECT_TRUE(detail::parse_accept_header(
  553. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  554. api_result));
  555. EXPECT_EQ(api_result.size(), 3U);
  556. EXPECT_EQ(api_result[0], "application/json");
  557. EXPECT_EQ(api_result[1], "application/xml");
  558. EXPECT_EQ(api_result[2], "text/plain");
  559. }
  560. TEST(ParseAcceptHeaderTest, SpecialCases) {
  561. // Quality value with 3 decimal places
  562. std::vector<std::string> decimal_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  565. EXPECT_EQ(decimal_result.size(), 2U);
  566. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  567. EXPECT_EQ(decimal_result[1], "text/html");
  568. // Zero quality (should still be included but with lowest priority)
  569. std::vector<std::string> zero_q_result;
  570. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  571. zero_q_result));
  572. EXPECT_EQ(zero_q_result.size(), 2U);
  573. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  574. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  575. // No spaces around commas
  576. std::vector<std::string> no_space_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  579. no_space_result));
  580. EXPECT_EQ(no_space_result.size(), 3U);
  581. EXPECT_EQ(no_space_result[0], "text/html");
  582. EXPECT_EQ(no_space_result[1], "application/json");
  583. EXPECT_EQ(no_space_result[2], "text/plain");
  584. }
  585. TEST(ParseAcceptHeaderTest, InvalidCases) {
  586. std::vector<std::string> result;
  587. // Invalid quality value (> 1.0)
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  590. // Invalid quality value (< 0.0)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  593. // Invalid quality value (not a number)
  594. EXPECT_FALSE(detail::parse_accept_header(
  595. "text/html;q=invalid,application/json", result));
  596. // Empty quality value
  597. EXPECT_FALSE(
  598. detail::parse_accept_header("text/html;q=,application/json", result));
  599. // Invalid media type format (no slash and not wildcard)
  600. EXPECT_FALSE(
  601. detail::parse_accept_header("invalidtype,application/json", result));
  602. // Empty media type
  603. result.clear();
  604. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  605. // Only commas
  606. result.clear();
  607. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  608. // Valid cases should still work
  609. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  610. EXPECT_EQ(result.size(), 1U);
  611. EXPECT_EQ(result[0], "*/*");
  612. EXPECT_TRUE(detail::parse_accept_header("*", result));
  613. EXPECT_EQ(result.size(), 1U);
  614. EXPECT_EQ(result[0], "*");
  615. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  616. EXPECT_EQ(result.size(), 1U);
  617. EXPECT_EQ(result[0], "text/*");
  618. }
  619. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  620. Server svr;
  621. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  622. EXPECT_EQ(req.accept_content_types.size(), 3U);
  623. EXPECT_EQ(req.accept_content_types[0], "application/json");
  624. EXPECT_EQ(req.accept_content_types[1], "text/html");
  625. EXPECT_EQ(req.accept_content_types[2], "*/*");
  626. res.set_content("ok", "text/plain");
  627. });
  628. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  629. EXPECT_TRUE(false);
  630. res.set_content("bad request", "text/plain");
  631. });
  632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. listen_thread.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli("localhost", PORT);
  640. {
  641. auto res =
  642. cli.Get("/accept_ok",
  643. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  644. ASSERT_TRUE(res);
  645. EXPECT_EQ(StatusCode::OK_200, res->status);
  646. }
  647. {
  648. auto res = cli.Get("/accept_bad_request",
  649. {{"Accept", "text/html;q=abc,application/json"}});
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  652. }
  653. }
  654. TEST(DivideTest, DivideStringTests) {
  655. auto divide = [](const std::string &str, char d) {
  656. std::string lhs;
  657. std::string rhs;
  658. detail::divide(str, d,
  659. [&](const char *lhs_data, std::size_t lhs_size,
  660. const char *rhs_data, std::size_t rhs_size) {
  661. lhs.assign(lhs_data, lhs_size);
  662. rhs.assign(rhs_data, rhs_size);
  663. });
  664. return std::make_pair(std::move(lhs), std::move(rhs));
  665. };
  666. {
  667. const auto res = divide("", '=');
  668. EXPECT_EQ(res.first, "");
  669. EXPECT_EQ(res.second, "");
  670. }
  671. {
  672. const auto res = divide("=", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide(" ", '=');
  678. EXPECT_EQ(res.first, " ");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide("a", '=');
  683. EXPECT_EQ(res.first, "a");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a=", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("=b", '=');
  693. EXPECT_EQ(res.first, "");
  694. EXPECT_EQ(res.second, "b");
  695. }
  696. {
  697. const auto res = divide("a=b", '=');
  698. EXPECT_EQ(res.first, "a");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b=", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b=");
  705. }
  706. {
  707. const auto res = divide("a=b=c", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=c");
  710. }
  711. }
  712. TEST(SplitTest, ParseQueryString) {
  713. string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  716. [&](const char *b, const char *e) {
  717. string key, val;
  718. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  719. if (key.empty()) {
  720. key.assign(b2, e2);
  721. } else {
  722. val.assign(b2, e2);
  723. }
  724. });
  725. dic.emplace(key, val);
  726. });
  727. EXPECT_EQ("val1", dic.find("key1")->second);
  728. EXPECT_EQ("val2", dic.find("key2")->second);
  729. EXPECT_EQ("val3", dic.find("key3")->second);
  730. }
  731. TEST(SplitTest, ParseInvalidQueryTests) {
  732. {
  733. string s = " ";
  734. Params dict;
  735. detail::parse_query_text(s, dict);
  736. EXPECT_TRUE(dict.empty());
  737. }
  738. {
  739. string s = " = =";
  740. Params dict;
  741. detail::parse_query_text(s, dict);
  742. EXPECT_TRUE(dict.empty());
  743. }
  744. }
  745. TEST(ParseQueryTest, ParseQueryString) {
  746. {
  747. std::string s = "key1=val1&key2=val2&key3=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("val1", dic.find("key1")->second);
  751. EXPECT_EQ("val2", dic.find("key2")->second);
  752. EXPECT_EQ("val3", dic.find("key3")->second);
  753. }
  754. {
  755. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  756. Params dic;
  757. detail::parse_query_text(s, dic);
  758. EXPECT_EQ("", dic.find("key1")->second);
  759. EXPECT_EQ("val1", dic.find("key2")->second);
  760. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  761. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  762. }
  763. }
  764. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  765. Params dic;
  766. EXPECT_EQ(detail::params_to_query_str(dic), "");
  767. dic.emplace("key1", "val1");
  768. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  769. dic.emplace("key2", "val2");
  770. dic.emplace("key3", "val3");
  771. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  772. }
  773. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  774. string content_type = "multipart/form-data; boundary=something";
  775. string boundary;
  776. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  777. EXPECT_TRUE(ret);
  778. EXPECT_EQ(boundary, "something");
  779. }
  780. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  781. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  794. }
  795. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  796. string content_type =
  797. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  798. string boundary;
  799. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  802. }
  803. TEST(GetHeaderValueTest, DefaultValue) {
  804. Headers headers = {{"Dummy", "Dummy"}};
  805. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  806. EXPECT_STREQ("text/plain", val);
  807. }
  808. TEST(GetHeaderValueTest, DefaultValueInt) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  811. EXPECT_EQ(100ull, val);
  812. }
  813. TEST(GetHeaderValueTest, RegularValue) {
  814. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  816. EXPECT_STREQ("text/html", val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, SetContent) {
  824. Response res;
  825. res.set_content("html", "text/html");
  826. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  827. res.set_content("text", "text/plain");
  828. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  829. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  830. }
  831. TEST(GetHeaderValueTest, RegularValueInt) {
  832. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  833. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  834. EXPECT_EQ(100ull, val);
  835. }
  836. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  837. Headers headers = {{"Content-Length", "x"}};
  838. auto is_invalid_value = false;
  839. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  840. is_invalid_value);
  841. EXPECT_EQ(0ull, val);
  842. EXPECT_TRUE(is_invalid_value);
  843. }
  844. TEST(GetHeaderValueTest, Range) {
  845. {
  846. Headers headers = {make_range_header({{1, -1}})};
  847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  848. EXPECT_STREQ("bytes=1-", val);
  849. }
  850. {
  851. Headers headers = {make_range_header({{-1, 1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=-1", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{1, 10}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=1-10", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10, 100-", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-200", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=0-0, -1", val);
  874. }
  875. }
  876. TEST(ParseHeaderValueTest, Range) {
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=1-", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(1u, ranges[0].first);
  883. EXPECT_EQ(-1, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=-1", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(-1, ranges[0].first);
  891. EXPECT_EQ(1u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  896. EXPECT_TRUE(ret);
  897. EXPECT_EQ(1u, ranges.size());
  898. EXPECT_EQ(1u, ranges[0].first);
  899. EXPECT_EQ(10u, ranges[0].second);
  900. }
  901. {
  902. Ranges ranges;
  903. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  904. EXPECT_FALSE(ret);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  909. EXPECT_TRUE(ret);
  910. EXPECT_EQ(2u, ranges.size());
  911. EXPECT_EQ(1u, ranges[0].first);
  912. EXPECT_EQ(10u, ranges[0].second);
  913. EXPECT_EQ(100u, ranges[1].first);
  914. EXPECT_EQ(-1, ranges[1].second);
  915. }
  916. {
  917. Ranges ranges;
  918. auto ret =
  919. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(3u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(200u, ranges[1].second);
  926. EXPECT_EQ(300u, ranges[2].first);
  927. EXPECT_EQ(400u, ranges[2].second);
  928. }
  929. {
  930. Ranges ranges;
  931. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  944. EXPECT_TRUE(ranges.empty());
  945. }
  946. }
  947. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  948. Request req;
  949. req.set_header("Accept-Encoding", "gzip");
  950. Response res;
  951. res.set_header("Content-Type", "text/plain");
  952. auto ret = detail::encoding_type(req, res);
  953. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  954. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  955. #else
  956. EXPECT_TRUE(ret == detail::EncodingType::None);
  957. #endif
  958. }
  959. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  960. Request req;
  961. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  962. Response res;
  963. res.set_header("Content-Type", "text/plain");
  964. auto ret = detail::encoding_type(req, res);
  965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  967. #elif CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #elif CPPHTTPLIB_ZSTD_SUPPORT
  970. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  971. #else
  972. EXPECT_TRUE(ret == detail::EncodingType::None);
  973. #endif
  974. }
  975. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  976. Request req;
  977. req.set_header("Accept-Encoding",
  978. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  993. // All supported encodings rejected with q=0 should return None
  994. Request req;
  995. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. EXPECT_TRUE(ret == detail::EncodingType::None);
  1000. }
  1001. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1002. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1003. Request req;
  1004. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1005. Response res;
  1006. res.set_header("Content-Type", "text/plain");
  1007. auto ret = detail::encoding_type(req, res);
  1008. EXPECT_TRUE(ret == detail::EncodingType::None);
  1009. }
  1010. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1011. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1012. Request req;
  1013. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. }
  1019. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1020. // RFC 7231: Accept-Encoding values are case-insensitive
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1037. // q value should determine priority, not hardcoded order
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. // gzip has highest q=1.0, so it should be selected even though
  1044. // br and zstd are also supported
  1045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1050. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1051. #else
  1052. EXPECT_TRUE(ret == detail::EncodingType::None);
  1053. #endif
  1054. }
  1055. TEST(BufferStreamTest, read) {
  1056. detail::BufferStream strm1;
  1057. Stream &strm = strm1;
  1058. EXPECT_EQ(5, strm.write("hello"));
  1059. char buf[512];
  1060. EXPECT_EQ(2, strm.read(buf, 2));
  1061. EXPECT_EQ('h', buf[0]);
  1062. EXPECT_EQ('e', buf[1]);
  1063. EXPECT_EQ(2, strm.read(buf, 2));
  1064. EXPECT_EQ('l', buf[0]);
  1065. EXPECT_EQ('l', buf[1]);
  1066. EXPECT_EQ(1, strm.read(buf, 1));
  1067. EXPECT_EQ('o', buf[0]);
  1068. EXPECT_EQ(0, strm.read(buf, 1));
  1069. }
  1070. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1071. auto host = "www.httpwatch.com";
  1072. auto ip = hosted_at(host);
  1073. EXPECT_EQ("23.96.13.243", ip);
  1074. std::vector<std::string> addrs;
  1075. hosted_at(host, addrs);
  1076. EXPECT_EQ(1u, addrs.size());
  1077. }
  1078. #if 0 // It depends on each test environment...
  1079. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1080. auto host = "www.youtube.com";
  1081. std::vector<std::string> addrs;
  1082. hosted_at(host, addrs);
  1083. EXPECT_EQ(20u, addrs.size());
  1084. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1085. EXPECT_TRUE(it != addrs.end());
  1086. }
  1087. #endif
  1088. class ChunkedEncodingTest : public ::testing::Test {
  1089. protected:
  1090. ChunkedEncodingTest()
  1091. : cli_(HOST, PORT)
  1092. #ifdef CPPHTTPLIB_SSL_ENABLED
  1093. ,
  1094. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1095. #endif
  1096. {
  1097. cli_.set_connection_timeout(2);
  1098. #ifdef CPPHTTPLIB_SSL_ENABLED
  1099. cli_.enable_server_certificate_verification(false);
  1100. #endif
  1101. }
  1102. virtual void SetUp() {
  1103. read_file("./image.jpg", image_data_);
  1104. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. svr_.Get(
  1108. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1109. res.set_chunked_content_provider(
  1110. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1111. size_t remaining = image_data_.size() - offset;
  1112. if (remaining == 0) {
  1113. sink.done();
  1114. } else {
  1115. constexpr size_t CHUNK_SIZE = 1024;
  1116. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1117. sink.write(&image_data_[offset], send_size);
  1118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1119. }
  1120. return true;
  1121. });
  1122. });
  1123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1124. svr_.wait_until_ready();
  1125. }
  1126. virtual void TearDown() {
  1127. svr_.stop();
  1128. if (!request_threads_.empty()) {
  1129. std::this_thread::sleep_for(std::chrono::seconds(1));
  1130. for (auto &t : request_threads_) {
  1131. t.join();
  1132. }
  1133. }
  1134. t_.join();
  1135. }
  1136. #ifdef CPPHTTPLIB_SSL_ENABLED
  1137. SSLClient cli_;
  1138. SSLServer svr_;
  1139. #else
  1140. Client cli_;
  1141. Server svr_;
  1142. #endif
  1143. thread t_;
  1144. std::vector<thread> request_threads_;
  1145. std::string image_data_;
  1146. };
  1147. TEST_F(ChunkedEncodingTest, NormalGet) {
  1148. auto res = cli_.Get("/chunked");
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, res->body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1158. body.append(data, data_length);
  1159. return true;
  1160. });
  1161. ASSERT_TRUE(res);
  1162. std::string out;
  1163. read_file("./image.jpg", out);
  1164. EXPECT_EQ(StatusCode::OK_200, res->status);
  1165. EXPECT_EQ(out, body);
  1166. }
  1167. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1168. std::string body;
  1169. auto res = cli_.Get(
  1170. "/chunked",
  1171. [&](const Response &response) {
  1172. EXPECT_EQ(StatusCode::OK_200, response.status);
  1173. return true;
  1174. },
  1175. [&](const char *data, size_t data_length) {
  1176. body.append(data, data_length);
  1177. return true;
  1178. });
  1179. ASSERT_TRUE(res);
  1180. std::string out;
  1181. read_file("./image.jpg", out);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. EXPECT_EQ(out, body);
  1184. }
  1185. TEST(RangeTest, FromHTTPBin_Online) {
  1186. auto host = "httpbingo.org";
  1187. auto path = std::string{"/range/32"};
  1188. #ifdef CPPHTTPLIB_SSL_ENABLED
  1189. auto port = 443;
  1190. SSLClient cli(host, port);
  1191. #else
  1192. auto port = 80;
  1193. Client cli(host, port);
  1194. #endif
  1195. cli.set_connection_timeout(5);
  1196. {
  1197. auto res = cli.Get(path);
  1198. ASSERT_TRUE(res);
  1199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1200. EXPECT_EQ(StatusCode::OK_200, res->status);
  1201. }
  1202. {
  1203. Headers headers = {make_range_header({{1, -1}})};
  1204. auto res = cli.Get(path, headers);
  1205. ASSERT_TRUE(res);
  1206. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1208. }
  1209. {
  1210. Headers headers = {make_range_header({{1, 10}})};
  1211. auto res = cli.Get(path, headers);
  1212. ASSERT_TRUE(res);
  1213. EXPECT_EQ("bcdefghijk", res->body);
  1214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1215. }
  1216. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1217. // entire resource, while the original httpbin returned 200. Both are
  1218. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1219. {
  1220. Headers headers = {make_range_header({{0, 31}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1224. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1225. res->status == StatusCode::PartialContent_206);
  1226. }
  1227. {
  1228. Headers headers = {make_range_header({{0, -1}})};
  1229. auto res = cli.Get(path, headers);
  1230. ASSERT_TRUE(res);
  1231. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1232. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1233. res->status == StatusCode::PartialContent_206);
  1234. }
  1235. // go-httpbin returns 206 with clamped range for over-range requests,
  1236. // while the original httpbin returned 416. Both behaviors are observed
  1237. // in real servers, so we only verify the request succeeds.
  1238. {
  1239. Headers headers = {make_range_header({{0, 32}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. }
  1243. }
  1244. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1245. auto host = "unresolvableaddress.local";
  1246. auto path = std::string{"/"};
  1247. #ifdef CPPHTTPLIB_SSL_ENABLED
  1248. auto port = 443;
  1249. SSLClient cli(host, port);
  1250. #else
  1251. auto port = 80;
  1252. Client cli(host, port);
  1253. #endif
  1254. cli.set_connection_timeout(1);
  1255. {
  1256. auto res = cli.Get(path);
  1257. ASSERT_FALSE(res);
  1258. }
  1259. std::this_thread::sleep_for(std::chrono::seconds(8));
  1260. }
  1261. TEST(ConnectionErrorTest, InvalidHost) {
  1262. auto host = "-abcde.com";
  1263. #ifdef CPPHTTPLIB_SSL_ENABLED
  1264. auto port = 443;
  1265. SSLClient cli(host, port);
  1266. #else
  1267. auto port = 80;
  1268. Client cli(host, port);
  1269. #endif
  1270. cli.set_connection_timeout(std::chrono::seconds(2));
  1271. auto res = cli.Get("/");
  1272. ASSERT_TRUE(!res);
  1273. EXPECT_EQ(Error::Connection, res.error());
  1274. }
  1275. TEST(ConnectionErrorTest, InvalidHost2) {
  1276. auto host = "httpcan.org/";
  1277. #ifdef CPPHTTPLIB_SSL_ENABLED
  1278. SSLClient cli(host);
  1279. #else
  1280. Client cli(host);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(2));
  1283. auto res = cli.Get("/");
  1284. ASSERT_TRUE(!res);
  1285. EXPECT_EQ(Error::Connection, res.error());
  1286. }
  1287. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1288. auto host = "httpcan.org/";
  1289. #ifdef CPPHTTPLIB_SSL_ENABLED
  1290. SSLClient cli(host);
  1291. #else
  1292. Client cli(host);
  1293. #endif
  1294. cli.set_connection_timeout(std::chrono::seconds(2));
  1295. auto res = cli.Get("/");
  1296. ASSERT_TRUE(!res);
  1297. stringstream s;
  1298. s << "error code: " << res.error();
  1299. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1300. }
  1301. TEST(ConnectionErrorTest, InvalidPort) {
  1302. auto host = "localhost";
  1303. auto port = 44380;
  1304. #ifdef CPPHTTPLIB_SSL_ENABLED
  1305. SSLClient cli(host, port);
  1306. #else
  1307. Client cli(host, port);
  1308. #endif
  1309. cli.set_connection_timeout(std::chrono::seconds(2));
  1310. auto res = cli.Get("/");
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_TRUE(Error::Connection == res.error() ||
  1313. Error::ConnectionTimeout == res.error());
  1314. }
  1315. TEST(ConnectionErrorTest, Timeout_Online) {
  1316. auto host = "google.com";
  1317. #ifdef CPPHTTPLIB_SSL_ENABLED
  1318. auto port = 44380;
  1319. SSLClient cli(host, port);
  1320. #else
  1321. auto port = 8080;
  1322. Client cli(host, port);
  1323. #endif
  1324. cli.set_connection_timeout(std::chrono::seconds(2));
  1325. // only probe one address type so that the error reason
  1326. // correlates to the timed-out IPv4, not the unsupported
  1327. // IPv6 connection attempt
  1328. cli.set_address_family(AF_INET);
  1329. auto res = cli.Get("/");
  1330. ASSERT_TRUE(!res);
  1331. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1332. }
  1333. TEST(CancelTest, NoCancel_Online) {
  1334. auto host = "httpbingo.org";
  1335. auto path = std::string{"/range/32"};
  1336. #ifdef CPPHTTPLIB_SSL_ENABLED
  1337. auto port = 443;
  1338. SSLClient cli(host, port);
  1339. #else
  1340. auto port = 80;
  1341. Client cli(host, port);
  1342. #endif
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1345. ASSERT_TRUE(res);
  1346. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1347. EXPECT_EQ(StatusCode::OK_200, res->status);
  1348. }
  1349. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1350. // Use /bytes with a large payload so that the DownloadProgress callback
  1351. // (which only fires for Content-Length responses) is invoked before the
  1352. // entire body is received, giving cancellation a chance to fire.
  1353. auto host = "httpbingo.org";
  1354. auto path = std::string{"/bytes/524288"};
  1355. #ifdef CPPHTTPLIB_SSL_ENABLED
  1356. auto port = 443;
  1357. SSLClient cli(host, port);
  1358. #else
  1359. auto port = 80;
  1360. Client cli(host, port);
  1361. #endif
  1362. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1363. cli.set_connection_timeout(std::chrono::seconds(5));
  1364. ASSERT_TRUE(!res);
  1365. EXPECT_EQ(Error::Canceled, res.error());
  1366. }
  1367. TEST(CancelTest, WithCancelLargePayload_Online) {
  1368. auto host = "httpbingo.org";
  1369. auto path = std::string{"/bytes/524288"};
  1370. #ifdef CPPHTTPLIB_SSL_ENABLED
  1371. auto port = 443;
  1372. SSLClient cli(host, port);
  1373. #else
  1374. auto port = 80;
  1375. Client cli(host, port);
  1376. #endif
  1377. cli.set_connection_timeout(std::chrono::seconds(5));
  1378. uint32_t count = 0;
  1379. auto res =
  1380. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1381. ASSERT_TRUE(!res);
  1382. EXPECT_EQ(Error::Canceled, res.error());
  1383. }
  1384. TEST(CancelTest, NoCancelPost) {
  1385. Server svr;
  1386. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1387. res.set_content("Hello World!", "text/plain");
  1388. });
  1389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. thread.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, PORT);
  1397. cli.set_connection_timeout(std::chrono::seconds(5));
  1398. auto res =
  1399. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1400. "application/json", [](uint64_t, uint64_t) { return true; });
  1401. ASSERT_TRUE(res);
  1402. EXPECT_EQ("Hello World!", res->body);
  1403. EXPECT_EQ(StatusCode::OK_200, res->status);
  1404. }
  1405. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1406. Server svr;
  1407. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1408. res.set_content("Hello World!", "text/plain");
  1409. });
  1410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1411. auto se = detail::scope_exit([&] {
  1412. svr.stop();
  1413. thread.join();
  1414. ASSERT_FALSE(svr.is_running());
  1415. });
  1416. svr.wait_until_ready();
  1417. Client cli(HOST, PORT);
  1418. cli.set_connection_timeout(std::chrono::seconds(5));
  1419. auto res =
  1420. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1421. "application/json", [](uint64_t, uint64_t) { return false; });
  1422. ASSERT_TRUE(!res);
  1423. EXPECT_EQ(Error::Canceled, res.error());
  1424. }
  1425. TEST(CancelTest, WithCancelLargePayloadPost) {
  1426. Server svr;
  1427. svr.set_payload_max_length(200 * 1024 * 1024);
  1428. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1429. res.set_content(LARGE_DATA, "text/plain");
  1430. });
  1431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. thread.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. Client cli(HOST, PORT);
  1439. cli.set_payload_max_length(200 * 1024 * 1024);
  1440. cli.set_connection_timeout(std::chrono::seconds(5));
  1441. auto res =
  1442. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1443. "application/json", [](uint64_t, uint64_t) { return false; });
  1444. ASSERT_TRUE(!res);
  1445. EXPECT_EQ(Error::Canceled, res.error());
  1446. }
  1447. TEST(CancelTest, NoCancelPut) {
  1448. Server svr;
  1449. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("Hello World!", "text/plain");
  1451. });
  1452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1453. auto se = detail::scope_exit([&] {
  1454. svr.stop();
  1455. thread.join();
  1456. ASSERT_FALSE(svr.is_running());
  1457. });
  1458. svr.wait_until_ready();
  1459. Client cli(HOST, PORT);
  1460. cli.set_connection_timeout(std::chrono::seconds(5));
  1461. auto res =
  1462. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1463. "application/json", [](uint64_t, uint64_t) { return true; });
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ("Hello World!", res->body);
  1466. EXPECT_EQ(StatusCode::OK_200, res->status);
  1467. }
  1468. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1469. Server svr;
  1470. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1471. res.set_content("Hello World!", "text/plain");
  1472. });
  1473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1474. auto se = detail::scope_exit([&] {
  1475. svr.stop();
  1476. thread.join();
  1477. ASSERT_FALSE(svr.is_running());
  1478. });
  1479. svr.wait_until_ready();
  1480. Client cli(HOST, PORT);
  1481. cli.set_connection_timeout(std::chrono::seconds(5));
  1482. auto res =
  1483. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1484. "application/json", [](uint64_t, uint64_t) { return false; });
  1485. ASSERT_TRUE(!res);
  1486. EXPECT_EQ(Error::Canceled, res.error());
  1487. }
  1488. TEST(CancelTest, WithCancelLargePayloadPut) {
  1489. Server svr;
  1490. svr.set_payload_max_length(200 * 1024 * 1024);
  1491. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1492. res.set_content(LARGE_DATA, "text/plain");
  1493. });
  1494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1495. auto se = detail::scope_exit([&] {
  1496. svr.stop();
  1497. thread.join();
  1498. ASSERT_FALSE(svr.is_running());
  1499. });
  1500. svr.wait_until_ready();
  1501. Client cli(HOST, PORT);
  1502. cli.set_payload_max_length(200 * 1024 * 1024);
  1503. cli.set_connection_timeout(std::chrono::seconds(5));
  1504. auto res =
  1505. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1506. "application/json", [](uint64_t, uint64_t) { return false; });
  1507. ASSERT_TRUE(!res);
  1508. EXPECT_EQ(Error::Canceled, res.error());
  1509. }
  1510. TEST(CancelTest, NoCancelPatch) {
  1511. Server svr;
  1512. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1513. res.set_content("Hello World!", "text/plain");
  1514. });
  1515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1516. auto se = detail::scope_exit([&] {
  1517. svr.stop();
  1518. thread.join();
  1519. ASSERT_FALSE(svr.is_running());
  1520. });
  1521. svr.wait_until_ready();
  1522. Client cli(HOST, PORT);
  1523. cli.set_connection_timeout(std::chrono::seconds(5));
  1524. auto res =
  1525. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1526. "application/json", [](uint64_t, uint64_t) { return true; });
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ("Hello World!", res->body);
  1529. EXPECT_EQ(StatusCode::OK_200, res->status);
  1530. }
  1531. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1532. Server svr;
  1533. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1534. res.set_content("Hello World!", "text/plain");
  1535. });
  1536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1537. auto se = detail::scope_exit([&] {
  1538. svr.stop();
  1539. thread.join();
  1540. ASSERT_FALSE(svr.is_running());
  1541. });
  1542. svr.wait_until_ready();
  1543. Client cli(HOST, PORT);
  1544. cli.set_connection_timeout(std::chrono::seconds(5));
  1545. auto res =
  1546. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1547. "application/json", [](uint64_t, uint64_t) { return false; });
  1548. ASSERT_TRUE(!res);
  1549. EXPECT_EQ(Error::Canceled, res.error());
  1550. }
  1551. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1552. Server svr;
  1553. svr.set_payload_max_length(200 * 1024 * 1024);
  1554. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1555. res.set_content(LARGE_DATA, "text/plain");
  1556. });
  1557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1558. auto se = detail::scope_exit([&] {
  1559. svr.stop();
  1560. thread.join();
  1561. ASSERT_FALSE(svr.is_running());
  1562. });
  1563. svr.wait_until_ready();
  1564. Client cli(HOST, PORT);
  1565. cli.set_payload_max_length(200 * 1024 * 1024);
  1566. cli.set_connection_timeout(std::chrono::seconds(5));
  1567. auto res =
  1568. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1569. "application/json", [](uint64_t, uint64_t) { return false; });
  1570. ASSERT_TRUE(!res);
  1571. EXPECT_EQ(Error::Canceled, res.error());
  1572. }
  1573. TEST(CancelTest, NoCancelDelete) {
  1574. Server svr;
  1575. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1576. res.set_content("Hello World!", "text/plain");
  1577. });
  1578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1579. auto se = detail::scope_exit([&] {
  1580. svr.stop();
  1581. thread.join();
  1582. ASSERT_FALSE(svr.is_running());
  1583. });
  1584. svr.wait_until_ready();
  1585. Client cli(HOST, PORT);
  1586. cli.set_connection_timeout(std::chrono::seconds(5));
  1587. auto res =
  1588. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1589. "application/json", [](uint64_t, uint64_t) { return true; });
  1590. ASSERT_TRUE(res);
  1591. EXPECT_EQ("Hello World!", res->body);
  1592. EXPECT_EQ(StatusCode::OK_200, res->status);
  1593. }
  1594. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1595. Server svr;
  1596. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1597. res.set_content("Hello World!", "text/plain");
  1598. });
  1599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1600. auto se = detail::scope_exit([&] {
  1601. svr.stop();
  1602. thread.join();
  1603. ASSERT_FALSE(svr.is_running());
  1604. });
  1605. svr.wait_until_ready();
  1606. Client cli(HOST, PORT);
  1607. cli.set_connection_timeout(std::chrono::seconds(5));
  1608. auto res =
  1609. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1610. "application/json", [](uint64_t, uint64_t) { return false; });
  1611. ASSERT_TRUE(!res);
  1612. EXPECT_EQ(Error::Canceled, res.error());
  1613. }
  1614. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1615. Server svr;
  1616. svr.set_payload_max_length(200 * 1024 * 1024);
  1617. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1618. res.set_content(LARGE_DATA, "text/plain");
  1619. });
  1620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1621. auto se = detail::scope_exit([&] {
  1622. svr.stop();
  1623. thread.join();
  1624. ASSERT_FALSE(svr.is_running());
  1625. });
  1626. svr.wait_until_ready();
  1627. Client cli(HOST, PORT);
  1628. cli.set_payload_max_length(200 * 1024 * 1024);
  1629. cli.set_connection_timeout(std::chrono::seconds(5));
  1630. auto res =
  1631. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1632. "application/json", [](uint64_t, uint64_t) { return false; });
  1633. ASSERT_TRUE(!res);
  1634. EXPECT_EQ(Error::Canceled, res.error());
  1635. }
  1636. static std::string remove_whitespace(const std::string &input) {
  1637. std::string output;
  1638. output.reserve(input.size());
  1639. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1640. [](unsigned char c) { return !std::isspace(c); });
  1641. return output;
  1642. }
  1643. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1644. auto host = "httpbingo.org";
  1645. auto path = std::string{"/basic-auth/hello/world"};
  1646. #ifdef CPPHTTPLIB_SSL_ENABLED
  1647. auto port = 443;
  1648. SSLClient cli(host, port);
  1649. #else
  1650. auto port = 80;
  1651. Client cli(host, port);
  1652. #endif
  1653. {
  1654. auto res = cli.Get(path);
  1655. ASSERT_TRUE(res);
  1656. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1657. }
  1658. {
  1659. auto res =
  1660. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1661. ASSERT_TRUE(res);
  1662. auto body = remove_whitespace(res->body);
  1663. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1664. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1665. EXPECT_EQ(StatusCode::OK_200, res->status);
  1666. }
  1667. {
  1668. cli.set_basic_auth("hello", "world");
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. auto body = remove_whitespace(res->body);
  1672. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1673. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1674. EXPECT_EQ(StatusCode::OK_200, res->status);
  1675. }
  1676. {
  1677. cli.set_basic_auth("hello", "bad");
  1678. auto res = cli.Get(path);
  1679. ASSERT_TRUE(res);
  1680. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1681. }
  1682. {
  1683. cli.set_basic_auth("bad", "world");
  1684. auto res = cli.Get(path);
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1687. }
  1688. }
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1691. auto host = "httpbingo.org";
  1692. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1693. auto paths = std::vector<std::string>{
  1694. "/digest-auth/auth/hello/world/MD5",
  1695. "/digest-auth/auth/hello/world/SHA-256",
  1696. };
  1697. auto port = 443;
  1698. SSLClient cli(host, port);
  1699. {
  1700. auto res = cli.Get(unauth_path);
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. {
  1705. cli.set_digest_auth("hello", "world");
  1706. for (const auto &path : paths) {
  1707. auto res = cli.Get(path.c_str());
  1708. ASSERT_TRUE(res);
  1709. auto body = remove_whitespace(res->body);
  1710. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1711. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. cli.set_digest_auth("hello", "bad");
  1715. for (const auto &path : paths) {
  1716. auto res = cli.Get(path.c_str());
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1719. }
  1720. }
  1721. }
  1722. #endif
  1723. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1724. auto host = "google.com";
  1725. auto another_host = "example.com";
  1726. auto wrong_ip = "0.0.0.0";
  1727. #ifdef CPPHTTPLIB_SSL_ENABLED
  1728. SSLClient cli(host);
  1729. #else
  1730. Client cli(host);
  1731. #endif
  1732. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1733. auto res = cli.Get("/");
  1734. ASSERT_TRUE(res);
  1735. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1736. }
  1737. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1738. auto host = "google.com";
  1739. auto wrong_ip = "0.0.0.0";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_hostname_addr_map({{host, wrong_ip}});
  1746. auto res = cli.Get("/");
  1747. ASSERT_TRUE(!res);
  1748. EXPECT_EQ(Error::Connection, res.error());
  1749. }
  1750. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1751. auto host = "httpbingo.org";
  1752. auto path = std::string{"/absolute-redirect/3"};
  1753. #ifdef CPPHTTPLIB_SSL_ENABLED
  1754. SSLClient cli(host);
  1755. #else
  1756. Client cli(host);
  1757. #endif
  1758. cli.set_follow_location(true);
  1759. auto res = cli.Get(path);
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. TEST(RedirectTest, Redirect_Online) {
  1764. auto host = "httpbingo.org";
  1765. auto path = std::string{"/redirect/3"};
  1766. #ifdef CPPHTTPLIB_SSL_ENABLED
  1767. SSLClient cli(host);
  1768. #else
  1769. Client cli(host);
  1770. #endif
  1771. cli.set_follow_location(true);
  1772. auto res = cli.Get(path);
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::OK_200, res->status);
  1775. }
  1776. TEST(RelativeRedirectTest, Redirect_Online) {
  1777. auto host = "httpbingo.org";
  1778. auto path = std::string{"/relative-redirect/3"};
  1779. #ifdef CPPHTTPLIB_SSL_ENABLED
  1780. SSLClient cli(host);
  1781. #else
  1782. Client cli(host);
  1783. #endif
  1784. cli.set_follow_location(true);
  1785. auto res = cli.Get(path);
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(StatusCode::OK_200, res->status);
  1788. }
  1789. TEST(TooManyRedirectTest, Redirect_Online) {
  1790. auto host = "httpbingo.org";
  1791. auto path = std::string{"/redirect/21"};
  1792. #ifdef CPPHTTPLIB_SSL_ENABLED
  1793. SSLClient cli(host);
  1794. #else
  1795. Client cli(host);
  1796. #endif
  1797. cli.set_follow_location(true);
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(!res);
  1800. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1801. }
  1802. #ifdef CPPHTTPLIB_SSL_ENABLED
  1803. TEST(YahooRedirectTest, Redirect_Online) {
  1804. Client cli("yahoo.com");
  1805. auto res = cli.Get("/");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1808. cli.set_follow_location(true);
  1809. res = cli.Get("/");
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::OK_200, res->status);
  1812. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1813. }
  1814. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1815. #define REDIR_HOST "httpbingo.org"
  1816. #define REDIR_PATH "/redirect-to"
  1817. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1818. SSLClient cli(REDIR_HOST);
  1819. cli.set_follow_location(true);
  1820. auto res =
  1821. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1826. SSLClient cli(REDIR_HOST);
  1827. cli.set_follow_location(true);
  1828. Params params;
  1829. params.emplace("url", "http://example.com");
  1830. params.emplace("status_code", "302");
  1831. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. }
  1835. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1836. SSLClient cli(REDIR_HOST);
  1837. cli.set_follow_location(true);
  1838. Params params;
  1839. params.emplace("url", "http://example.com");
  1840. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1841. ASSERT_TRUE(res);
  1842. EXPECT_EQ(StatusCode::OK_200, res->status);
  1843. }
  1844. TEST(UrlWithSpace, Redirect_Online) {
  1845. SSLClient cli("edge.forgecdn.net");
  1846. cli.set_follow_location(true);
  1847. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1848. ASSERT_TRUE(res);
  1849. EXPECT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1851. }
  1852. #endif
  1853. #if !defined(_WIN32) && !defined(_WIN64)
  1854. TEST(ReceiveSignals, Signal) {
  1855. auto setupSignalHandlers = []() {
  1856. struct sigaction act;
  1857. sigemptyset(&act.sa_mask);
  1858. act.sa_flags = SA_SIGINFO;
  1859. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1860. switch (sig) {
  1861. case SIGINT:
  1862. default: break;
  1863. }
  1864. };
  1865. ::sigaction(SIGINT, &act, nullptr);
  1866. };
  1867. Server svr;
  1868. int port = 0;
  1869. auto thread = std::thread([&]() {
  1870. setupSignalHandlers();
  1871. port = svr.bind_to_any_port(HOST);
  1872. svr.listen_after_bind();
  1873. });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. ASSERT_TRUE(svr.is_running());
  1881. pthread_kill(thread.native_handle(), SIGINT);
  1882. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1883. ASSERT_TRUE(svr.is_running());
  1884. }
  1885. #endif
  1886. TEST(RedirectToDifferentPort, Redirect) {
  1887. Server svr1;
  1888. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. int svr1_port = 0;
  1892. auto thread1 = std::thread([&]() {
  1893. svr1_port = svr1.bind_to_any_port(HOST);
  1894. svr1.listen_after_bind();
  1895. });
  1896. Server svr2;
  1897. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1898. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1899. });
  1900. int svr2_port = 0;
  1901. auto thread2 = std::thread([&]() {
  1902. svr2_port = svr2.bind_to_any_port(HOST);
  1903. svr2.listen_after_bind();
  1904. });
  1905. auto se = detail::scope_exit([&] {
  1906. svr2.stop();
  1907. thread2.join();
  1908. svr1.stop();
  1909. thread1.join();
  1910. ASSERT_FALSE(svr2.is_running());
  1911. ASSERT_FALSE(svr1.is_running());
  1912. });
  1913. svr1.wait_until_ready();
  1914. svr2.wait_until_ready();
  1915. Client cli("localhost", svr2_port);
  1916. cli.set_follow_location(true);
  1917. auto res = cli.Get("/2");
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. EXPECT_EQ("Hello World!", res->body);
  1921. }
  1922. static void
  1923. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1924. Server svr1;
  1925. std::string captured_authorization;
  1926. svr1.Get("/target", [&](const Request &req, Response &res) {
  1927. captured_authorization = req.get_header_value("Authorization");
  1928. res.set_content("OK", "text/plain");
  1929. });
  1930. int svr1_port = 0;
  1931. auto thread1 = std::thread([&]() {
  1932. svr1_port = svr1.bind_to_any_port(HOST);
  1933. svr1.listen_after_bind();
  1934. });
  1935. Server svr2;
  1936. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1937. res.set_redirect(
  1938. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1939. });
  1940. int svr2_port = 0;
  1941. auto thread2 = std::thread([&]() {
  1942. svr2_port = svr2.bind_to_any_port(HOST);
  1943. svr2.listen_after_bind();
  1944. });
  1945. auto se = detail::scope_exit([&] {
  1946. svr2.stop();
  1947. thread2.join();
  1948. svr1.stop();
  1949. thread1.join();
  1950. ASSERT_FALSE(svr2.is_running());
  1951. ASSERT_FALSE(svr1.is_running());
  1952. });
  1953. svr1.wait_until_ready();
  1954. svr2.wait_until_ready();
  1955. Client cli("localhost", svr2_port);
  1956. cli.set_follow_location(true);
  1957. set_auth(cli);
  1958. auto res = cli.Get("/redir");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1962. EXPECT_TRUE(captured_authorization.empty());
  1963. }
  1964. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1965. TestDoNotForwardCredentialsOnRedirect(
  1966. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1967. }
  1968. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1969. TestDoNotForwardCredentialsOnRedirect(
  1970. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1971. }
  1972. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1973. Server svr;
  1974. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1975. // Port number that overflows int — should not crash
  1976. res.set_redirect("http://localhost:99999999999999999999/target");
  1977. });
  1978. auto port = svr.bind_to_any_port(HOST);
  1979. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1980. auto se = detail::scope_exit([&] {
  1981. svr.stop();
  1982. thread.join();
  1983. ASSERT_FALSE(svr.is_running());
  1984. });
  1985. svr.wait_until_ready();
  1986. Client cli(HOST, port);
  1987. cli.set_follow_location(true);
  1988. auto res = cli.Get("/redir");
  1989. // Should fail gracefully, not crash (no valid response due to bad port)
  1990. EXPECT_FALSE(res);
  1991. }
  1992. TEST(RedirectFromPageWithContent, Redirect) {
  1993. Server svr;
  1994. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1995. res.set_content("___", "text/plain");
  1996. res.set_redirect("/2");
  1997. });
  1998. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1999. res.set_content("Hello World!", "text/plain");
  2000. });
  2001. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2002. auto se = detail::scope_exit([&] {
  2003. svr.stop();
  2004. th.join();
  2005. ASSERT_FALSE(svr.is_running());
  2006. });
  2007. svr.wait_until_ready();
  2008. {
  2009. Client cli("localhost", PORT);
  2010. cli.set_follow_location(true);
  2011. std::string body;
  2012. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2013. body.append(data, data_length);
  2014. return true;
  2015. });
  2016. ASSERT_TRUE(res);
  2017. EXPECT_EQ(StatusCode::OK_200, res->status);
  2018. EXPECT_EQ("Hello World!", body);
  2019. }
  2020. {
  2021. Client cli("localhost", PORT);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::Found_302, res->status);
  2029. EXPECT_EQ("___", body);
  2030. }
  2031. }
  2032. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2033. Server svr;
  2034. auto port_str = std::to_string(PORT);
  2035. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2036. auto expected_host = "[::1]:" + port_str;
  2037. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2038. res.set_content("___", "text/plain");
  2039. // res.set_redirect("/2");
  2040. res.set_redirect(redirect_url);
  2041. });
  2042. svr.Get("/2", [&](const Request &req, Response &res) {
  2043. auto host_header = req.headers.find("Host");
  2044. ASSERT_TRUE(host_header != req.headers.end());
  2045. EXPECT_EQ(expected_host, host_header->second);
  2046. res.set_content("Hello World!", "text/plain");
  2047. });
  2048. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2049. auto se = detail::scope_exit([&] {
  2050. svr.stop();
  2051. th.join();
  2052. ASSERT_FALSE(svr.is_running());
  2053. });
  2054. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2055. // actually starts anything, so the condition !svr.is_running() will
  2056. // always remain true, and the loop never stops.
  2057. // This basically counts how many milliseconds have passed since the
  2058. // call to svr.listen(), and if after 5 seconds nothing started yet
  2059. // aborts the test.
  2060. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2061. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2062. ASSERT_LT(milliseconds, 5000U);
  2063. }
  2064. {
  2065. Client cli("::1", PORT);
  2066. cli.set_follow_location(true);
  2067. std::string body;
  2068. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2069. body.append(data, data_length);
  2070. return true;
  2071. });
  2072. ASSERT_TRUE(res);
  2073. EXPECT_EQ(StatusCode::OK_200, res->status);
  2074. EXPECT_EQ("Hello World!", body);
  2075. }
  2076. {
  2077. Client cli("::1", PORT);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::Found_302, res->status);
  2085. EXPECT_EQ("___", body);
  2086. }
  2087. }
  2088. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2089. Server svr;
  2090. svr.Get("/foo", [](const Request &req, Response &res) {
  2091. auto a = req.params.find("a");
  2092. if (a != req.params.end()) {
  2093. res.set_content((*a).second, "text/plain");
  2094. res.status = StatusCode::OK_200;
  2095. } else {
  2096. res.status = StatusCode::BadRequest_400;
  2097. }
  2098. });
  2099. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2100. auto se = detail::scope_exit([&] {
  2101. svr.stop();
  2102. thread.join();
  2103. ASSERT_FALSE(svr.is_running());
  2104. });
  2105. svr.wait_until_ready();
  2106. {
  2107. Client cli(HOST, PORT);
  2108. cli.set_path_encode(false);
  2109. auto res = cli.Get("/foo?a=explicitly+encoded");
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(StatusCode::OK_200, res->status);
  2112. // This expects it back with a space, as the `+` won't have been
  2113. // url-encoded, and server-side the params get decoded turning `+`
  2114. // into spaces.
  2115. EXPECT_EQ("explicitly encoded", res->body);
  2116. }
  2117. }
  2118. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2119. Server svr;
  2120. svr.Get("/", [](const Request &req, Response &) {
  2121. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2122. });
  2123. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2124. auto se = detail::scope_exit([&] {
  2125. svr.stop();
  2126. thread.join();
  2127. ASSERT_FALSE(svr.is_running());
  2128. });
  2129. svr.wait_until_ready();
  2130. {
  2131. Client cli(HOST, PORT);
  2132. cli.set_path_encode(false);
  2133. auto res = cli.Get("/?something=%0A");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. }
  2137. }
  2138. TEST(BindServerTest, BindDualStack) {
  2139. Server svr;
  2140. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2141. res.set_content("Hello World!", "text/plain");
  2142. });
  2143. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2144. auto se = detail::scope_exit([&] {
  2145. svr.stop();
  2146. thread.join();
  2147. ASSERT_FALSE(svr.is_running());
  2148. });
  2149. svr.wait_until_ready();
  2150. {
  2151. Client cli("127.0.0.1", PORT);
  2152. auto res = cli.Get("/1");
  2153. ASSERT_TRUE(res);
  2154. EXPECT_EQ(StatusCode::OK_200, res->status);
  2155. EXPECT_EQ("Hello World!", res->body);
  2156. }
  2157. {
  2158. Client cli("::1", PORT);
  2159. auto res = cli.Get("/1");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. EXPECT_EQ("Hello World!", res->body);
  2163. }
  2164. }
  2165. TEST(BindServerTest, BindAndListenSeparately) {
  2166. Server svr;
  2167. int port = svr.bind_to_any_port("0.0.0.0");
  2168. ASSERT_TRUE(svr.is_valid());
  2169. ASSERT_TRUE(port > 0);
  2170. svr.stop();
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2175. CLIENT_CA_CERT_DIR);
  2176. int port = svr.bind_to_any_port("0.0.0.0");
  2177. ASSERT_TRUE(svr.is_valid());
  2178. ASSERT_TRUE(port > 0);
  2179. svr.stop();
  2180. }
  2181. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2182. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2183. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2184. int port = svr.bind_to_any_port("0.0.0.0");
  2185. ASSERT_TRUE(svr.is_valid());
  2186. ASSERT_TRUE(port > 0);
  2187. svr.stop();
  2188. }
  2189. TEST(BindServerTest, UpdateCertsPem) {
  2190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2191. int port = svr.bind_to_any_port("0.0.0.0");
  2192. ASSERT_TRUE(svr.is_valid());
  2193. ASSERT_TRUE(port > 0);
  2194. // Read PEM files
  2195. std::string cert_pem, key_pem, ca_pem;
  2196. read_file(SERVER_CERT_FILE, cert_pem);
  2197. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2198. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2199. // Update server certificates using PEM API
  2200. ASSERT_TRUE(
  2201. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2202. ASSERT_TRUE(svr.is_valid());
  2203. svr.stop();
  2204. }
  2205. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2206. // Start server with client CA (enables client auth)
  2207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2208. ASSERT_TRUE(svr.is_valid());
  2209. bool handler_called = false;
  2210. svr.Get("/test", [&](const Request &req, Response &res) {
  2211. handler_called = true;
  2212. // Verify client certificate is present
  2213. auto cert = req.peer_cert();
  2214. EXPECT_TRUE(static_cast<bool>(cert));
  2215. res.set_content("ok", "text/plain");
  2216. });
  2217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2218. auto se = detail::scope_exit([&] {
  2219. svr.stop();
  2220. t.join();
  2221. ASSERT_FALSE(svr.is_running());
  2222. });
  2223. svr.wait_until_ready();
  2224. // Read PEM files
  2225. std::string cert_pem, key_pem, ca_pem;
  2226. read_file(SERVER_CERT_FILE, cert_pem);
  2227. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2228. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2229. // Update server certificates and client CA using PEM API while server running
  2230. ASSERT_TRUE(
  2231. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2232. // Connect with client certificate
  2233. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2234. cli.enable_server_certificate_verification(false);
  2235. cli.set_connection_timeout(30);
  2236. auto res = cli.Get("/test");
  2237. ASSERT_TRUE(res);
  2238. ASSERT_EQ(StatusCode::OK_200, res->status);
  2239. ASSERT_TRUE(handler_called);
  2240. EXPECT_EQ("ok", res->body);
  2241. }
  2242. #endif
  2243. TEST(ErrorHandlerTest, ContentLength) {
  2244. Server svr;
  2245. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2246. res.status = StatusCode::OK_200;
  2247. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2248. "text/html"); // <= Content-Length still 13
  2249. });
  2250. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2251. res.set_content("Hello World!\n", "text/plain");
  2252. res.status = 524;
  2253. });
  2254. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2255. auto se = detail::scope_exit([&] {
  2256. svr.stop();
  2257. thread.join();
  2258. ASSERT_FALSE(svr.is_running());
  2259. });
  2260. svr.wait_until_ready();
  2261. {
  2262. Client cli(HOST, PORT);
  2263. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(StatusCode::OK_200, res->status);
  2266. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2267. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2268. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2269. }
  2270. }
  2271. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2272. TEST(ExceptionTest, WithoutExceptionHandler) {
  2273. Server svr;
  2274. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2275. throw std::runtime_error("exception...");
  2276. });
  2277. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2278. throw std::runtime_error("exception\r\n...");
  2279. });
  2280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2281. auto se = detail::scope_exit([&] {
  2282. svr.stop();
  2283. listen_thread.join();
  2284. ASSERT_FALSE(svr.is_running());
  2285. });
  2286. svr.wait_until_ready();
  2287. Client cli("localhost", PORT);
  2288. {
  2289. auto res = cli.Get("/exception");
  2290. ASSERT_TRUE(res);
  2291. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2292. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2293. }
  2294. {
  2295. auto res = cli.Get("/unknown");
  2296. ASSERT_TRUE(res);
  2297. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2298. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2299. }
  2300. }
  2301. TEST(ExceptionTest, WithExceptionHandler) {
  2302. Server svr;
  2303. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2304. std::exception_ptr ep) {
  2305. EXPECT_FALSE(ep == nullptr);
  2306. try {
  2307. std::rethrow_exception(ep);
  2308. } catch (std::exception &e) {
  2309. EXPECT_EQ("abc", std::string(e.what()));
  2310. } catch (...) {}
  2311. res.status = StatusCode::InternalServerError_500;
  2312. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2313. "text/html"); // <= Content-Length still 13 at this point
  2314. });
  2315. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2316. res.set_content("Hello World!\n", "text/plain");
  2317. throw std::runtime_error("abc");
  2318. });
  2319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2320. auto se = detail::scope_exit([&] {
  2321. svr.stop();
  2322. thread.join();
  2323. ASSERT_FALSE(svr.is_running());
  2324. });
  2325. svr.wait_until_ready();
  2326. for (size_t i = 0; i < 10; i++) {
  2327. Client cli(HOST, PORT);
  2328. for (size_t j = 0; j < 100; j++) {
  2329. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2332. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2333. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2334. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2335. }
  2336. cli.set_keep_alive(true);
  2337. for (size_t j = 0; j < 100; j++) {
  2338. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2339. ASSERT_TRUE(res);
  2340. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2342. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2343. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2344. }
  2345. }
  2346. }
  2347. TEST(ExceptionTest, AndErrorHandler) {
  2348. Server svr;
  2349. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2350. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2351. });
  2352. svr.set_exception_handler(
  2353. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2354. EXPECT_FALSE(ep == nullptr);
  2355. try {
  2356. std::rethrow_exception(ep);
  2357. } catch (std::exception &e) {
  2358. res.set_content(e.what(), "text/html");
  2359. } catch (...) {}
  2360. res.status = StatusCode::InternalServerError_500;
  2361. });
  2362. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2363. throw std::runtime_error("EXCEPTION");
  2364. });
  2365. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2366. res.set_content("ERROR", "text/html");
  2367. res.status = StatusCode::InternalServerError_500;
  2368. });
  2369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2370. auto se = detail::scope_exit([&] {
  2371. svr.stop();
  2372. thread.join();
  2373. ASSERT_FALSE(svr.is_running());
  2374. });
  2375. svr.wait_until_ready();
  2376. Client cli(HOST, PORT);
  2377. {
  2378. auto res = cli.Get("/exception");
  2379. ASSERT_TRUE(res);
  2380. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2381. EXPECT_EQ("EXCEPTION", res->body);
  2382. }
  2383. {
  2384. auto res = cli.Get("/error");
  2385. ASSERT_TRUE(res);
  2386. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2387. EXPECT_EQ("ERROR", res->body);
  2388. }
  2389. {
  2390. auto res = cli.Get("/invalid");
  2391. ASSERT_TRUE(res);
  2392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2393. EXPECT_EQ("NOT_FOUND", res->body);
  2394. }
  2395. }
  2396. #endif
  2397. TEST(NoContentTest, ContentLength) {
  2398. Server svr;
  2399. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2400. res.status = StatusCode::NoContent_204;
  2401. });
  2402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2403. auto se = detail::scope_exit([&] {
  2404. svr.stop();
  2405. thread.join();
  2406. ASSERT_FALSE(svr.is_running());
  2407. });
  2408. svr.wait_until_ready();
  2409. {
  2410. Client cli(HOST, PORT);
  2411. auto res = cli.Get("/hi");
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2415. }
  2416. }
  2417. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2418. #ifdef CPPHTTPLIB_SSL_ENABLED
  2419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2420. ASSERT_TRUE(svr.is_valid());
  2421. #else
  2422. Server svr;
  2423. #endif
  2424. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2425. if (req.path == "/routing_handler") {
  2426. res.set_header("PRE_ROUTING", "on");
  2427. res.set_content("Routing Handler", "text/plain");
  2428. return httplib::Server::HandlerResponse::Handled;
  2429. }
  2430. return httplib::Server::HandlerResponse::Unhandled;
  2431. });
  2432. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2433. res.set_content("Error", "text/html");
  2434. });
  2435. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("POST_ROUTING", "on");
  2438. }
  2439. });
  2440. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2441. res.set_content("Hello World!\n", "text/plain");
  2442. });
  2443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2444. auto se = detail::scope_exit([&] {
  2445. svr.stop();
  2446. thread.join();
  2447. ASSERT_FALSE(svr.is_running());
  2448. });
  2449. svr.wait_until_ready();
  2450. {
  2451. #ifdef CPPHTTPLIB_SSL_ENABLED
  2452. SSLClient cli(HOST, PORT);
  2453. cli.enable_server_certificate_verification(false);
  2454. #else
  2455. Client cli(HOST, PORT);
  2456. #endif
  2457. auto res = cli.Get("/routing_handler");
  2458. ASSERT_TRUE(res);
  2459. EXPECT_EQ(StatusCode::OK_200, res->status);
  2460. EXPECT_EQ("Routing Handler", res->body);
  2461. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2462. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2463. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2464. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2465. }
  2466. {
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(HOST, PORT);
  2469. cli.enable_server_certificate_verification(false);
  2470. #else
  2471. Client cli(HOST, PORT);
  2472. #endif
  2473. auto res = cli.Get("/hi");
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(StatusCode::OK_200, res->status);
  2476. EXPECT_EQ("Hello World!\n", res->body);
  2477. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2478. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2479. }
  2480. {
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(HOST, PORT);
  2483. cli.enable_server_certificate_verification(false);
  2484. #else
  2485. Client cli(HOST, PORT);
  2486. #endif
  2487. auto res = cli.Get("/aaa");
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2490. EXPECT_EQ("Error", res->body);
  2491. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2492. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2493. }
  2494. }
  2495. TEST(RequestHandlerTest, PreRequestHandler) {
  2496. auto route_path = "/user/:user";
  2497. Server svr;
  2498. svr.Get("/hi", [](const Request &, Response &res) {
  2499. res.set_content("hi", "text/plain");
  2500. });
  2501. svr.Get(route_path, [](const Request &req, Response &res) {
  2502. res.set_content(req.path_params.at("user"), "text/plain");
  2503. });
  2504. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2505. if (req.matched_route == route_path) {
  2506. auto user = req.path_params.at("user");
  2507. if (user != "john") {
  2508. res.status = StatusCode::Forbidden_403;
  2509. res.set_content("error", "text/html");
  2510. return Server::HandlerResponse::Handled;
  2511. }
  2512. }
  2513. return Server::HandlerResponse::Unhandled;
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. {
  2524. auto res = cli.Get("/hi");
  2525. ASSERT_TRUE(res);
  2526. EXPECT_EQ(StatusCode::OK_200, res->status);
  2527. EXPECT_EQ("hi", res->body);
  2528. }
  2529. {
  2530. auto res = cli.Get("/user/john");
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(StatusCode::OK_200, res->status);
  2533. EXPECT_EQ("john", res->body);
  2534. }
  2535. {
  2536. auto res = cli.Get("/user/invalid-user");
  2537. ASSERT_TRUE(res);
  2538. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2539. EXPECT_EQ("error", res->body);
  2540. }
  2541. }
  2542. TEST(AnyTest, BasicOperations) {
  2543. // Default construction
  2544. httplib::any a;
  2545. EXPECT_FALSE(a.has_value());
  2546. // Value construction and any_cast (pointer form, noexcept)
  2547. httplib::any b(42);
  2548. EXPECT_TRUE(b.has_value());
  2549. auto *p = httplib::any_cast<int>(&b);
  2550. ASSERT_NE(nullptr, p);
  2551. EXPECT_EQ(42, *p);
  2552. // Type mismatch → nullptr
  2553. auto *q = httplib::any_cast<std::string>(&b);
  2554. EXPECT_EQ(nullptr, q);
  2555. // any_cast (value form) succeeds
  2556. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2557. // any_cast (value form) throws on type mismatch
  2558. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2559. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2560. #endif
  2561. // Copy
  2562. httplib::any c = b;
  2563. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2564. // Move
  2565. httplib::any d = std::move(c);
  2566. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2567. // Assignment with different type
  2568. b = std::string("hello");
  2569. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2570. // Reset
  2571. b.reset();
  2572. EXPECT_FALSE(b.has_value());
  2573. }
  2574. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2575. struct AuthCtx {
  2576. std::string user_id;
  2577. };
  2578. Server svr;
  2579. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2580. res.user_data["auth"] = AuthCtx{"alice"};
  2581. return Server::HandlerResponse::Unhandled;
  2582. });
  2583. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2584. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2585. ASSERT_NE(nullptr, ctx);
  2586. res.set_content("Hello " + ctx->user_id, "text/plain");
  2587. });
  2588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2589. auto se = detail::scope_exit([&] {
  2590. svr.stop();
  2591. thread.join();
  2592. ASSERT_FALSE(svr.is_running());
  2593. });
  2594. svr.wait_until_ready();
  2595. Client cli(HOST, PORT);
  2596. auto res = cli.Get("/me");
  2597. ASSERT_TRUE(res);
  2598. EXPECT_EQ(StatusCode::OK_200, res->status);
  2599. EXPECT_EQ("Hello alice", res->body);
  2600. }
  2601. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2602. struct RoleCtx {
  2603. std::string role;
  2604. };
  2605. Server svr;
  2606. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2607. res.user_data["role"] = RoleCtx{"admin"};
  2608. return Server::HandlerResponse::Unhandled;
  2609. });
  2610. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2611. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2612. ASSERT_NE(nullptr, ctx);
  2613. res.set_content(ctx->role, "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/role");
  2624. ASSERT_TRUE(res);
  2625. EXPECT_EQ(StatusCode::OK_200, res->status);
  2626. EXPECT_EQ("admin", res->body);
  2627. }
  2628. TEST(InvalidFormatTest, StatusCode) {
  2629. Server svr;
  2630. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2631. res.set_content("Hello World!\n", "text/plain");
  2632. res.status = 9999; // Status should be a three-digit code...
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. {
  2642. Client cli(HOST, PORT);
  2643. auto res = cli.Get("/hi");
  2644. ASSERT_FALSE(res);
  2645. }
  2646. }
  2647. TEST(URLFragmentTest, WithFragment) {
  2648. Server svr;
  2649. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2650. EXPECT_TRUE(req.target == "/hi");
  2651. });
  2652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2653. auto se = detail::scope_exit([&] {
  2654. svr.stop();
  2655. thread.join();
  2656. ASSERT_FALSE(svr.is_running());
  2657. });
  2658. svr.wait_until_ready();
  2659. {
  2660. Client cli(HOST, PORT);
  2661. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2662. EXPECT_TRUE(res);
  2663. EXPECT_EQ(StatusCode::OK_200, res->status);
  2664. res = cli.Get("/hi%23key1=val1=key2=val2");
  2665. EXPECT_TRUE(res);
  2666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2667. }
  2668. }
  2669. TEST(HeaderWriter, SetHeaderWriter) {
  2670. Server svr;
  2671. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2672. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2673. return detail::write_headers(strm, hdrs);
  2674. });
  2675. svr.Get("/hi", [](const Request &req, Response &res) {
  2676. auto it = req.headers.find("CustomClientHeader");
  2677. EXPECT_TRUE(it != req.headers.end());
  2678. EXPECT_EQ(it->second, "CustomClientValue");
  2679. res.set_content("Hello World!\n", "text/plain");
  2680. });
  2681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2682. auto se = detail::scope_exit([&] {
  2683. svr.stop();
  2684. thread.join();
  2685. ASSERT_FALSE(svr.is_running());
  2686. });
  2687. svr.wait_until_ready();
  2688. {
  2689. Client cli(HOST, PORT);
  2690. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2691. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2692. return detail::write_headers(strm, hdrs);
  2693. });
  2694. auto res = cli.Get("/hi");
  2695. EXPECT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. auto it = res->headers.find("CustomServerHeader");
  2698. EXPECT_TRUE(it != res->headers.end());
  2699. EXPECT_EQ(it->second, "CustomServerValue");
  2700. }
  2701. }
  2702. class ServerTest : public ::testing::Test {
  2703. protected:
  2704. ServerTest()
  2705. : cli_(HOST, PORT)
  2706. #ifdef CPPHTTPLIB_SSL_ENABLED
  2707. ,
  2708. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2709. #endif
  2710. {
  2711. #ifdef CPPHTTPLIB_SSL_ENABLED
  2712. cli_.enable_server_certificate_verification(false);
  2713. #endif
  2714. // Allow LARGE_DATA (100MB) responses
  2715. cli_.set_payload_max_length(200 * 1024 * 1024);
  2716. }
  2717. virtual void SetUp() {
  2718. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2719. svr_.set_payload_max_length(200 * 1024 * 1024);
  2720. svr_.set_mount_point("/", "./www");
  2721. svr_.set_mount_point("/mount", "./www2");
  2722. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2723. svr_.Get("/hi",
  2724. [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. })
  2727. .Get("/file_content",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_file_content("./www/dir/test.html");
  2730. })
  2731. .Get("/file_content_with_content_type",
  2732. [&](const Request & /*req*/, Response &res) {
  2733. res.set_file_content("./www/file", "text/plain");
  2734. })
  2735. .Get("/invalid_file_content",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_file_content("./www/dir/invalid_file_path");
  2738. })
  2739. .Get("/http_response_splitting",
  2740. [&](const Request & /*req*/, Response &res) {
  2741. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2742. EXPECT_EQ(0U, res.headers.size());
  2743. EXPECT_FALSE(res.has_header("a"));
  2744. res.set_header("a", "1\nSet-Cookie: a=1");
  2745. EXPECT_EQ(0U, res.headers.size());
  2746. EXPECT_FALSE(res.has_header("a"));
  2747. res.set_header("a", "1\rSet-Cookie: a=1");
  2748. EXPECT_EQ(0U, res.headers.size());
  2749. EXPECT_FALSE(res.has_header("a"));
  2750. res.set_header("a\r\nb", "0");
  2751. EXPECT_EQ(0U, res.headers.size());
  2752. EXPECT_FALSE(res.has_header("a"));
  2753. res.set_header("a\rb", "0");
  2754. EXPECT_EQ(0U, res.headers.size());
  2755. EXPECT_FALSE(res.has_header("a"));
  2756. res.set_header("a\nb", "0");
  2757. EXPECT_EQ(0U, res.headers.size());
  2758. EXPECT_FALSE(res.has_header("a"));
  2759. res.set_redirect("1\r\nSet-Cookie: a=1");
  2760. EXPECT_EQ(0U, res.headers.size());
  2761. EXPECT_FALSE(res.has_header("Location"));
  2762. })
  2763. .Get("/slow",
  2764. [&](const Request & /*req*/, Response &res) {
  2765. std::this_thread::sleep_for(std::chrono::seconds(2));
  2766. res.set_content("slow", "text/plain");
  2767. })
  2768. #if 0
  2769. .Post("/slowpost",
  2770. [&](const Request & /*req*/, Response &res) {
  2771. std::this_thread::sleep_for(std::chrono::seconds(2));
  2772. res.set_content("slow", "text/plain");
  2773. })
  2774. #endif
  2775. .Get("/remote_addr",
  2776. [&](const Request &req, Response &res) {
  2777. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2778. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2779. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2780. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2781. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2782. #endif
  2783. res.set_content(req.remote_addr, "text/plain");
  2784. })
  2785. .Get("/local_addr",
  2786. [&](const Request &req, Response &res) {
  2787. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2788. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2789. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2790. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2791. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2792. #endif
  2793. auto local_addr = req.local_addr;
  2794. auto local_port = std::to_string(req.local_port);
  2795. res.set_content(local_addr.append(":").append(local_port),
  2796. "text/plain");
  2797. })
  2798. .Get("/endwith%",
  2799. [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. })
  2802. .Get("/a\\+\\+b",
  2803. [&](const Request &req, Response &res) {
  2804. ASSERT_TRUE(req.has_param("a +b"));
  2805. auto val = req.get_param_value("a +b");
  2806. res.set_content(val, "text/plain");
  2807. })
  2808. .Get("/", [&](const Request & /*req*/,
  2809. Response &res) { res.set_redirect("/hi"); })
  2810. .Post("/1",
  2811. [](const Request & /*req*/, Response &res) {
  2812. res.set_redirect("/2", StatusCode::SeeOther_303);
  2813. })
  2814. .Get("/2",
  2815. [](const Request & /*req*/, Response &res) {
  2816. res.set_content("redirected.", "text/plain");
  2817. res.status = StatusCode::OK_200;
  2818. })
  2819. .Post("/person",
  2820. [&](const Request &req, Response &res) {
  2821. if (req.has_param("name") && req.has_param("note")) {
  2822. persons_[req.get_param_value("name")] =
  2823. req.get_param_value("note");
  2824. } else {
  2825. res.status = StatusCode::BadRequest_400;
  2826. }
  2827. })
  2828. .Put("/person",
  2829. [&](const Request &req, Response &res) {
  2830. if (req.has_param("name") && req.has_param("note")) {
  2831. persons_[req.get_param_value("name")] =
  2832. req.get_param_value("note");
  2833. } else {
  2834. res.status = StatusCode::BadRequest_400;
  2835. }
  2836. })
  2837. .Get("/person/(.*)",
  2838. [&](const Request &req, Response &res) {
  2839. string name = req.matches[1];
  2840. if (persons_.find(name) != persons_.end()) {
  2841. auto note = persons_[name];
  2842. res.set_content(note, "text/plain");
  2843. } else {
  2844. res.status = StatusCode::NotFound_404;
  2845. }
  2846. })
  2847. .Delete("/person",
  2848. [&](const Request &req, Response &res) {
  2849. if (req.has_param("name")) {
  2850. string name = req.get_param_value("name");
  2851. if (persons_.find(name) != persons_.end()) {
  2852. persons_.erase(name);
  2853. res.set_content("DELETED", "text/plain");
  2854. } else {
  2855. res.status = StatusCode::NotFound_404;
  2856. }
  2857. } else {
  2858. res.status = StatusCode::BadRequest_400;
  2859. }
  2860. })
  2861. .Post("/x-www-form-urlencoded-json",
  2862. [&](const Request &req, Response &res) {
  2863. auto json = req.get_param_value("json");
  2864. ASSERT_EQ(JSON_DATA, json);
  2865. res.set_content(json, "appliation/json");
  2866. res.status = StatusCode::OK_200;
  2867. })
  2868. .Get("/streamed-chunked",
  2869. [&](const Request & /*req*/, Response &res) {
  2870. res.set_chunked_content_provider(
  2871. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2872. sink.os << "123";
  2873. sink.os << "456";
  2874. sink.os << "789";
  2875. sink.done();
  2876. return true;
  2877. });
  2878. })
  2879. .Get("/streamed-chunked-with-prohibited-trailer",
  2880. [&](const Request & /*req*/, Response &res) {
  2881. auto i = new int(0);
  2882. // Declare both a prohibited trailer (Content-Length) and an
  2883. // allowed one
  2884. res.set_header("Trailer", "Content-Length, X-Allowed");
  2885. res.set_chunked_content_provider(
  2886. "text/plain",
  2887. [i](size_t /*offset*/, DataSink &sink) {
  2888. switch (*i) {
  2889. case 0: sink.os << "123"; break;
  2890. case 1: sink.os << "456"; break;
  2891. case 2: sink.os << "789"; break;
  2892. case 3: {
  2893. sink.done_with_trailer(
  2894. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2895. } break;
  2896. }
  2897. (*i)++;
  2898. return true;
  2899. },
  2900. [i](bool success) {
  2901. EXPECT_TRUE(success);
  2902. delete i;
  2903. });
  2904. })
  2905. .Get("/streamed-chunked2",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. auto i = new int(0);
  2908. res.set_chunked_content_provider(
  2909. "text/plain",
  2910. [i](size_t /*offset*/, DataSink &sink) {
  2911. switch (*i) {
  2912. case 0: sink.os << "123"; break;
  2913. case 1: sink.os << "456"; break;
  2914. case 2: sink.os << "789"; break;
  2915. case 3: sink.done(); break;
  2916. }
  2917. (*i)++;
  2918. return true;
  2919. },
  2920. [i](bool success) {
  2921. EXPECT_TRUE(success);
  2922. delete i;
  2923. });
  2924. })
  2925. .Get("/streamed-chunked-with-trailer",
  2926. [&](const Request & /*req*/, Response &res) {
  2927. auto i = new int(0);
  2928. res.set_header("Trailer", "Dummy1, Dummy2");
  2929. res.set_chunked_content_provider(
  2930. "text/plain",
  2931. [i](size_t /*offset*/, DataSink &sink) {
  2932. switch (*i) {
  2933. case 0: sink.os << "123"; break;
  2934. case 1: sink.os << "456"; break;
  2935. case 2: sink.os << "789"; break;
  2936. case 3: {
  2937. sink.done_with_trailer(
  2938. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2939. } break;
  2940. }
  2941. (*i)++;
  2942. return true;
  2943. },
  2944. [i](bool success) {
  2945. EXPECT_TRUE(success);
  2946. delete i;
  2947. });
  2948. })
  2949. .Get("/streamed",
  2950. [&](const Request & /*req*/, Response &res) {
  2951. res.set_content_provider(
  2952. 6, "text/plain",
  2953. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2954. sink.os << (offset < 3 ? "a" : "b");
  2955. return true;
  2956. });
  2957. })
  2958. .Get("/streamed-with-range",
  2959. [&](const Request &req, Response &res) {
  2960. auto data = new std::string("abcdefg");
  2961. res.set_content_provider(
  2962. data->size(), "text/plain",
  2963. [data](size_t offset, size_t length, DataSink &sink) {
  2964. size_t DATA_CHUNK_SIZE = 4;
  2965. const auto &d = *data;
  2966. auto out_len =
  2967. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2968. auto ret =
  2969. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2970. EXPECT_TRUE(ret);
  2971. return true;
  2972. },
  2973. [data, &req](bool success) {
  2974. EXPECT_EQ(success, !req.has_param("error"));
  2975. delete data;
  2976. });
  2977. })
  2978. .Get("/streamed-cancel",
  2979. [&](const Request & /*req*/, Response &res) {
  2980. res.set_content_provider(
  2981. size_t(-1), "text/plain",
  2982. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2983. sink.os << "data_chunk";
  2984. return true;
  2985. });
  2986. })
  2987. .Get("/regex-with-delimiter",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. ASSERT_TRUE(req.has_param("key"));
  2990. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2991. })
  2992. .Get("/with-range",
  2993. [&](const Request & /*req*/, Response &res) {
  2994. res.set_content("abcdefg", "text/plain");
  2995. })
  2996. .Get("/test-start-time",
  2997. [&](const Request &req, Response & /*res*/) {
  2998. EXPECT_NE(req.start_time_,
  2999. std::chrono::steady_clock::time_point::min());
  3000. })
  3001. .Get("/with-range-customized-response",
  3002. [&](const Request & /*req*/, Response &res) {
  3003. res.status = StatusCode::BadRequest_400;
  3004. res.set_content(JSON_DATA, "application/json");
  3005. })
  3006. .Post("/chunked",
  3007. [&](const Request &req, Response & /*res*/) {
  3008. EXPECT_EQ(req.body, "dechunked post body");
  3009. })
  3010. .Post("/large-chunked",
  3011. [&](const Request &req, Response & /*res*/) {
  3012. std::string expected(6 * 30 * 1024u, 'a');
  3013. EXPECT_EQ(req.body, expected);
  3014. })
  3015. .Post("/multipart",
  3016. [&](const Request &req, Response & /*res*/) {
  3017. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3018. req.form.get_field_count("text2") +
  3019. req.form.get_field_count("file3") +
  3020. req.form.get_field_count("file4"));
  3021. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3022. req.form.get_file_count("file2"));
  3023. ASSERT_TRUE(!req.form.has_file("???"));
  3024. ASSERT_TRUE(!req.form.has_field("???"));
  3025. ASSERT_TRUE(req.body.empty());
  3026. {
  3027. const auto &text = req.form.get_field("text1");
  3028. EXPECT_EQ("text default", text);
  3029. }
  3030. {
  3031. const auto &text = req.form.get_field("text2");
  3032. EXPECT_EQ("aωb", text);
  3033. }
  3034. {
  3035. const auto &file = req.form.get_file("file1");
  3036. EXPECT_EQ("hello.txt", file.filename);
  3037. EXPECT_EQ("text/plain", file.content_type);
  3038. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3039. }
  3040. {
  3041. const auto &file = req.form.get_file("file2");
  3042. EXPECT_EQ("world.json", file.filename);
  3043. EXPECT_EQ("application/json", file.content_type);
  3044. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3045. }
  3046. {
  3047. const auto &text = req.form.get_field("file3");
  3048. EXPECT_EQ(0u, text.size());
  3049. }
  3050. {
  3051. const auto &text = req.form.get_field("file4");
  3052. EXPECT_EQ(0u, text.size());
  3053. }
  3054. })
  3055. .Post("/multipart/multi_file_values",
  3056. [&](const Request &req, Response & /*res*/) {
  3057. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3058. req.form.get_field_count("multi_text1"));
  3059. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3060. ASSERT_TRUE(!req.form.has_file("???"));
  3061. ASSERT_TRUE(!req.form.has_field("???"));
  3062. ASSERT_TRUE(req.body.empty());
  3063. {
  3064. const auto &text = req.form.get_field("text");
  3065. EXPECT_EQ("default text", text);
  3066. }
  3067. {
  3068. const auto &text1_values = req.form.get_fields("multi_text1");
  3069. EXPECT_EQ(2u, text1_values.size());
  3070. EXPECT_EQ("aaaaa", text1_values[0]);
  3071. EXPECT_EQ("bbbbb", text1_values[1]);
  3072. }
  3073. {
  3074. const auto &file1_values = req.form.get_files("multi_file1");
  3075. EXPECT_EQ(2u, file1_values.size());
  3076. auto file1 = file1_values[0];
  3077. EXPECT_EQ(file1.filename, "hello.txt");
  3078. EXPECT_EQ(file1.content_type, "text/plain");
  3079. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3080. auto file2 = file1_values[1];
  3081. EXPECT_EQ(file2.filename, "world.json");
  3082. EXPECT_EQ(file2.content_type, "application/json");
  3083. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3084. }
  3085. })
  3086. .Post("/empty",
  3087. [&](const Request &req, Response &res) {
  3088. EXPECT_EQ(req.body, "");
  3089. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3090. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3091. res.set_content("empty", "text/plain");
  3092. })
  3093. .Post("/empty-no-content-type",
  3094. [&](const Request &req, Response &res) {
  3095. EXPECT_EQ(req.body, "");
  3096. EXPECT_FALSE(req.has_header("Content-Type"));
  3097. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3098. res.set_content("empty-no-content-type", "text/plain");
  3099. })
  3100. .Post("/path-only",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(req.body, "");
  3103. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3104. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3105. res.set_content("path-only", "text/plain");
  3106. })
  3107. .Post("/path-headers-only",
  3108. [&](const Request &req, Response &res) {
  3109. EXPECT_EQ(req.body, "");
  3110. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3111. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3112. EXPECT_EQ("world", req.get_header_value("hello"));
  3113. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3114. res.set_content("path-headers-only", "text/plain");
  3115. })
  3116. .Post("/post-large",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(req.body, LARGE_DATA);
  3119. res.set_content(req.body, "text/plain");
  3120. })
  3121. .Post("/post-loopback",
  3122. [&](const Request &, Response &res,
  3123. ContentReader const &content_reader) {
  3124. std::string body;
  3125. content_reader([&](const char *data, size_t data_length) {
  3126. body.append(data, data_length);
  3127. return true;
  3128. });
  3129. res.set_content(body, "text/plain");
  3130. })
  3131. .Put("/put-loopback",
  3132. [&](const Request &, Response &res,
  3133. ContentReader const &content_reader) {
  3134. std::string body;
  3135. content_reader([&](const char *data, size_t data_length) {
  3136. body.append(data, data_length);
  3137. return true;
  3138. });
  3139. res.set_content(body, "text/plain");
  3140. })
  3141. .Patch("/patch-loopback",
  3142. [&](const Request &, Response &res,
  3143. ContentReader const &content_reader) {
  3144. std::string body;
  3145. content_reader([&](const char *data, size_t data_length) {
  3146. body.append(data, data_length);
  3147. return true;
  3148. });
  3149. res.set_content(body, "text/plain");
  3150. })
  3151. .Put("/empty-no-content-type",
  3152. [&](const Request &req, Response &res) {
  3153. EXPECT_EQ(req.body, "");
  3154. EXPECT_FALSE(req.has_header("Content-Type"));
  3155. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3156. res.set_content("empty-no-content-type", "text/plain");
  3157. })
  3158. .Put("/put",
  3159. [&](const Request &req, Response &res) {
  3160. EXPECT_EQ(req.body, "PUT");
  3161. res.set_content(req.body, "text/plain");
  3162. })
  3163. .Put("/put-large",
  3164. [&](const Request &req, Response &res) {
  3165. EXPECT_EQ(req.body, LARGE_DATA);
  3166. res.set_content(req.body, "text/plain");
  3167. })
  3168. .Patch("/patch",
  3169. [&](const Request &req, Response &res) {
  3170. EXPECT_EQ(req.body, "PATCH");
  3171. res.set_content(req.body, "text/plain");
  3172. })
  3173. .Delete("/delete",
  3174. [&](const Request & /*req*/, Response &res) {
  3175. res.set_content("DELETE", "text/plain");
  3176. })
  3177. .Delete("/delete-body",
  3178. [&](const Request &req, Response &res) {
  3179. EXPECT_EQ(req.body, "content");
  3180. res.set_content(req.body, "text/plain");
  3181. })
  3182. .Options(R"(\*)",
  3183. [&](const Request & /*req*/, Response &res) {
  3184. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3185. })
  3186. .Get("/request-target",
  3187. [&](const Request &req, Response & /*res*/) {
  3188. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3189. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3190. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3191. })
  3192. .Get("/long-query-value",
  3193. [&](const Request &req, Response & /*res*/) {
  3194. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3195. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3196. })
  3197. .Get("/too-long-query-value",
  3198. [&](const Request &req, Response & /*res*/) {
  3199. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3200. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3201. })
  3202. .Get("/array-param",
  3203. [&](const Request &req, Response & /*res*/) {
  3204. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3205. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3206. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3207. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3208. })
  3209. .Post("/validate-no-multiple-headers",
  3210. [&](const Request &req, Response & /*res*/) {
  3211. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3212. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3213. })
  3214. .Post("/content_receiver",
  3215. [&](const Request &req, Response &res,
  3216. const ContentReader &content_reader) {
  3217. if (req.is_multipart_form_data()) {
  3218. std::vector<FormData> items;
  3219. content_reader(
  3220. [&](const FormData &file) {
  3221. items.push_back(file);
  3222. return true;
  3223. },
  3224. [&](const char *data, size_t data_length) {
  3225. items.back().content.append(data, data_length);
  3226. return true;
  3227. });
  3228. EXPECT_EQ(5u, items.size());
  3229. {
  3230. const auto &file = get_file_value(items, "text1");
  3231. EXPECT_TRUE(file.filename.empty());
  3232. EXPECT_EQ("text default", file.content);
  3233. }
  3234. {
  3235. const auto &file = get_file_value(items, "text2");
  3236. EXPECT_TRUE(file.filename.empty());
  3237. EXPECT_EQ("aωb", file.content);
  3238. }
  3239. {
  3240. const auto &file = get_file_value(items, "file1");
  3241. EXPECT_EQ("hello.txt", file.filename);
  3242. EXPECT_EQ("text/plain", file.content_type);
  3243. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3244. }
  3245. {
  3246. const auto &file = get_file_value(items, "file2");
  3247. EXPECT_EQ("world.json", file.filename);
  3248. EXPECT_EQ("application/json", file.content_type);
  3249. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3250. }
  3251. {
  3252. const auto &file = get_file_value(items, "file3");
  3253. EXPECT_TRUE(file.filename.empty());
  3254. EXPECT_EQ("application/octet-stream", file.content_type);
  3255. EXPECT_EQ(0u, file.content.size());
  3256. }
  3257. } else {
  3258. std::string body;
  3259. content_reader([&](const char *data, size_t data_length) {
  3260. EXPECT_EQ(7U, data_length);
  3261. body.append(data, data_length);
  3262. return true;
  3263. });
  3264. EXPECT_EQ(body, "content");
  3265. res.set_content(body, "text/plain");
  3266. }
  3267. })
  3268. .Put("/content_receiver",
  3269. [&](const Request & /*req*/, Response &res,
  3270. const ContentReader &content_reader) {
  3271. std::string body;
  3272. content_reader([&](const char *data, size_t data_length) {
  3273. body.append(data, data_length);
  3274. return true;
  3275. });
  3276. EXPECT_EQ(body, "content");
  3277. res.set_content(body, "text/plain");
  3278. })
  3279. .Patch("/content_receiver",
  3280. [&](const Request & /*req*/, Response &res,
  3281. const ContentReader &content_reader) {
  3282. std::string body;
  3283. content_reader([&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. EXPECT_EQ(body, "content");
  3288. res.set_content(body, "text/plain");
  3289. })
  3290. .Post("/query-string-and-body",
  3291. [&](const Request &req, Response & /*res*/) {
  3292. ASSERT_TRUE(req.has_param("key"));
  3293. EXPECT_EQ(req.get_param_value("key"), "value");
  3294. EXPECT_EQ(req.body, "content");
  3295. })
  3296. .Get("/last-request",
  3297. [&](const Request &req, Response & /*res*/) {
  3298. EXPECT_EQ("close", req.get_header_value("Connection"));
  3299. })
  3300. .Get(R"(/redirect/(\d+))",
  3301. [&](const Request &req, Response &res) {
  3302. auto num = std::stoi(req.matches[1]) + 1;
  3303. std::string url = "/redirect/" + std::to_string(num);
  3304. res.set_redirect(url);
  3305. })
  3306. .Post("/binary",
  3307. [&](const Request &req, Response &res) {
  3308. EXPECT_EQ(4U, req.body.size());
  3309. EXPECT_EQ("application/octet-stream",
  3310. req.get_header_value("Content-Type"));
  3311. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3312. res.set_content(req.body, "application/octet-stream");
  3313. })
  3314. .Put("/binary",
  3315. [&](const Request &req, Response &res) {
  3316. EXPECT_EQ(4U, req.body.size());
  3317. EXPECT_EQ("application/octet-stream",
  3318. req.get_header_value("Content-Type"));
  3319. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3320. res.set_content(req.body, "application/octet-stream");
  3321. })
  3322. .Patch("/binary",
  3323. [&](const Request &req, Response &res) {
  3324. EXPECT_EQ(4U, req.body.size());
  3325. EXPECT_EQ("application/octet-stream",
  3326. req.get_header_value("Content-Type"));
  3327. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3328. res.set_content(req.body, "application/octet-stream");
  3329. })
  3330. .Delete("/binary",
  3331. [&](const Request &req, Response &res) {
  3332. EXPECT_EQ(4U, req.body.size());
  3333. EXPECT_EQ("application/octet-stream",
  3334. req.get_header_value("Content-Type"));
  3335. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3336. res.set_content(req.body, "application/octet-stream");
  3337. })
  3338. .Get("/issue1772",
  3339. [&](const Request & /*req*/, Response &res) {
  3340. res.status = 401;
  3341. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3342. })
  3343. .Delete("/issue609",
  3344. [](const httplib::Request &, httplib::Response &res,
  3345. const httplib::ContentReader &) {
  3346. res.set_content("ok", "text/plain");
  3347. })
  3348. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3349. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3350. .Get("/compress",
  3351. [&](const Request & /*req*/, Response &res) {
  3352. res.set_content(
  3353. "12345678901234567890123456789012345678901234567890123456789"
  3354. "01234567890123456789012345678901234567890",
  3355. "text/plain");
  3356. })
  3357. .Get("/compress-with-charset",
  3358. [&](const Request & /*req*/, Response &res) {
  3359. res.set_content(
  3360. "12345678901234567890123456789012345678901234567890123456789"
  3361. "01234567890123456789012345678901234567890",
  3362. "application/json; charset=utf-8");
  3363. })
  3364. .Get("/nocompress",
  3365. [&](const Request & /*req*/, Response &res) {
  3366. res.set_content(
  3367. "12345678901234567890123456789012345678901234567890123456789"
  3368. "01234567890123456789012345678901234567890",
  3369. "application/octet-stream");
  3370. })
  3371. .Post("/compress-multipart",
  3372. [&](const Request &req, Response & /*res*/) {
  3373. EXPECT_EQ(2u, req.form.fields.size());
  3374. ASSERT_TRUE(!req.form.has_field("???"));
  3375. {
  3376. const auto &text = req.form.get_field("key1");
  3377. EXPECT_EQ("test", text);
  3378. }
  3379. {
  3380. const auto &text = req.form.get_field("key2");
  3381. EXPECT_EQ("--abcdefg123", text);
  3382. }
  3383. })
  3384. #endif
  3385. ;
  3386. persons_["john"] = "programmer";
  3387. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3388. svr_.wait_until_ready();
  3389. }
  3390. virtual void TearDown() {
  3391. svr_.stop();
  3392. if (!request_threads_.empty()) {
  3393. std::this_thread::sleep_for(std::chrono::seconds(1));
  3394. for (auto &t : request_threads_) {
  3395. t.join();
  3396. }
  3397. }
  3398. t_.join();
  3399. }
  3400. map<string, string> persons_;
  3401. #ifdef CPPHTTPLIB_SSL_ENABLED
  3402. SSLClient cli_;
  3403. SSLServer svr_;
  3404. #else
  3405. Client cli_;
  3406. Server svr_;
  3407. #endif
  3408. thread t_;
  3409. std::vector<thread> request_threads_;
  3410. };
  3411. TEST_F(ServerTest, GetMethod200) {
  3412. auto res = cli_.Get("/hi");
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ("HTTP/1.1", res->version);
  3415. EXPECT_EQ(StatusCode::OK_200, res->status);
  3416. EXPECT_EQ("OK", res->reason);
  3417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3418. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3419. EXPECT_EQ("Hello World!", res->body);
  3420. }
  3421. TEST_F(ServerTest, GetEmptyFile) {
  3422. auto res = cli_.Get("/empty_file");
  3423. ASSERT_TRUE(res);
  3424. EXPECT_EQ(StatusCode::OK_200, res->status);
  3425. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3426. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3427. EXPECT_EQ("", res->body);
  3428. }
  3429. TEST_F(ServerTest, GetFileContent) {
  3430. auto res = cli_.Get("/file_content");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3435. EXPECT_EQ("test.html", res->body);
  3436. }
  3437. TEST_F(ServerTest, GetFileContentWithRange) {
  3438. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3441. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3442. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3443. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3444. EXPECT_EQ("est", res->body);
  3445. }
  3446. TEST_F(ServerTest, GetFileContentWithContentType) {
  3447. auto res = cli_.Get("/file_content_with_content_type");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3452. EXPECT_EQ("file\n", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetInvalidFileContent) {
  3455. auto res = cli_.Get("/invalid_file_content");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3458. }
  3459. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3460. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3461. ASSERT_TRUE(res);
  3462. EXPECT_EQ("HTTP/1.1", res->version);
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3465. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3466. EXPECT_EQ("Hello World!", res->body);
  3467. }
  3468. TEST_F(ServerTest, GetMethod302) {
  3469. auto res = cli_.Get("/");
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(StatusCode::Found_302, res->status);
  3472. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3473. }
  3474. TEST_F(ServerTest, GetMethod302Redirect) {
  3475. cli_.set_follow_location(true);
  3476. auto res = cli_.Get("/");
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("Hello World!", res->body);
  3480. EXPECT_EQ("/hi", res->location);
  3481. }
  3482. TEST_F(ServerTest, GetMethod404) {
  3483. auto res = cli_.Get("/invalid");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3486. }
  3487. TEST_F(ServerTest, HeadMethod200) {
  3488. auto res = cli_.Head("/hi");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_TRUE(res->body.empty());
  3493. }
  3494. TEST_F(ServerTest, HeadMethod200Static) {
  3495. auto res = cli_.Head("/mount/dir/index.html");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::OK_200, res->status);
  3498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3499. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3500. EXPECT_TRUE(res->body.empty());
  3501. }
  3502. TEST_F(ServerTest, HeadMethod404) {
  3503. auto res = cli_.Head("/invalid");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3506. EXPECT_TRUE(res->body.empty());
  3507. }
  3508. TEST_F(ServerTest, GetMethodPersonJohn) {
  3509. auto res = cli_.Get("/person/john");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("programmer", res->body);
  3514. }
  3515. TEST_F(ServerTest, PostMethod1) {
  3516. auto res = cli_.Get("/person/john1");
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3519. res = cli_.Post("/person", "name=john1&note=coder",
  3520. "application/x-www-form-urlencoded");
  3521. ASSERT_TRUE(res);
  3522. ASSERT_EQ(StatusCode::OK_200, res->status);
  3523. res = cli_.Get("/person/john1");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3527. ASSERT_EQ("coder", res->body);
  3528. }
  3529. TEST_F(ServerTest, PostMethod2) {
  3530. auto res = cli_.Get("/person/john2");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3533. Params params;
  3534. params.emplace("name", "john2");
  3535. params.emplace("note", "coder");
  3536. res = cli_.Post("/person", params);
  3537. ASSERT_TRUE(res);
  3538. ASSERT_EQ(StatusCode::OK_200, res->status);
  3539. res = cli_.Get("/person/john2");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. ASSERT_EQ("coder", res->body);
  3544. }
  3545. TEST_F(ServerTest, PutMethod3) {
  3546. auto res = cli_.Get("/person/john3");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3549. Params params;
  3550. params.emplace("name", "john3");
  3551. params.emplace("note", "coder");
  3552. res = cli_.Put("/person", params);
  3553. ASSERT_TRUE(res);
  3554. ASSERT_EQ(StatusCode::OK_200, res->status);
  3555. res = cli_.Get("/person/john3");
  3556. ASSERT_TRUE(res);
  3557. ASSERT_EQ(StatusCode::OK_200, res->status);
  3558. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3559. ASSERT_EQ("coder", res->body);
  3560. }
  3561. TEST_F(ServerTest, DeleteMethod1) {
  3562. auto res = cli_.Get("/person/john4");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3565. Params params;
  3566. params.emplace("name", "john4");
  3567. params.emplace("note", "coder");
  3568. res = cli_.Post("/person", params);
  3569. ASSERT_TRUE(res);
  3570. ASSERT_EQ(StatusCode::OK_200, res->status);
  3571. res = cli_.Get("/person/john4");
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3575. ASSERT_EQ("coder", res->body);
  3576. Params delete_params;
  3577. delete_params.emplace("name", "john4");
  3578. res = cli_.Delete("/person", delete_params);
  3579. ASSERT_TRUE(res);
  3580. ASSERT_EQ(StatusCode::OK_200, res->status);
  3581. ASSERT_EQ("DELETED", res->body);
  3582. res = cli_.Get("/person/john4");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3585. }
  3586. TEST_F(ServerTest, DeleteMethod2) {
  3587. auto res = cli_.Get("/person/john5");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3590. Params params;
  3591. params.emplace("name", "john5");
  3592. params.emplace("note", "developer");
  3593. res = cli_.Post("/person", params);
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::OK_200, res->status);
  3596. res = cli_.Get("/person/john5");
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3600. ASSERT_EQ("developer", res->body);
  3601. Params delete_params;
  3602. delete_params.emplace("name", "john5");
  3603. Headers headers;
  3604. headers.emplace("Custom-Header", "test-value");
  3605. res = cli_.Delete("/person", headers, delete_params);
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ("DELETED", res->body);
  3609. res = cli_.Get("/person/john5");
  3610. ASSERT_TRUE(res);
  3611. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3612. }
  3613. TEST_F(ServerTest, DeleteMethod3) {
  3614. auto res = cli_.Get("/person/john6");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3617. Params params;
  3618. params.emplace("name", "john6");
  3619. params.emplace("note", "tester");
  3620. res = cli_.Post("/person", params);
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::OK_200, res->status);
  3623. res = cli_.Get("/person/john6");
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3627. ASSERT_EQ("tester", res->body);
  3628. Params delete_params;
  3629. delete_params.emplace("name", "john6");
  3630. Headers headers;
  3631. headers.emplace("Custom-Header", "test-value");
  3632. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("DELETED", res->body);
  3636. res = cli_.Get("/person/john6");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3639. }
  3640. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3641. Params params;
  3642. params.emplace("json", JSON_DATA);
  3643. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(JSON_DATA, res->body);
  3647. }
  3648. TEST_F(ServerTest, PostEmptyContent) {
  3649. auto res = cli_.Post("/empty", "", "text/plain");
  3650. ASSERT_TRUE(res);
  3651. ASSERT_EQ(StatusCode::OK_200, res->status);
  3652. ASSERT_EQ("empty", res->body);
  3653. }
  3654. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3655. auto res = cli_.Post("/empty-no-content-type");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ("empty-no-content-type", res->body);
  3659. }
  3660. TEST_F(ServerTest, PostPathOnly) {
  3661. auto res = cli_.Post("/path-only");
  3662. ASSERT_TRUE(res);
  3663. ASSERT_EQ(StatusCode::OK_200, res->status);
  3664. ASSERT_EQ("path-only", res->body);
  3665. }
  3666. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3667. auto res = cli_.Post("/path-headers-only",
  3668. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3669. ASSERT_TRUE(res);
  3670. ASSERT_EQ(StatusCode::OK_200, res->status);
  3671. ASSERT_EQ("path-headers-only", res->body);
  3672. }
  3673. TEST_F(ServerTest, PostLarge) {
  3674. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3675. ASSERT_TRUE(res);
  3676. ASSERT_EQ(StatusCode::OK_200, res->status);
  3677. EXPECT_EQ(LARGE_DATA, res->body);
  3678. }
  3679. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3680. auto res = cli_.Put("/empty-no-content-type");
  3681. ASSERT_TRUE(res);
  3682. ASSERT_EQ(StatusCode::OK_200, res->status);
  3683. ASSERT_EQ("empty-no-content-type", res->body);
  3684. }
  3685. TEST_F(ServerTest, GetMethodDir) {
  3686. auto res = cli_.Get("/dir/");
  3687. ASSERT_TRUE(res);
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3690. auto body = R"(<html>
  3691. <head>
  3692. </head>
  3693. <body>
  3694. <a href="/dir/test.html">Test</a>
  3695. <a href="/hi">hi</a>
  3696. </body>
  3697. </html>
  3698. )";
  3699. EXPECT_EQ(body, res->body);
  3700. }
  3701. TEST_F(ServerTest, GetMethodDirTest) {
  3702. auto res = cli_.Get("/dir/test.html");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3706. EXPECT_EQ("test.html", res->body);
  3707. }
  3708. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3709. auto res = cli_.Get("/dir/../dir/test.html");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::OK_200, res->status);
  3712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3713. EXPECT_EQ("test.html", res->body);
  3714. }
  3715. TEST_F(ServerTest, GetMethodInvalidPath) {
  3716. auto res = cli_.Get("/dir/../test.html");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3719. }
  3720. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3721. auto res = cli_.Get("/../www/dir/test.html");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3724. }
  3725. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3726. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. TEST_F(ServerTest, GetMethodDirMountTest) {
  3731. auto res = cli_.Get("/mount/dir/test.html");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("test.html", res->body);
  3736. }
  3737. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3738. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3742. EXPECT_EQ("test.html", res->body);
  3743. }
  3744. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3745. auto res = cli_.Get("/mount/dir/../test.html");
  3746. ASSERT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3750. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3753. }
  3754. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3755. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3756. ASSERT_TRUE(res);
  3757. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3758. }
  3759. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3760. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3761. ASSERT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3763. }
  3764. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3765. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3768. }
  3769. TEST_F(ServerTest, PostMethod303) {
  3770. auto res = cli_.Post("/1", "body", "text/plain");
  3771. ASSERT_TRUE(res);
  3772. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3773. EXPECT_EQ("/2", res->get_header_value("Location"));
  3774. }
  3775. TEST_F(ServerTest, PostMethod303Redirect) {
  3776. cli_.set_follow_location(true);
  3777. auto res = cli_.Post("/1", "body", "text/plain");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. EXPECT_EQ("redirected.", res->body);
  3781. EXPECT_EQ("/2", res->location);
  3782. }
  3783. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3784. auto res = cli_.Get("/dir/test.abcde");
  3785. ASSERT_TRUE(res);
  3786. EXPECT_EQ(StatusCode::OK_200, res->status);
  3787. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3788. EXPECT_EQ("abcde", res->body);
  3789. }
  3790. TEST_F(ServerTest, StaticFileRange) {
  3791. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3792. ASSERT_TRUE(res);
  3793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3794. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3795. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3796. EXPECT_EQ(true, res->has_header("Content-Range"));
  3797. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3798. EXPECT_EQ(std::string("cd"), res->body);
  3799. }
  3800. TEST_F(ServerTest, StaticFileRanges) {
  3801. auto res =
  3802. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_TRUE(
  3806. res->get_header_value("Content-Type")
  3807. .find(
  3808. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3809. 0);
  3810. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3811. }
  3812. TEST_F(ServerTest, StaticFileRangeHead) {
  3813. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ(true, res->has_header("Content-Range"));
  3819. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3820. }
  3821. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3822. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3827. EXPECT_EQ(true, res->has_header("Content-Range"));
  3828. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3829. res->get_header_value("Content-Range"));
  3830. EXPECT_EQ("LAST\n", res->body);
  3831. }
  3832. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3833. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3837. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(true, res->has_header("Content-Range"));
  3839. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3840. }
  3841. TEST_F(ServerTest, StaticFileBigFile) {
  3842. auto res = cli_.Get("/dir/1MB.txt");
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::OK_200, res->status);
  3845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3846. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3847. }
  3848. TEST_F(ServerTest, InvalidBaseDirMount) {
  3849. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3850. }
  3851. TEST_F(ServerTest, Binary) {
  3852. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3853. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3854. "application/octet-stream");
  3855. ASSERT_TRUE(res);
  3856. ASSERT_EQ(StatusCode::OK_200, res->status);
  3857. ASSERT_EQ(4U, res->body.size());
  3858. res = cli_.Put("/binary", binary.data(), binary.size(),
  3859. "application/octet-stream");
  3860. ASSERT_TRUE(res);
  3861. ASSERT_EQ(StatusCode::OK_200, res->status);
  3862. ASSERT_EQ(4U, res->body.size());
  3863. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3864. "application/octet-stream");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. ASSERT_EQ(4U, res->body.size());
  3868. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3869. "application/octet-stream");
  3870. ASSERT_TRUE(res);
  3871. ASSERT_EQ(StatusCode::OK_200, res->status);
  3872. ASSERT_EQ(4U, res->body.size());
  3873. }
  3874. TEST_F(ServerTest, BinaryString) {
  3875. auto binary = std::string("\x00\x01\x02\x03", 4);
  3876. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3877. ASSERT_TRUE(res);
  3878. ASSERT_EQ(StatusCode::OK_200, res->status);
  3879. ASSERT_EQ(4U, res->body.size());
  3880. res = cli_.Put("/binary", binary, "application/octet-stream");
  3881. ASSERT_TRUE(res);
  3882. ASSERT_EQ(StatusCode::OK_200, res->status);
  3883. ASSERT_EQ(4U, res->body.size());
  3884. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3885. ASSERT_TRUE(res);
  3886. ASSERT_EQ(StatusCode::OK_200, res->status);
  3887. ASSERT_EQ(4U, res->body.size());
  3888. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3889. ASSERT_TRUE(res);
  3890. ASSERT_EQ(StatusCode::OK_200, res->status);
  3891. ASSERT_EQ(4U, res->body.size());
  3892. }
  3893. TEST_F(ServerTest, EmptyRequest) {
  3894. auto res = cli_.Get("");
  3895. ASSERT_TRUE(!res);
  3896. EXPECT_EQ(Error::Connection, res.error());
  3897. }
  3898. TEST_F(ServerTest, LongRequest) {
  3899. std::string request;
  3900. for (size_t i = 0; i < 545; i++) {
  3901. request += "/TooLongRequest";
  3902. }
  3903. request += "OK";
  3904. auto res = cli_.Get(request.c_str());
  3905. ASSERT_TRUE(res);
  3906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3907. }
  3908. TEST_F(ServerTest, TooLongRequest) {
  3909. std::string request;
  3910. for (size_t i = 0; i < 546; i++) {
  3911. request += "/TooLongRequest";
  3912. }
  3913. request += "_NG";
  3914. auto start = std::chrono::high_resolution_clock::now();
  3915. cli_.set_keep_alive(true);
  3916. auto res = cli_.Get(request.c_str());
  3917. auto end = std::chrono::high_resolution_clock::now();
  3918. auto elapsed =
  3919. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3920. .count();
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3923. EXPECT_LE(elapsed, 1000);
  3924. EXPECT_EQ("close", res->get_header_value("Connection"));
  3925. EXPECT_FALSE(cli_.is_socket_open());
  3926. }
  3927. TEST_F(ServerTest, AlmostTooLongRequest) {
  3928. // test for #2046 - URI length check shouldn't include other content on req
  3929. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3930. // leading /, space, HTTP/1.1)
  3931. std::string request =
  3932. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3933. auto res = cli_.Get(request.c_str());
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3936. }
  3937. TEST_F(ServerTest, LongHeader) {
  3938. Request req;
  3939. req.method = "GET";
  3940. req.path = "/hi";
  3941. std::string host_and_port;
  3942. host_and_port += HOST;
  3943. host_and_port += ":";
  3944. host_and_port += std::to_string(PORT);
  3945. req.headers.emplace("Host", host_and_port.c_str());
  3946. req.headers.emplace("Accept", "*/*");
  3947. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3948. req.headers.emplace(
  3949. "Header-Name",
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@");
  3979. auto res = std::make_shared<Response>();
  3980. auto error = Error::Success;
  3981. auto ret = cli_.send(req, *res, error);
  3982. ASSERT_TRUE(ret);
  3983. EXPECT_EQ(StatusCode::OK_200, res->status);
  3984. }
  3985. TEST_F(ServerTest, LongQueryValue) {
  3986. auto start = std::chrono::high_resolution_clock::now();
  3987. cli_.set_keep_alive(true);
  3988. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3989. auto end = std::chrono::high_resolution_clock::now();
  3990. auto elapsed =
  3991. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3992. .count();
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3995. EXPECT_LE(elapsed, 1000);
  3996. EXPECT_EQ("close", res->get_header_value("Connection"));
  3997. EXPECT_FALSE(cli_.is_socket_open());
  3998. }
  3999. TEST_F(ServerTest, TooLongQueryValue) {
  4000. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4001. ASSERT_FALSE(res);
  4002. EXPECT_EQ(Error::Read, res.error());
  4003. }
  4004. TEST_F(ServerTest, TooLongHeader) {
  4005. Request req;
  4006. req.method = "GET";
  4007. req.path = "/hi";
  4008. std::string host_and_port;
  4009. host_and_port += HOST;
  4010. host_and_port += ":";
  4011. host_and_port += std::to_string(PORT);
  4012. req.headers.emplace("Host", host_and_port.c_str());
  4013. req.headers.emplace("Accept", "*/*");
  4014. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4015. req.headers.emplace(
  4016. "Header-Name",
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@");
  4046. auto res = std::make_shared<Response>();
  4047. auto error = Error::Success;
  4048. auto ret = cli_.send(req, *res, error);
  4049. ASSERT_TRUE(ret);
  4050. EXPECT_EQ(StatusCode::OK_200, res->status);
  4051. }
  4052. TEST_F(ServerTest, HeaderCountAtLimit) {
  4053. // Test with headers just under the 100 limit
  4054. httplib::Headers headers;
  4055. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4056. // This should keep us just under the 100 header limit
  4057. for (int i = 0; i < 95; i++) {
  4058. std::string name = "X-Test-Header-" + std::to_string(i);
  4059. std::string value = "value" + std::to_string(i);
  4060. headers.emplace(name, value);
  4061. }
  4062. // This should work fine as we're under the limit
  4063. auto res = cli_.Get("/hi", headers);
  4064. EXPECT_TRUE(res);
  4065. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4066. }
  4067. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4068. // Test with many headers to exceed the 100 limit
  4069. httplib::Headers headers;
  4070. // Add 150 headers to definitely exceed the 100 limit
  4071. for (int i = 0; i < 150; i++) {
  4072. std::string name = "X-Test-Header-" + std::to_string(i);
  4073. std::string value = "value" + std::to_string(i);
  4074. headers.emplace(name, value);
  4075. }
  4076. // This should fail due to exceeding header count limit
  4077. cli_.set_keep_alive(true);
  4078. auto res = cli_.Get("/hi", headers);
  4079. // The server should respond with 400 Bad Request
  4080. ASSERT_TRUE(res);
  4081. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4082. EXPECT_EQ("close", res->get_header_value("Connection"));
  4083. EXPECT_FALSE(cli_.is_socket_open());
  4084. }
  4085. TEST_F(ServerTest, PercentEncoding) {
  4086. auto res = cli_.Get("/e%6edwith%");
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::OK_200, res->status);
  4089. }
  4090. TEST_F(ServerTest, PercentEncodingUnicode) {
  4091. auto res = cli_.Get("/e%u006edwith%");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. }
  4095. TEST_F(ServerTest, InvalidPercentEncoding) {
  4096. auto res = cli_.Get("/%endwith%");
  4097. ASSERT_TRUE(res);
  4098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4099. }
  4100. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4101. auto res = cli_.Get("/%uendwith%");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4104. }
  4105. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4106. auto res = cli_.Get("/hello?aaa=bbb%");
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4109. }
  4110. TEST_F(ServerTest, PlusSignEncoding) {
  4111. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. EXPECT_EQ("a +b", res->body);
  4115. }
  4116. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4117. // This test simulates a potential DoS attack using many headers
  4118. // to verify our security fix prevents memory exhaustion
  4119. httplib::Headers attack_headers;
  4120. // Attempt to add many headers like an attacker would (200 headers to far
  4121. // exceed limit)
  4122. for (int i = 0; i < 200; i++) {
  4123. std::string name = "X-Attack-Header-" + std::to_string(i);
  4124. std::string value = "attack_payload_" + std::to_string(i);
  4125. attack_headers.emplace(name, value);
  4126. }
  4127. // Try to POST with excessive headers
  4128. cli_.set_keep_alive(true);
  4129. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4130. // Should either fail or return 400 Bad Request due to security limit
  4131. if (res) {
  4132. // If we get a response, it should be 400 Bad Request
  4133. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4134. EXPECT_EQ("close", res->get_header_value("Connection"));
  4135. }
  4136. EXPECT_FALSE(cli_.is_socket_open());
  4137. }
  4138. TEST_F(ServerTest, MultipartFormData) {
  4139. UploadFormDataItems items = {
  4140. {"text1", "text default", "", ""},
  4141. {"text2", "aωb", "", ""},
  4142. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4143. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4144. {"file3", "", "", "application/octet-stream"},
  4145. {"file4", "", "", " application/json tmp-string "}};
  4146. auto res = cli_.Post("/multipart", items);
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. }
  4150. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4151. UploadFormDataItems items = {
  4152. {"text", "default text", "", ""},
  4153. {"multi_text1", "aaaaa", "", ""},
  4154. {"multi_text1", "bbbbb", "", ""},
  4155. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4156. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4157. "application/json"},
  4158. };
  4159. auto res = cli_.Post("/multipart/multi_file_values", items);
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. }
  4163. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4164. auto res = cli_.Get("/hi");
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4168. EXPECT_EQ("Hello World!", res->body);
  4169. }
  4170. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4171. Request req;
  4172. req.method = "POST";
  4173. req.path = "/chunked";
  4174. std::string host_and_port;
  4175. host_and_port += HOST;
  4176. host_and_port += ":";
  4177. host_and_port += std::to_string(PORT);
  4178. req.headers.emplace("Host", host_and_port.c_str());
  4179. req.headers.emplace("Accept", "*/*");
  4180. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4181. req.headers.emplace("Content-Type", "text/plain");
  4182. req.headers.emplace("Content-Length", "0");
  4183. req.headers.emplace(
  4184. "Transfer-Encoding",
  4185. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4186. // Client does not chunk, so make a chunked body manually.
  4187. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4188. auto res = std::make_shared<Response>();
  4189. auto error = Error::Success;
  4190. auto ret = cli_.send(req, *res, error);
  4191. ASSERT_TRUE(ret);
  4192. EXPECT_EQ(StatusCode::OK_200, res->status);
  4193. }
  4194. TEST_F(ServerTest, GetStreamed2) {
  4195. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4196. ASSERT_TRUE(res);
  4197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4198. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4199. EXPECT_EQ(true, res->has_header("Content-Range"));
  4200. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4201. EXPECT_EQ(std::string("ab"), res->body);
  4202. }
  4203. TEST_F(ServerTest, GetStreamed) {
  4204. auto res = cli_.Get("/streamed");
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4208. EXPECT_EQ(std::string("aaabbb"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedWithRange1) {
  4211. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4214. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4215. EXPECT_EQ(true, res->has_header("Content-Range"));
  4216. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4217. EXPECT_EQ(std::string("def"), res->body);
  4218. }
  4219. TEST_F(ServerTest, GetStreamedWithRange2) {
  4220. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4221. ASSERT_TRUE(res);
  4222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4223. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4224. EXPECT_EQ(true, res->has_header("Content-Range"));
  4225. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4226. EXPECT_EQ(std::string("bcdefg"), res->body);
  4227. }
  4228. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4229. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4233. EXPECT_EQ(true, res->has_header("Content-Range"));
  4234. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4235. EXPECT_EQ(std::string("efg"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4238. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4241. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(false, res->has_header("Content-Range"));
  4243. EXPECT_EQ(0U, res->body.size());
  4244. }
  4245. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4246. auto res = cli_.Get("/streamed-with-range",
  4247. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4248. "92233720368547758079223372036854775807"}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4251. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4252. EXPECT_EQ(false, res->has_header("Content-Range"));
  4253. EXPECT_EQ(0U, res->body.size());
  4254. }
  4255. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4256. auto res = cli_.Get(
  4257. "/with-range",
  4258. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4259. {"Accept-Encoding", ""}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4262. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(true, res->has_header("Content-Range"));
  4264. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4265. EXPECT_EQ(std::string("abcdefg"), res->body);
  4266. }
  4267. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4268. auto res = cli_.Get("/with-range", {
  4269. {"Range", "bytes=0-"},
  4270. {"Accept-Encoding", ""},
  4271. });
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4274. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4275. EXPECT_EQ(true, res->has_header("Content-Range"));
  4276. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4277. EXPECT_EQ(std::string("abcdefg"), res->body);
  4278. }
  4279. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4280. auto res =
  4281. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4284. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4285. EXPECT_EQ(false, res->has_header("Content-Range"));
  4286. EXPECT_EQ(267U, res->body.size());
  4287. // Check that both range contents are present
  4288. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4289. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4290. // Check that Content-Range headers are present for both ranges
  4291. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4292. std::string::npos);
  4293. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4294. std::string::npos);
  4295. }
  4296. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4297. Ranges ranges;
  4298. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4299. ranges.emplace_back(0, -1);
  4300. }
  4301. auto res =
  4302. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4305. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(false, res->has_header("Content-Range"));
  4307. EXPECT_EQ(0U, res->body.size());
  4308. }
  4309. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4310. auto res =
  4311. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4314. EXPECT_EQ(5U, res->body.size());
  4315. // Check that overlapping ranges are coalesced into a single range
  4316. EXPECT_EQ("bcdef", res->body);
  4317. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4318. // Should be single range, not multipart
  4319. EXPECT_TRUE(res->has_header("Content-Range"));
  4320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4321. }
  4322. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4323. auto res =
  4324. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4327. EXPECT_EQ(268U, res->body.size());
  4328. // Check that both range contents are present
  4329. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4330. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4331. // Check that Content-Range headers are present for both ranges
  4332. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4333. std::string::npos);
  4334. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4335. std::string::npos);
  4336. }
  4337. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4338. auto res =
  4339. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4342. EXPECT_EQ(269U, res->body.size());
  4343. // Check that both duplicate range contents are present
  4344. size_t first_abc = res->body.find("abc\r\n");
  4345. EXPECT_TRUE(first_abc != std::string::npos);
  4346. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4347. EXPECT_TRUE(second_abc != std::string::npos);
  4348. // Check that Content-Range headers are present for both ranges
  4349. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4350. EXPECT_TRUE(first_range != std::string::npos);
  4351. size_t second_range =
  4352. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4353. EXPECT_TRUE(second_range != std::string::npos);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4356. auto res = cli_.Get("/streamed-with-range?error",
  4357. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4358. ASSERT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4360. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4361. EXPECT_EQ(false, res->has_header("Content-Range"));
  4362. EXPECT_EQ(0U, res->body.size());
  4363. }
  4364. TEST_F(ServerTest, GetStreamedEndless) {
  4365. uint64_t offset = 0;
  4366. auto res = cli_.Get("/streamed-cancel",
  4367. [&](const char * /*data*/, uint64_t data_length) {
  4368. if (offset < 100) {
  4369. offset += data_length;
  4370. return true;
  4371. }
  4372. return false;
  4373. });
  4374. ASSERT_TRUE(!res);
  4375. EXPECT_EQ(Error::Canceled, res.error());
  4376. }
  4377. TEST_F(ServerTest, ClientStop) {
  4378. std::atomic_size_t count{4};
  4379. std::vector<std::thread> threads;
  4380. for (auto i = count.load(); i != 0; --i) {
  4381. threads.emplace_back([&]() {
  4382. auto res = cli_.Get("/streamed-cancel",
  4383. [&](const char *, uint64_t) { return true; });
  4384. --count;
  4385. ASSERT_TRUE(!res);
  4386. EXPECT_TRUE(res.error() == Error::Canceled ||
  4387. res.error() == Error::Read || res.error() == Error::Write);
  4388. });
  4389. }
  4390. std::this_thread::sleep_for(std::chrono::seconds(2));
  4391. while (count != 0) {
  4392. cli_.stop();
  4393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4394. }
  4395. for (auto &t : threads) {
  4396. t.join();
  4397. }
  4398. }
  4399. TEST_F(ServerTest, GetWithRange1) {
  4400. auto res = cli_.Get("/with-range", {
  4401. make_range_header({{3, 5}}),
  4402. {"Accept-Encoding", ""},
  4403. });
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4406. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4407. EXPECT_EQ(true, res->has_header("Content-Range"));
  4408. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4409. EXPECT_EQ(std::string("def"), res->body);
  4410. }
  4411. TEST_F(ServerTest, GetWithRange2) {
  4412. auto res = cli_.Get("/with-range", {
  4413. make_range_header({{1, -1}}),
  4414. {"Accept-Encoding", ""},
  4415. });
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4419. EXPECT_EQ(true, res->has_header("Content-Range"));
  4420. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4421. EXPECT_EQ(std::string("bcdefg"), res->body);
  4422. }
  4423. TEST_F(ServerTest, GetWithRange3) {
  4424. auto res = cli_.Get("/with-range", {
  4425. make_range_header({{0, 0}}),
  4426. {"Accept-Encoding", ""},
  4427. });
  4428. ASSERT_TRUE(res);
  4429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4430. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4431. EXPECT_EQ(true, res->has_header("Content-Range"));
  4432. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4433. EXPECT_EQ(std::string("a"), res->body);
  4434. }
  4435. TEST_F(ServerTest, GetWithRange4) {
  4436. auto res = cli_.Get("/with-range", {
  4437. make_range_header({{-1, 2}}),
  4438. {"Accept-Encoding", ""},
  4439. });
  4440. ASSERT_TRUE(res);
  4441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4443. EXPECT_EQ(true, res->has_header("Content-Range"));
  4444. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4445. EXPECT_EQ(std::string("fg"), res->body);
  4446. }
  4447. TEST_F(ServerTest, GetWithRange5) {
  4448. auto res = cli_.Get("/with-range", {
  4449. make_range_header({{0, 5}}),
  4450. {"Accept-Encoding", ""},
  4451. });
  4452. ASSERT_TRUE(res);
  4453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4454. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ(true, res->has_header("Content-Range"));
  4456. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4457. EXPECT_EQ(std::string("abcdef"), res->body);
  4458. }
  4459. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4460. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4463. }
  4464. TEST_F(ServerTest, GetWithRangeMultipart) {
  4465. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4468. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(267U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4473. auto res =
  4474. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4477. }
  4478. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4479. auto res = cli_.Get("/with-range-customized-response",
  4480. {{make_range_header({{1, 2}})}});
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4483. EXPECT_EQ(true, res->has_header("Content-Length"));
  4484. EXPECT_EQ(false, res->has_header("Content-Range"));
  4485. EXPECT_EQ(JSON_DATA, res->body);
  4486. }
  4487. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4488. auto res = cli_.Get("/with-range-customized-response",
  4489. {{make_range_header({{1, 2}, {4, 5}})}});
  4490. ASSERT_TRUE(res);
  4491. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4492. EXPECT_EQ(true, res->has_header("Content-Length"));
  4493. EXPECT_EQ(false, res->has_header("Content-Range"));
  4494. EXPECT_EQ(JSON_DATA, res->body);
  4495. }
  4496. TEST_F(ServerTest, Issue1772) {
  4497. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4498. ASSERT_TRUE(res);
  4499. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4500. }
  4501. TEST_F(ServerTest, Issue609) {
  4502. auto res = cli_.Delete("/issue609");
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ(std::string("ok"), res->body);
  4506. }
  4507. TEST_F(ServerTest, GetStreamedChunked) {
  4508. auto res = cli_.Get("/streamed-chunked");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ(std::string("123456789"), res->body);
  4512. }
  4513. TEST_F(ServerTest, GetStreamedChunked2) {
  4514. auto res = cli_.Get("/streamed-chunked2");
  4515. ASSERT_TRUE(res);
  4516. EXPECT_EQ(StatusCode::OK_200, res->status);
  4517. EXPECT_EQ(std::string("123456789"), res->body);
  4518. }
  4519. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4520. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(std::string("123456789"), res->body);
  4524. EXPECT_TRUE(res->has_header("Trailer"));
  4525. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4526. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4527. // Trailers are now stored separately from headers (security fix)
  4528. EXPECT_EQ(2U, res->trailers.size());
  4529. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4530. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4531. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4532. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4533. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4534. // Verify trailers are NOT in headers (security verification)
  4535. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4536. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4537. }
  4538. TEST_F(ServerTest, LargeChunkedPost) {
  4539. Request req;
  4540. req.method = "POST";
  4541. req.path = "/large-chunked";
  4542. std::string host_and_port;
  4543. host_and_port += HOST;
  4544. host_and_port += ":";
  4545. host_and_port += std::to_string(PORT);
  4546. req.headers.emplace("Host", host_and_port.c_str());
  4547. req.headers.emplace("Accept", "*/*");
  4548. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4549. req.headers.emplace("Content-Type", "text/plain");
  4550. req.headers.emplace("Content-Length", "0");
  4551. req.headers.emplace("Transfer-Encoding", "chunked");
  4552. std::string long_string(30 * 1024u, 'a');
  4553. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4554. // Attempt to make a large enough post to exceed OS buffers, to test that
  4555. // the server handles short reads if the full chunk data isn't available.
  4556. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4557. auto res = std::make_shared<Response>();
  4558. auto error = Error::Success;
  4559. auto ret = cli_.send(req, *res, error);
  4560. ASSERT_TRUE(ret);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4564. auto res = cli_.Get("/remote_addr");
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4568. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4569. }
  4570. TEST_F(ServerTest, GetMethodLocalAddr) {
  4571. auto res = cli_.Get("/local_addr");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4575. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4576. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4577. }
  4578. TEST_F(ServerTest, HTTPResponseSplitting) {
  4579. auto res = cli_.Get("/http_response_splitting");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, SlowRequest) {
  4584. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4585. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4587. }
  4588. #if 0
  4589. TEST_F(ServerTest, SlowPost) {
  4590. char buffer[64 * 1024];
  4591. memset(buffer, 0x42, sizeof(buffer));
  4592. auto res = cli_.Post(
  4593. "/slowpost", 64 * 1024 * 1024,
  4594. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4595. auto ret = sink.write(buffer, sizeof(buffer));
  4596. EXPECT_TRUE(ret);
  4597. return true;
  4598. },
  4599. "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. TEST_F(ServerTest, SlowPostFail) {
  4604. char buffer[64 * 1024];
  4605. memset(buffer, 0x42, sizeof(buffer));
  4606. cli_.set_write_timeout(std::chrono::seconds(0));
  4607. auto res = cli_.Post(
  4608. "/slowpost", 64 * 1024 * 1024,
  4609. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4610. sink.write(buffer, sizeof(buffer));
  4611. return true;
  4612. },
  4613. "text/plain");
  4614. ASSERT_TRUE(!res);
  4615. EXPECT_EQ(Error::Write, res.error());
  4616. }
  4617. #endif
  4618. TEST_F(ServerTest, Put) {
  4619. auto res = cli_.Put("/put", "PUT", "text/plain");
  4620. ASSERT_TRUE(res);
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("PUT", res->body);
  4623. }
  4624. TEST_F(ServerTest, PutWithContentProvider) {
  4625. auto res = cli_.Put(
  4626. "/put", 3,
  4627. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4628. sink.os << "PUT";
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("PUT", res->body);
  4635. }
  4636. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4637. auto res = cli_.Post(
  4638. "/post", 42,
  4639. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4640. return false;
  4641. },
  4642. "text/plain");
  4643. ASSERT_TRUE(!res);
  4644. EXPECT_EQ(Error::Canceled, res.error());
  4645. }
  4646. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4647. auto res = cli_.Put(
  4648. "/put",
  4649. [](size_t /*offset*/, DataSink &sink) {
  4650. sink.os << "PUT";
  4651. sink.done();
  4652. return true;
  4653. },
  4654. "text/plain");
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("PUT", res->body);
  4658. }
  4659. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4660. auto res = cli_.Post(
  4661. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4662. "text/plain");
  4663. ASSERT_TRUE(!res);
  4664. EXPECT_EQ(Error::Canceled, res.error());
  4665. }
  4666. TEST_F(ServerTest, PostLoopBack) {
  4667. std::string body;
  4668. auto res = cli_.Post(
  4669. "/post-loopback", 9,
  4670. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4671. EXPECT_EQ(9u, length);
  4672. sink.write("123", 3);
  4673. sink.write("456", 3);
  4674. sink.write("789", 3);
  4675. return true;
  4676. },
  4677. "text/plain",
  4678. [&body](const char *data, size_t data_length) {
  4679. body.append(data, data_length);
  4680. return true;
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("123456789", body);
  4685. }
  4686. TEST_F(ServerTest, PutLoopBack) {
  4687. std::string body;
  4688. auto res = cli_.Put(
  4689. "/put-loopback", 9,
  4690. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4691. EXPECT_EQ(9u, length);
  4692. sink.write("123", 3);
  4693. sink.write("456", 3);
  4694. sink.write("789", 3);
  4695. return true;
  4696. },
  4697. "text/plain",
  4698. [&body](const char *data, size_t data_length) {
  4699. body.append(data, data_length);
  4700. return true;
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("123456789", body);
  4705. }
  4706. TEST_F(ServerTest, PatchLoopBack) {
  4707. std::string body;
  4708. auto res = cli_.Patch(
  4709. "/patch-loopback", 9,
  4710. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4711. EXPECT_EQ(9u, length);
  4712. sink.write("123", 3);
  4713. sink.write("456", 3);
  4714. sink.write("789", 3);
  4715. return true;
  4716. },
  4717. "text/plain",
  4718. [&body](const char *data, size_t data_length) {
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("123456789", body);
  4725. }
  4726. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4727. std::string body;
  4728. auto res = cli_.Post(
  4729. "/post-loopback",
  4730. [](size_t /*offset*/, DataSink &sink) {
  4731. sink.write("123", 3);
  4732. sink.write("456", 3);
  4733. sink.write("789", 3);
  4734. sink.done();
  4735. return true;
  4736. },
  4737. "text/plain",
  4738. [&body](const char *data, size_t data_length) {
  4739. body.append(data, data_length);
  4740. return true;
  4741. });
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ("123456789", body);
  4745. }
  4746. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4747. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4748. cli_.set_compress(true);
  4749. auto res = cli_.Put(
  4750. "/put", 3,
  4751. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4752. sink.os << "PUT";
  4753. return true;
  4754. },
  4755. "text/plain");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("PUT", res->body);
  4759. }
  4760. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4761. cli_.set_compress(true);
  4762. auto res = cli_.Post(
  4763. "/post", 42,
  4764. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4765. return false;
  4766. },
  4767. "text/plain");
  4768. ASSERT_TRUE(!res);
  4769. EXPECT_EQ(Error::Canceled, res.error());
  4770. }
  4771. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4772. cli_.set_compress(true);
  4773. auto res = cli_.Put(
  4774. "/put",
  4775. [](size_t /*offset*/, DataSink &sink) {
  4776. sink.os << "PUT";
  4777. sink.done();
  4778. return true;
  4779. },
  4780. "text/plain");
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ("PUT", res->body);
  4784. }
  4785. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4786. cli_.set_compress(true);
  4787. auto res = cli_.Post(
  4788. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4789. "text/plain");
  4790. ASSERT_TRUE(!res);
  4791. EXPECT_EQ(Error::Canceled, res.error());
  4792. }
  4793. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4794. cli_.set_compress(true);
  4795. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. EXPECT_EQ(LARGE_DATA, res->body);
  4799. }
  4800. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4801. #ifdef CPPHTTPLIB_SSL_ENABLED
  4802. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4803. Client cli(s.c_str());
  4804. cli.enable_server_certificate_verification(false);
  4805. #else
  4806. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4807. Client cli(s.c_str());
  4808. #endif
  4809. cli.set_compress(true);
  4810. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::OK_200, res->status);
  4813. EXPECT_EQ(LARGE_DATA, res->body);
  4814. // The compressed size should be less than a 10th of the original. May vary
  4815. // depending on the zlib library.
  4816. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4817. static_cast<uint64_t>(10 * 1024 * 1024));
  4818. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4819. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4820. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4821. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4822. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4823. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4824. #endif
  4825. }
  4826. TEST_F(ServerTest, PutContentWithDeflate) {
  4827. cli_.set_compress(false);
  4828. Headers headers;
  4829. headers.emplace("Content-Encoding", "deflate");
  4830. // PUT in deflate format:
  4831. auto res = cli_.Put("/put", headers,
  4832. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. EXPECT_EQ("PUT", res->body);
  4836. }
  4837. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4838. Headers headers;
  4839. headers.emplace("Accept-Encoding", "gzip, deflate");
  4840. auto res = cli_.Get("/streamed-chunked", headers);
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ(std::string("123456789"), res->body);
  4844. }
  4845. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4846. Headers headers;
  4847. headers.emplace("Accept-Encoding", "gzip, deflate");
  4848. auto res = cli_.Get("/streamed-chunked2", headers);
  4849. ASSERT_TRUE(res);
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ(std::string("123456789"), res->body);
  4852. }
  4853. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4854. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. }
  4858. TEST(GzipDecompressor, ChunkedDecompression) {
  4859. std::string data;
  4860. for (size_t i = 0; i < 32 * 1024; ++i) {
  4861. data.push_back(static_cast<char>('a' + i % 26));
  4862. }
  4863. std::string compressed_data;
  4864. {
  4865. httplib::detail::gzip_compressor compressor;
  4866. bool result = compressor.compress(
  4867. data.data(), data.size(),
  4868. /*last=*/true,
  4869. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4870. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4871. compressed_data_size);
  4872. return true;
  4873. });
  4874. ASSERT_TRUE(result);
  4875. }
  4876. std::string decompressed_data;
  4877. {
  4878. httplib::detail::gzip_decompressor decompressor;
  4879. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4880. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4881. size_t chunk_size = 130;
  4882. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4883. chunk_begin += chunk_size) {
  4884. size_t current_chunk_size =
  4885. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4886. bool result = decompressor.decompress(
  4887. compressed_data.data() + chunk_begin, current_chunk_size,
  4888. [&](const char *decompressed_data_chunk,
  4889. size_t decompressed_data_chunk_size) {
  4890. decompressed_data.insert(decompressed_data.size(),
  4891. decompressed_data_chunk,
  4892. decompressed_data_chunk_size);
  4893. return true;
  4894. });
  4895. ASSERT_TRUE(result);
  4896. }
  4897. }
  4898. ASSERT_EQ(data, decompressed_data);
  4899. }
  4900. TEST(GzipDecompressor, DeflateDecompression) {
  4901. std::string original_text = "Raw deflate without gzip";
  4902. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4903. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4904. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4905. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4906. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4907. std::string decompressed_data;
  4908. {
  4909. httplib::detail::gzip_decompressor decompressor;
  4910. bool result = decompressor.decompress(
  4911. compressed_data.data(), compressed_data.size(),
  4912. [&](const char *decompressed_data_chunk,
  4913. size_t decompressed_data_chunk_size) {
  4914. decompressed_data.insert(decompressed_data.size(),
  4915. decompressed_data_chunk,
  4916. decompressed_data_chunk_size);
  4917. return true;
  4918. });
  4919. ASSERT_TRUE(result);
  4920. }
  4921. ASSERT_EQ(original_text, decompressed_data);
  4922. }
  4923. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4924. std::string original_text = "Raw deflate without gzip";
  4925. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4926. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4927. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4928. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4929. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4930. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4931. std::string decompressed_data;
  4932. {
  4933. httplib::detail::gzip_decompressor decompressor;
  4934. bool result = decompressor.decompress(
  4935. compressed_data.data(), compressed_data.size(),
  4936. [&](const char *decompressed_data_chunk,
  4937. size_t decompressed_data_chunk_size) {
  4938. decompressed_data.insert(decompressed_data.size(),
  4939. decompressed_data_chunk,
  4940. decompressed_data_chunk_size);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(result);
  4944. }
  4945. ASSERT_EQ(original_text, decompressed_data);
  4946. }
  4947. #endif
  4948. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4949. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4950. Headers headers;
  4951. headers.emplace("Accept-Encoding", "br");
  4952. auto res = cli_.Get("/streamed-chunked", headers);
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ(std::string("123456789"), res->body);
  4956. }
  4957. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "br");
  4960. auto res = cli_.Get("/streamed-chunked2", headers);
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. EXPECT_EQ(std::string("123456789"), res->body);
  4964. }
  4965. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4966. cli_.set_compress(true);
  4967. auto res = cli_.Put(
  4968. "/put", 3,
  4969. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4970. sink.os << "PUT";
  4971. return true;
  4972. },
  4973. "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("PUT", res->body);
  4977. }
  4978. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4979. cli_.set_compress(true);
  4980. auto res = cli_.Put(
  4981. "/put",
  4982. [](size_t /*offset*/, DataSink &sink) {
  4983. sink.os << "PUT";
  4984. sink.done();
  4985. return true;
  4986. },
  4987. "text/plain");
  4988. ASSERT_TRUE(res);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. EXPECT_EQ("PUT", res->body);
  4991. }
  4992. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4993. cli_.set_compress(true);
  4994. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ(LARGE_DATA, res->body);
  4998. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4999. }
  5000. #endif
  5001. TEST_F(ServerTest, Patch) {
  5002. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5003. ASSERT_TRUE(res);
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. EXPECT_EQ("PATCH", res->body);
  5006. }
  5007. TEST_F(ServerTest, Delete) {
  5008. auto res = cli_.Delete("/delete");
  5009. ASSERT_TRUE(res);
  5010. EXPECT_EQ(StatusCode::OK_200, res->status);
  5011. EXPECT_EQ("DELETE", res->body);
  5012. }
  5013. TEST_F(ServerTest, DeleteContentReceiver) {
  5014. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5015. ASSERT_TRUE(res);
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. EXPECT_EQ("content", res->body);
  5018. }
  5019. TEST_F(ServerTest, Options) {
  5020. auto res = cli_.Options("*");
  5021. ASSERT_TRUE(res);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5024. EXPECT_TRUE(res->body.empty());
  5025. }
  5026. TEST_F(ServerTest, URL) {
  5027. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5028. ASSERT_TRUE(res);
  5029. EXPECT_EQ(StatusCode::OK_200, res->status);
  5030. }
  5031. TEST_F(ServerTest, ArrayParam) {
  5032. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. }
  5036. TEST_F(ServerTest, NoMultipleHeaders) {
  5037. Headers headers = {{"Content-Length", "5"}};
  5038. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5039. "text/plain");
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. }
  5043. TEST_F(ServerTest, PostContentReceiver) {
  5044. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5045. ASSERT_TRUE(res);
  5046. ASSERT_EQ(StatusCode::OK_200, res->status);
  5047. ASSERT_EQ("content", res->body);
  5048. }
  5049. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5050. UploadFormDataItems items = {
  5051. {"text1", "text default", "", ""},
  5052. {"text2", "aωb", "", ""},
  5053. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5054. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5055. {"file3", "", "", "application/octet-stream"},
  5056. };
  5057. auto res = cli_.Post("/content_receiver", items);
  5058. ASSERT_TRUE(res);
  5059. EXPECT_EQ(StatusCode::OK_200, res->status);
  5060. }
  5061. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5062. UploadFormDataItems items = {
  5063. {"text1", "text default", "", ""},
  5064. {"text2", "aωb", "", ""},
  5065. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5066. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5067. {"file3", "", "", "application/octet-stream"},
  5068. };
  5069. auto boundary = std::string("+++++");
  5070. std::string body;
  5071. for (const auto &item : items) {
  5072. body += "--" + boundary + "\r\n";
  5073. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5074. if (!item.filename.empty()) {
  5075. body += "; filename=\"" + item.filename + "\"";
  5076. }
  5077. body += "\r\n";
  5078. if (!item.content_type.empty()) {
  5079. body += "Content-Type: " + item.content_type + "\r\n";
  5080. }
  5081. body += "\r\n";
  5082. body += item.content + "\r\n";
  5083. }
  5084. body += "--" + boundary + "--\r\n";
  5085. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5086. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5087. ASSERT_TRUE(res);
  5088. EXPECT_EQ(StatusCode::OK_200, res->status);
  5089. }
  5090. TEST_F(ServerTest, PostContentReceiverGzip) {
  5091. cli_.set_compress(true);
  5092. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5093. ASSERT_TRUE(res);
  5094. ASSERT_EQ(StatusCode::OK_200, res->status);
  5095. ASSERT_EQ("content", res->body);
  5096. }
  5097. TEST_F(ServerTest, PutContentReceiver) {
  5098. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5099. ASSERT_TRUE(res);
  5100. ASSERT_EQ(StatusCode::OK_200, res->status);
  5101. ASSERT_EQ("content", res->body);
  5102. }
  5103. TEST_F(ServerTest, PatchContentReceiver) {
  5104. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5105. ASSERT_TRUE(res);
  5106. ASSERT_EQ(StatusCode::OK_200, res->status);
  5107. ASSERT_EQ("content", res->body);
  5108. }
  5109. template <typename ClientType>
  5110. void TestWithHeadersAndContentReceiver(
  5111. ClientType &cli,
  5112. std::function<Result(ClientType &, const std::string &, const Headers &,
  5113. const std::string &, const std::string &,
  5114. ContentReceiver, DownloadProgress)>
  5115. request_func) {
  5116. Headers headers;
  5117. headers.emplace("X-Custom-Header", "test-value");
  5118. std::string received_body;
  5119. auto res = request_func(
  5120. cli, "/content_receiver", headers, "content", "application/json",
  5121. [&](const char *data, size_t data_length) {
  5122. received_body.append(data, data_length);
  5123. return true;
  5124. },
  5125. nullptr);
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. EXPECT_EQ("content", received_body);
  5129. }
  5130. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5131. #ifdef CPPHTTPLIB_SSL_ENABLED
  5132. using ClientT = SSLClient;
  5133. #else
  5134. using ClientT = Client;
  5135. #endif
  5136. TestWithHeadersAndContentReceiver<ClientT>(
  5137. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5138. const std::string &body, const std::string &content_type,
  5139. ContentReceiver receiver, DownloadProgress progress) {
  5140. return cli.Post(path, headers, body, content_type, receiver, progress);
  5141. });
  5142. }
  5143. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5144. #ifdef CPPHTTPLIB_SSL_ENABLED
  5145. using ClientT = SSLClient;
  5146. #else
  5147. using ClientT = Client;
  5148. #endif
  5149. TestWithHeadersAndContentReceiver<ClientT>(
  5150. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5151. const std::string &body, const std::string &content_type,
  5152. ContentReceiver receiver, DownloadProgress progress) {
  5153. return cli.Put(path, headers, body, content_type, receiver, progress);
  5154. });
  5155. }
  5156. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5157. #ifdef CPPHTTPLIB_SSL_ENABLED
  5158. using ClientT = SSLClient;
  5159. #else
  5160. using ClientT = Client;
  5161. #endif
  5162. TestWithHeadersAndContentReceiver<ClientT>(
  5163. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5164. const std::string &body, const std::string &content_type,
  5165. ContentReceiver receiver, DownloadProgress progress) {
  5166. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5167. });
  5168. }
  5169. template <typename ClientType>
  5170. void TestWithHeadersAndContentReceiverWithProgress(
  5171. ClientType &cli,
  5172. std::function<Result(ClientType &, const std::string &, const Headers &,
  5173. const std::string &, const std::string &,
  5174. ContentReceiver, DownloadProgress)>
  5175. request_func) {
  5176. Headers headers;
  5177. headers.emplace("X-Test-Header", "progress-test");
  5178. std::string received_body;
  5179. auto progress_called = false;
  5180. auto res = request_func(
  5181. cli, "/content_receiver", headers, "content", "text/plain",
  5182. [&](const char *data, size_t data_length) {
  5183. received_body.append(data, data_length);
  5184. return true;
  5185. },
  5186. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5187. progress_called = true;
  5188. return true;
  5189. });
  5190. ASSERT_TRUE(res);
  5191. EXPECT_EQ(StatusCode::OK_200, res->status);
  5192. EXPECT_EQ("content", received_body);
  5193. EXPECT_TRUE(progress_called);
  5194. }
  5195. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5196. #ifdef CPPHTTPLIB_SSL_ENABLED
  5197. using ClientT = SSLClient;
  5198. #else
  5199. using ClientT = Client;
  5200. #endif
  5201. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5202. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5203. const std::string &body, const std::string &content_type,
  5204. ContentReceiver receiver, DownloadProgress progress) {
  5205. return cli.Post(path, headers, body, content_type, receiver, progress);
  5206. });
  5207. }
  5208. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5209. #ifdef CPPHTTPLIB_SSL_ENABLED
  5210. using ClientT = SSLClient;
  5211. #else
  5212. using ClientT = Client;
  5213. #endif
  5214. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5215. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5216. const std::string &body, const std::string &content_type,
  5217. ContentReceiver receiver, DownloadProgress progress) {
  5218. return cli.Put(path, headers, body, content_type, receiver, progress);
  5219. });
  5220. }
  5221. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5222. #ifdef CPPHTTPLIB_SSL_ENABLED
  5223. using ClientT = SSLClient;
  5224. #else
  5225. using ClientT = Client;
  5226. #endif
  5227. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5228. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5229. const std::string &body, const std::string &content_type,
  5230. ContentReceiver receiver, DownloadProgress progress) {
  5231. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5232. });
  5233. }
  5234. template <typename ClientType>
  5235. void TestWithHeadersAndContentReceiverError(
  5236. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5237. const Headers &, const std::string &,
  5238. const std::string &, ContentReceiver)>
  5239. request_func) {
  5240. Headers headers;
  5241. headers.emplace("X-Error-Test", "true");
  5242. std::string received_body;
  5243. auto receiver_failed = false;
  5244. auto res =
  5245. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5246. [&](const char *data, size_t data_length) {
  5247. received_body.append(data, data_length);
  5248. receiver_failed = true;
  5249. return false;
  5250. });
  5251. ASSERT_FALSE(res);
  5252. EXPECT_TRUE(receiver_failed);
  5253. }
  5254. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5255. #ifdef CPPHTTPLIB_SSL_ENABLED
  5256. using ClientT = SSLClient;
  5257. #else
  5258. using ClientT = Client;
  5259. #endif
  5260. TestWithHeadersAndContentReceiverError<ClientT>(
  5261. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5262. const std::string &body, const std::string &content_type,
  5263. ContentReceiver receiver) {
  5264. return cli.Post(path, headers, body, content_type, receiver);
  5265. });
  5266. }
  5267. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5268. #ifdef CPPHTTPLIB_SSL_ENABLED
  5269. using ClientT = SSLClient;
  5270. #else
  5271. using ClientT = Client;
  5272. #endif
  5273. TestWithHeadersAndContentReceiverError<ClientT>(
  5274. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5275. const std::string &body, const std::string &content_type,
  5276. ContentReceiver receiver) {
  5277. return cli.Put(path, headers, body, content_type, receiver);
  5278. });
  5279. }
  5280. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5281. #ifdef CPPHTTPLIB_SSL_ENABLED
  5282. using ClientT = SSLClient;
  5283. #else
  5284. using ClientT = Client;
  5285. #endif
  5286. TestWithHeadersAndContentReceiverError<ClientT>(
  5287. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5288. const std::string &body, const std::string &content_type,
  5289. ContentReceiver receiver) {
  5290. return cli.Patch(path, headers, body, content_type, receiver);
  5291. });
  5292. }
  5293. TEST_F(ServerTest, PostQueryStringAndBody) {
  5294. auto res =
  5295. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5296. ASSERT_TRUE(res);
  5297. ASSERT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, HTTP2Magic) {
  5300. Request req;
  5301. req.method = "PRI";
  5302. req.path = "*";
  5303. req.body = "SM";
  5304. auto res = std::make_shared<Response>();
  5305. auto error = Error::Success;
  5306. auto ret = cli_.send(req, *res, error);
  5307. ASSERT_TRUE(ret);
  5308. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5309. }
  5310. TEST_F(ServerTest, KeepAlive) {
  5311. auto res = cli_.Get("/hi");
  5312. ASSERT_TRUE(res);
  5313. EXPECT_EQ(StatusCode::OK_200, res->status);
  5314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5315. EXPECT_EQ("Hello World!", res->body);
  5316. res = cli_.Get("/hi");
  5317. ASSERT_TRUE(res);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5320. EXPECT_EQ("Hello World!", res->body);
  5321. res = cli_.Get("/hi");
  5322. ASSERT_TRUE(res);
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5325. EXPECT_EQ("Hello World!", res->body);
  5326. res = cli_.Get("/not-exist");
  5327. ASSERT_TRUE(res);
  5328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5329. res = cli_.Post("/empty", "", "text/plain");
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. EXPECT_EQ("empty", res->body);
  5334. EXPECT_EQ("close", res->get_header_value("Connection"));
  5335. res = cli_.Post(
  5336. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5337. "text/plain");
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::OK_200, res->status);
  5340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. EXPECT_EQ("empty", res->body);
  5342. cli_.set_keep_alive(false);
  5343. res = cli_.Get("/last-request");
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ("close", res->get_header_value("Connection"));
  5347. }
  5348. TEST_F(ServerTest, TooManyRedirect) {
  5349. cli_.set_follow_location(true);
  5350. auto res = cli_.Get("/redirect/0");
  5351. ASSERT_TRUE(!res);
  5352. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5353. }
  5354. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5355. Request req;
  5356. req.method = "FOOBAR";
  5357. req.path = "/hi";
  5358. cli_.set_keep_alive(true);
  5359. auto res = cli_.send(req);
  5360. ASSERT_TRUE(res);
  5361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5362. EXPECT_EQ("close", res->get_header_value("Connection"));
  5363. EXPECT_FALSE(cli_.is_socket_open());
  5364. }
  5365. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5366. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5367. TEST_F(ServerTest, Gzip) {
  5368. Headers headers;
  5369. headers.emplace("Accept-Encoding", "gzip, deflate");
  5370. auto res = cli_.Get("/compress", headers);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5374. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5376. "7890123456789012345678901234567890",
  5377. res->body);
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. }
  5380. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5381. Headers headers;
  5382. headers.emplace("Accept-Encoding", "gzip, deflate");
  5383. auto res = cli_.Get("/compress-with-charset", headers);
  5384. ASSERT_TRUE(res);
  5385. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5386. EXPECT_EQ("application/json; charset=utf-8",
  5387. res->get_header_value("Content-Type"));
  5388. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5389. "7890123456789012345678901234567890",
  5390. res->body);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5394. Headers headers;
  5395. headers.emplace("Accept-Encoding", "");
  5396. auto res = cli_.Get("/compress", headers);
  5397. ASSERT_TRUE(res);
  5398. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5400. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5402. "7890123456789012345678901234567890",
  5403. res->body);
  5404. EXPECT_EQ(StatusCode::OK_200, res->status);
  5405. }
  5406. TEST_F(ServerTest, GzipWithContentReceiver) {
  5407. Headers headers;
  5408. headers.emplace("Accept-Encoding", "gzip, deflate");
  5409. std::string body;
  5410. auto res = cli_.Get("/compress", headers,
  5411. [&](const char *data, uint64_t data_length) {
  5412. EXPECT_EQ(100U, data_length);
  5413. body.append(data, data_length);
  5414. return true;
  5415. });
  5416. ASSERT_TRUE(res);
  5417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5421. "7890123456789012345678901234567890",
  5422. body);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. }
  5425. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5426. Headers headers;
  5427. headers.emplace("Accept-Encoding", "gzip, deflate");
  5428. cli_.set_decompress(false);
  5429. auto res = cli_.Get("/compress", headers);
  5430. ASSERT_TRUE(res);
  5431. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5432. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5434. EXPECT_EQ(33U, res->body.size());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. }
  5437. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5438. Headers headers;
  5439. headers.emplace("Accept-Encoding", "");
  5440. std::string body;
  5441. auto res = cli_.Get("/compress", headers,
  5442. [&](const char *data, uint64_t data_length) {
  5443. EXPECT_EQ(100U, data_length);
  5444. body.append(data, data_length);
  5445. return true;
  5446. });
  5447. ASSERT_TRUE(res);
  5448. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5450. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5452. "7890123456789012345678901234567890",
  5453. body);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. }
  5456. TEST_F(ServerTest, NoGzip) {
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "gzip, deflate");
  5459. auto res = cli_.Get("/nocompress", headers);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5462. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5463. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5464. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5465. "7890123456789012345678901234567890",
  5466. res->body);
  5467. EXPECT_EQ(StatusCode::OK_200, res->status);
  5468. }
  5469. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5470. Headers headers;
  5471. headers.emplace("Accept-Encoding", "gzip, deflate");
  5472. std::string body;
  5473. auto res = cli_.Get("/nocompress", headers,
  5474. [&](const char *data, uint64_t data_length) {
  5475. EXPECT_EQ(100U, data_length);
  5476. body.append(data, data_length);
  5477. return true;
  5478. });
  5479. ASSERT_TRUE(res);
  5480. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5481. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5484. "7890123456789012345678901234567890",
  5485. body);
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. }
  5488. TEST_F(ServerTest, MultipartFormDataGzip) {
  5489. UploadFormDataItems items = {
  5490. {"key1", "test", "", ""},
  5491. {"key2", "--abcdefg123", "", ""},
  5492. };
  5493. cli_.set_compress(true);
  5494. auto res = cli_.Post("/compress-multipart", items);
  5495. ASSERT_TRUE(res);
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. }
  5498. #endif
  5499. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5500. TEST_F(ServerTest, Brotli) {
  5501. Headers headers;
  5502. headers.emplace("Accept-Encoding", "br");
  5503. auto res = cli_.Get("/compress", headers);
  5504. ASSERT_TRUE(res);
  5505. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5507. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5509. "7890123456789012345678901234567890",
  5510. res->body);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. }
  5513. #endif
  5514. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5515. TEST_F(ServerTest, Zstd) {
  5516. Headers headers;
  5517. headers.emplace("Accept-Encoding", "zstd");
  5518. auto res = cli_.Get("/compress", headers);
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5522. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5523. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5524. "7890123456789012345678901234567890",
  5525. res->body);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "");
  5531. auto res = cli_.Get("/compress", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5535. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5536. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5537. "7890123456789012345678901234567890",
  5538. res->body);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. }
  5541. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5542. Headers headers;
  5543. headers.emplace("Accept-Encoding", "zstd");
  5544. std::string body;
  5545. auto res = cli_.Get("/compress", headers,
  5546. [&](const char *data, uint64_t data_length) {
  5547. EXPECT_EQ(100U, data_length);
  5548. body.append(data, data_length);
  5549. return true;
  5550. });
  5551. ASSERT_TRUE(res);
  5552. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5556. "7890123456789012345678901234567890",
  5557. body);
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. }
  5560. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5561. Headers headers;
  5562. headers.emplace("Accept-Encoding", "zstd");
  5563. cli_.set_decompress(false);
  5564. auto res = cli_.Get("/compress", headers);
  5565. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5566. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5567. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5568. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5569. ASSERT_TRUE(res);
  5570. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5571. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5572. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. ASSERT_EQ(26U, res->body.size());
  5575. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5576. 0);
  5577. }
  5578. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5579. Headers headers;
  5580. headers.emplace("Accept-Encoding", "");
  5581. std::string body;
  5582. auto res = cli_.Get("/compress", headers,
  5583. [&](const char *data, uint64_t data_length) {
  5584. EXPECT_EQ(100U, data_length);
  5585. body.append(data, data_length);
  5586. return true;
  5587. });
  5588. ASSERT_TRUE(res);
  5589. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5592. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5593. "7890123456789012345678901234567890",
  5594. body);
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. }
  5597. TEST_F(ServerTest, NoZstd) {
  5598. Headers headers;
  5599. headers.emplace("Accept-Encoding", "zstd");
  5600. auto res = cli_.Get("/nocompress", headers);
  5601. ASSERT_TRUE(res);
  5602. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5603. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5604. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5605. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5606. "7890123456789012345678901234567890",
  5607. res->body);
  5608. EXPECT_EQ(StatusCode::OK_200, res->status);
  5609. }
  5610. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5611. Headers headers;
  5612. headers.emplace("Accept-Encoding", "zstd");
  5613. std::string body;
  5614. auto res = cli_.Get("/nocompress", headers,
  5615. [&](const char *data, uint64_t data_length) {
  5616. EXPECT_EQ(100U, data_length);
  5617. body.append(data, data_length);
  5618. return true;
  5619. });
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5622. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5625. "7890123456789012345678901234567890",
  5626. body);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. // TODO: How to enable zstd ??
  5630. TEST_F(ServerTest, MultipartFormDataZstd) {
  5631. UploadFormDataItems items = {
  5632. {"key1", "test", "", ""},
  5633. {"key2", "--abcdefg123", "", ""},
  5634. };
  5635. Headers headers;
  5636. headers.emplace("Accept-Encoding", "zstd");
  5637. cli_.set_compress(true);
  5638. auto res = cli_.Post("/compress-multipart", headers, items);
  5639. ASSERT_TRUE(res);
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. }
  5642. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5643. Headers headers;
  5644. headers.emplace("Accept-Encoding", "zstd");
  5645. cli_.set_compress(true);
  5646. auto res = cli_.Put(
  5647. "/put", headers, 3,
  5648. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5649. sink.os << "PUT";
  5650. return true;
  5651. },
  5652. "text/plain");
  5653. ASSERT_TRUE(res);
  5654. EXPECT_EQ(StatusCode::OK_200, res->status);
  5655. EXPECT_EQ("PUT", res->body);
  5656. }
  5657. // Pre-compression logging tests
  5658. TEST_F(ServerTest, PreCompressionLogging) {
  5659. // Test data for compression (matches the actual /compress endpoint content)
  5660. const std::string test_content =
  5661. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5662. "3456789012345678901234567890";
  5663. // Variables to capture logging data
  5664. std::string pre_compression_body;
  5665. std::string pre_compression_content_type;
  5666. std::string pre_compression_content_encoding;
  5667. std::string post_compression_body;
  5668. std::string post_compression_content_type;
  5669. std::string post_compression_content_encoding;
  5670. // Set up pre-compression logger
  5671. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5672. const Response &res) {
  5673. pre_compression_body = res.body;
  5674. pre_compression_content_type = res.get_header_value("Content-Type");
  5675. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5676. });
  5677. // Set up post-compression logger
  5678. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5679. post_compression_body = res.body;
  5680. post_compression_content_type = res.get_header_value("Content-Type");
  5681. post_compression_content_encoding =
  5682. res.get_header_value("Content-Encoding");
  5683. });
  5684. // Test with gzip compression
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "gzip");
  5687. auto res = cli_.Get("/compress", headers);
  5688. // Verify response was compressed
  5689. ASSERT_TRUE(res);
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5692. // Verify pre-compression logger captured uncompressed content
  5693. EXPECT_EQ(test_content, pre_compression_body);
  5694. EXPECT_EQ("text/plain", pre_compression_content_type);
  5695. EXPECT_TRUE(pre_compression_content_encoding
  5696. .empty()); // No encoding header before compression
  5697. // Verify post-compression logger captured compressed content
  5698. EXPECT_NE(test_content,
  5699. post_compression_body); // Should be different after compression
  5700. EXPECT_EQ("text/plain", post_compression_content_type);
  5701. EXPECT_EQ("gzip", post_compression_content_encoding);
  5702. // Verify compressed content is smaller
  5703. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5704. }
  5705. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5706. const std::string test_content =
  5707. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5708. "3456789012345678901234567890";
  5709. std::string pre_compression_body;
  5710. std::string post_compression_body;
  5711. svr_.set_pre_compression_logger(
  5712. [&](const Request & /*req*/, const Response &res) {
  5713. pre_compression_body = res.body;
  5714. });
  5715. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5716. post_compression_body = res.body;
  5717. });
  5718. Headers headers;
  5719. headers.emplace("Accept-Encoding", "br");
  5720. auto res = cli_.Get("/compress", headers);
  5721. ASSERT_TRUE(res);
  5722. EXPECT_EQ(StatusCode::OK_200, res->status);
  5723. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5724. // Verify pre-compression content is uncompressed
  5725. EXPECT_EQ(test_content, pre_compression_body);
  5726. // Verify post-compression content is compressed
  5727. EXPECT_NE(test_content, post_compression_body);
  5728. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5729. }
  5730. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5731. const std::string test_content =
  5732. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5733. "3456789012345678901234567890";
  5734. std::string pre_compression_body;
  5735. std::string post_compression_body;
  5736. svr_.set_pre_compression_logger(
  5737. [&](const Request & /*req*/, const Response &res) {
  5738. pre_compression_body = res.body;
  5739. });
  5740. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5741. post_compression_body = res.body;
  5742. });
  5743. // Request without compression (use /nocompress endpoint)
  5744. Headers headers;
  5745. auto res = cli_.Get("/nocompress", headers);
  5746. ASSERT_TRUE(res);
  5747. EXPECT_EQ(StatusCode::OK_200, res->status);
  5748. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5749. // Pre-compression logger should not be called when no compression is applied
  5750. EXPECT_TRUE(
  5751. pre_compression_body.empty()); // Pre-compression logger not called
  5752. EXPECT_EQ(
  5753. test_content,
  5754. post_compression_body); // Post-compression logger captures final content
  5755. }
  5756. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5757. const std::string test_content =
  5758. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5759. "3456789012345678901234567890";
  5760. std::string pre_compression_body;
  5761. bool pre_logger_called = false;
  5762. // Set only pre-compression logger
  5763. svr_.set_pre_compression_logger(
  5764. [&](const Request & /*req*/, const Response &res) {
  5765. pre_compression_body = res.body;
  5766. pre_logger_called = true;
  5767. });
  5768. Headers headers;
  5769. headers.emplace("Accept-Encoding", "gzip");
  5770. auto res = cli_.Get("/compress", headers);
  5771. ASSERT_TRUE(res);
  5772. EXPECT_EQ(StatusCode::OK_200, res->status);
  5773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5774. // Verify pre-compression logger was called
  5775. EXPECT_TRUE(pre_logger_called);
  5776. EXPECT_EQ(test_content, pre_compression_body);
  5777. }
  5778. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5779. {
  5780. // Test with Expect: 100-continue header - success case
  5781. // Server returns 100 Continue, client sends body, server returns 200 OK
  5782. Request req;
  5783. req.method = "POST";
  5784. req.path = "/post-large";
  5785. req.set_header("Expect", "100-continue");
  5786. req.body = LARGE_DATA;
  5787. Response res;
  5788. auto error = Error::Success;
  5789. cli_.set_keep_alive(true);
  5790. auto ret = cli_.send(req, res, error);
  5791. EXPECT_TRUE(ret);
  5792. EXPECT_EQ(StatusCode::OK_200, res.status);
  5793. EXPECT_EQ(LARGE_DATA, res.body);
  5794. }
  5795. {
  5796. // Test with Expect: 100-continue header - error case
  5797. // Client should not send the body when server returns an error
  5798. Request req;
  5799. req.method = "POST";
  5800. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5801. req.set_header("Expect", "100-continue");
  5802. req.body = LARGE_DATA;
  5803. Response res;
  5804. auto error = Error::Success;
  5805. auto start = std::chrono::high_resolution_clock::now();
  5806. cli_.set_keep_alive(true);
  5807. auto ret = cli_.send(req, res, error);
  5808. auto end = std::chrono::high_resolution_clock::now();
  5809. auto elapsed =
  5810. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5811. .count();
  5812. // With Expect: 100-continue, request completes successfully but with error
  5813. EXPECT_TRUE(ret);
  5814. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5815. EXPECT_EQ("close", res.get_header_value("Connection"));
  5816. EXPECT_FALSE(cli_.is_socket_open());
  5817. EXPECT_LE(elapsed, 200);
  5818. }
  5819. {
  5820. // Send an extra GET request to ensure error recovery without hanging
  5821. Request req;
  5822. req.method = "GET";
  5823. req.path = "/hi";
  5824. auto start = std::chrono::high_resolution_clock::now();
  5825. auto res = cli_.send(req);
  5826. auto end = std::chrono::high_resolution_clock::now();
  5827. auto elapsed =
  5828. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5829. .count();
  5830. ASSERT_TRUE(res);
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. EXPECT_EQ("Hello World!", res->body);
  5833. EXPECT_LE(elapsed, 500);
  5834. }
  5835. }
  5836. TEST(ZstdDecompressor, ChunkedDecompression) {
  5837. std::string data;
  5838. for (size_t i = 0; i < 32 * 1024; ++i) {
  5839. data.push_back(static_cast<char>('a' + i % 26));
  5840. }
  5841. std::string compressed_data;
  5842. {
  5843. httplib::detail::zstd_compressor compressor;
  5844. bool result = compressor.compress(
  5845. data.data(), data.size(),
  5846. /*last=*/true,
  5847. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5848. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5849. compressed_data_size);
  5850. return true;
  5851. });
  5852. ASSERT_TRUE(result);
  5853. }
  5854. std::string decompressed_data;
  5855. {
  5856. httplib::detail::zstd_decompressor decompressor;
  5857. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5858. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5859. size_t chunk_size = 130;
  5860. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5861. chunk_begin += chunk_size) {
  5862. size_t current_chunk_size =
  5863. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5864. bool result = decompressor.decompress(
  5865. compressed_data.data() + chunk_begin, current_chunk_size,
  5866. [&](const char *decompressed_data_chunk,
  5867. size_t decompressed_data_chunk_size) {
  5868. decompressed_data.insert(decompressed_data.size(),
  5869. decompressed_data_chunk,
  5870. decompressed_data_chunk_size);
  5871. return true;
  5872. });
  5873. ASSERT_TRUE(result);
  5874. }
  5875. }
  5876. ASSERT_EQ(data, decompressed_data);
  5877. }
  5878. TEST(ZstdDecompressor, Decompress) {
  5879. std::string original_text = "Compressed with ZSTD";
  5880. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5881. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5882. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5883. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5884. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5885. std::string decompressed_data;
  5886. {
  5887. httplib::detail::zstd_decompressor decompressor;
  5888. bool result = decompressor.decompress(
  5889. compressed_data.data(), compressed_data.size(),
  5890. [&](const char *decompressed_data_chunk,
  5891. size_t decompressed_data_chunk_size) {
  5892. decompressed_data.insert(decompressed_data.size(),
  5893. decompressed_data_chunk,
  5894. decompressed_data_chunk_size);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(result);
  5898. }
  5899. ASSERT_EQ(original_text, decompressed_data);
  5900. }
  5901. #endif
  5902. // Sends a raw request to a server listening at HOST:PORT.
  5903. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5904. std::string *resp = nullptr) {
  5905. auto error = Error::Success;
  5906. auto client_sock = detail::create_client_socket(
  5907. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5908. /*connection_timeout_sec=*/5, 0,
  5909. /*read_timeout_sec=*/5, 0,
  5910. /*write_timeout_sec=*/5, 0, std::string(), error);
  5911. if (client_sock == INVALID_SOCKET) { return false; }
  5912. auto ret = detail::process_client_socket(
  5913. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5914. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5915. if (req.size() !=
  5916. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5917. return false;
  5918. }
  5919. char buf[512];
  5920. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5921. while (line_reader.getline()) {
  5922. if (resp) { *resp += line_reader.ptr(); }
  5923. }
  5924. return true;
  5925. });
  5926. detail::close_socket(client_sock);
  5927. return ret;
  5928. }
  5929. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5930. Server svr;
  5931. std::string header_value;
  5932. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5933. header_value = req.get_header_value("foo");
  5934. res.set_content("ok", "text/plain");
  5935. });
  5936. thread t = thread([&] { svr.listen(HOST, PORT); });
  5937. auto se = detail::scope_exit([&] {
  5938. svr.stop();
  5939. t.join();
  5940. ASSERT_FALSE(svr.is_running());
  5941. });
  5942. svr.wait_until_ready();
  5943. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5944. // like characters are not treated the same - use vertical tab and escape.
  5945. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5946. "foo: \t \v bar \x1B\t \r\n"
  5947. "Connection: close\r\n"
  5948. "\r\n";
  5949. std::string res;
  5950. ASSERT_TRUE(send_request(5, req, &res));
  5951. EXPECT_EQ(header_value, "");
  5952. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5953. }
  5954. // Sends a raw request and verifies that there isn't a crash or exception.
  5955. static void test_raw_request(const std::string &req,
  5956. std::string *out = nullptr) {
  5957. Server svr;
  5958. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5959. res.set_content("ok", "text/plain");
  5960. });
  5961. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5962. res.set_content("ok", "text/plain");
  5963. });
  5964. svr.Get("/header_field_value_check",
  5965. [&](const Request & /*req*/, Response &res) {
  5966. res.set_content("ok", "text/plain");
  5967. });
  5968. // Server read timeout must be longer than the client read timeout for the
  5969. // bug to reproduce, probably to force the server to process a request
  5970. // without a trailing blank line.
  5971. const time_t client_read_timeout_sec = 1;
  5972. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5973. bool listen_thread_ok = false;
  5974. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5975. auto se = detail::scope_exit([&] {
  5976. svr.stop();
  5977. t.join();
  5978. ASSERT_FALSE(svr.is_running());
  5979. EXPECT_TRUE(listen_thread_ok);
  5980. });
  5981. svr.wait_until_ready();
  5982. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5983. }
  5984. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5985. // A certain header line causes an exception if the header property is parsed
  5986. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5987. test_raw_request(
  5988. "GET /hi HTTP/1.1\r\n"
  5989. " : "
  5990. " "
  5991. " ");
  5992. }
  5993. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5994. // A certain header line causes an exception if the header property *name* is
  5995. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5996. // greedy matcher and requires backtracking when there are a lot of ":"
  5997. // characters.
  5998. // This occurs with libc++ but not libstdc++.
  5999. test_raw_request(
  6000. "GET /hi HTTP/1.1\r\n"
  6001. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6002. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6003. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6004. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6005. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6006. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6007. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6008. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6009. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6010. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6011. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6012. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6013. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6014. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6015. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6016. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6017. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6018. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6019. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6020. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6021. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6022. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6023. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6024. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6025. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6026. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6027. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6028. "&&&%%%");
  6029. }
  6030. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6031. // Make sure this doesn't crash the server.
  6032. // In a previous version of the header line regex, the "\r" rendered the line
  6033. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6034. // a new position where the leading white space ended and the field value
  6035. // began.
  6036. // The crash occurs with libc++ but not libstdc++.
  6037. test_raw_request("GET /hi HTTP/1.1\r\n"
  6038. "a:" +
  6039. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6040. "\r\n"
  6041. "\r\n");
  6042. }
  6043. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6044. std::string out;
  6045. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6046. "Content-Type: text/plain\r\n"
  6047. "Transfer-Encoding: chunked\r\n"
  6048. "\r\n"
  6049. "nothex\r\n",
  6050. &out);
  6051. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6052. }
  6053. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6054. std::string out;
  6055. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6056. "Content-Type: text/plain\r\n"
  6057. "Transfer-Encoding: chunked\r\n"
  6058. "\r\n"
  6059. "3\r\n"
  6060. "xyz\r\n"
  6061. "NaN\r\n",
  6062. &out);
  6063. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6064. }
  6065. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6066. std::string out;
  6067. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6068. "Content-Type: text/plain\r\n"
  6069. "Transfer-Encoding: chunked\r\n"
  6070. "\r\n"
  6071. // Length is too large for 64 bits.
  6072. "1ffffffffffffffff\r\n"
  6073. "xyz\r\n",
  6074. &out);
  6075. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6076. }
  6077. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6078. test_raw_request("GET /hi HTTP/1.1\r\n"
  6079. "Content-Type: text/plain\r\n\r");
  6080. }
  6081. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6082. std::string out;
  6083. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6084. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6085. }
  6086. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6087. Server svr;
  6088. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6089. EXPECT_TRUE(!req.remote_addr.empty());
  6090. });
  6091. thread t = thread([&] { svr.listen(HOST, PORT); });
  6092. auto se = detail::scope_exit([&] {
  6093. svr.stop();
  6094. t.join();
  6095. ASSERT_FALSE(svr.is_running());
  6096. });
  6097. svr.wait_until_ready();
  6098. // Send an invalid request line to trigger Bad Request
  6099. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6100. std::string out;
  6101. ASSERT_TRUE(send_request(5, bad_req, &out));
  6102. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6103. }
  6104. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6105. std::string out;
  6106. std::string request(
  6107. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6108. test_raw_request(request, &out);
  6109. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6110. }
  6111. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6112. std::string out;
  6113. std::string request(
  6114. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6115. test_raw_request(request, &out);
  6116. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6117. }
  6118. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6119. std::string out;
  6120. std::string request(
  6121. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6122. test_raw_request(request, &out);
  6123. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6124. }
  6125. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6126. std::string out;
  6127. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6128. "Test: \r\n\r\n",
  6129. &out);
  6130. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6131. }
  6132. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6133. Server svr;
  6134. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6135. res.set_header("Cache-Control", "no-cache");
  6136. res.set_chunked_content_provider(
  6137. "text/event-stream", [](size_t offset, DataSink &sink) {
  6138. std::string s = "data:";
  6139. s += std::to_string(offset);
  6140. s += "\n\n";
  6141. auto ret = sink.write(s.data(), s.size());
  6142. EXPECT_TRUE(ret);
  6143. std::this_thread::sleep_for(std::chrono::seconds(1));
  6144. return true;
  6145. });
  6146. });
  6147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6148. svr.wait_until_ready();
  6149. Client client(HOST, PORT);
  6150. const Headers headers = {{"Accept", "text/event-stream"}};
  6151. auto get_thread = std::thread([&client, &headers]() {
  6152. auto res = client.Get(
  6153. "/events", headers,
  6154. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6155. });
  6156. auto se = detail::scope_exit([&] {
  6157. svr.stop();
  6158. get_thread.join();
  6159. listen_thread.join();
  6160. ASSERT_FALSE(svr.is_running());
  6161. });
  6162. // Give GET time to get a few messages.
  6163. std::this_thread::sleep_for(std::chrono::seconds(2));
  6164. }
  6165. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6166. httplib::Server svr;
  6167. svr.Post("/hi",
  6168. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6169. res.status = StatusCode::OK_200;
  6170. });
  6171. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6172. svr.wait_until_ready();
  6173. Client cli(HOST, PORT);
  6174. auto res = cli.Post("/hi", "data", "text/plain");
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. svr.stop();
  6178. thread.join();
  6179. ASSERT_FALSE(svr.is_running());
  6180. res = cli.Post("/hi", "data", "text/plain");
  6181. ASSERT_FALSE(res);
  6182. }
  6183. TEST(ServerStopTest, ListenFailure) {
  6184. Server svr;
  6185. auto t = thread([&]() {
  6186. auto ret = svr.listen("????", PORT);
  6187. EXPECT_FALSE(ret);
  6188. });
  6189. svr.wait_until_ready();
  6190. svr.stop();
  6191. t.join();
  6192. }
  6193. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6194. TEST(ServerStopTest, Decommision) {
  6195. Server svr;
  6196. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6197. for (int i = 0; i < 4; i++) {
  6198. auto is_even = !(i % 2);
  6199. std::thread t{[&] {
  6200. try {
  6201. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6202. if (is_even) {
  6203. throw std::runtime_error("Some thing that happens to go wrong.");
  6204. }
  6205. svr.listen(HOST, PORT);
  6206. } catch (...) { svr.decommission(); }
  6207. }};
  6208. svr.wait_until_ready();
  6209. // Server is up
  6210. {
  6211. Client cli(HOST, PORT);
  6212. auto res = cli.Get("/hi");
  6213. if (is_even) {
  6214. EXPECT_FALSE(res);
  6215. } else {
  6216. EXPECT_TRUE(res);
  6217. EXPECT_EQ("hi...", res->body);
  6218. }
  6219. }
  6220. svr.stop();
  6221. t.join();
  6222. // Server is down...
  6223. {
  6224. Client cli(HOST, PORT);
  6225. auto res = cli.Get("/hi");
  6226. EXPECT_FALSE(res);
  6227. }
  6228. }
  6229. }
  6230. #endif
  6231. // Helper function for string body upload progress tests
  6232. template <typename SetupHandler, typename ClientCall>
  6233. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6234. ClientCall &&client_call,
  6235. const string &body) {
  6236. Server svr;
  6237. setup_handler(svr);
  6238. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6239. auto se = detail::scope_exit([&] {
  6240. svr.stop();
  6241. t.join();
  6242. });
  6243. svr.wait_until_ready();
  6244. Client cli(HOST, PORT);
  6245. vector<uint64_t> progress_values;
  6246. bool progress_called = false;
  6247. auto res =
  6248. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6249. progress_values.push_back(current);
  6250. progress_called = true;
  6251. return true;
  6252. });
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(200, res->status);
  6255. EXPECT_TRUE(progress_called);
  6256. }
  6257. TEST(UploadProgressTest, PostStringBodyBasic) {
  6258. TestStringBodyUploadProgress(
  6259. [](Server &svr) {
  6260. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6261. res.set_content("received", "text/plain");
  6262. });
  6263. },
  6264. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6265. return cli.Post("/test", body, "text/plain", progress_callback);
  6266. },
  6267. "test data for upload progress");
  6268. }
  6269. TEST(UploadProgressTest, PutStringBodyBasic) {
  6270. TestStringBodyUploadProgress(
  6271. [](Server &svr) {
  6272. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6273. res.set_content("put received", "text/plain");
  6274. });
  6275. },
  6276. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6277. return cli.Put("/test", body, "text/plain", progress_callback);
  6278. },
  6279. "put test data for upload progress");
  6280. }
  6281. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6282. TestStringBodyUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("patch received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6289. return cli.Patch("/test", body, "text/plain", progress_callback);
  6290. },
  6291. "patch test data for upload progress");
  6292. }
  6293. // Helper function for content provider upload progress tests
  6294. template <typename SetupHandler, typename ClientCall>
  6295. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6296. ClientCall &&client_call) {
  6297. Server svr;
  6298. setup_handler(svr);
  6299. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6300. auto se = detail::scope_exit([&] {
  6301. svr.stop();
  6302. t.join();
  6303. });
  6304. svr.wait_until_ready();
  6305. Client cli(HOST, PORT);
  6306. vector<uint64_t> progress_values;
  6307. auto res =
  6308. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6309. progress_values.push_back(current);
  6310. return true;
  6311. });
  6312. ASSERT_TRUE(res);
  6313. EXPECT_EQ(200, res->status);
  6314. EXPECT_FALSE(progress_values.empty());
  6315. }
  6316. TEST(UploadProgressTest, PostContentProviderProgress) {
  6317. TestContentProviderUploadProgress(
  6318. [](Server &svr) {
  6319. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6320. res.set_content("provider received", "text/plain");
  6321. });
  6322. },
  6323. [](Client &cli, UploadProgress progress_callback) {
  6324. return cli.Post(
  6325. "/test", 10,
  6326. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6327. sink.os << "test data";
  6328. return true;
  6329. },
  6330. "text/plain", progress_callback);
  6331. });
  6332. }
  6333. // Helper function for multipart upload progress tests
  6334. template <typename SetupHandler, typename ClientCall>
  6335. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6336. ClientCall &&client_call,
  6337. const string &endpoint) {
  6338. Server svr;
  6339. setup_handler(svr);
  6340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. t.join();
  6344. });
  6345. svr.wait_until_ready();
  6346. Client cli(HOST, PORT);
  6347. vector<uint64_t> progress_values;
  6348. UploadFormDataItems items = {
  6349. {"field1", "value1", "", ""},
  6350. {"field2", "longer value for progress tracking test", "", ""},
  6351. {"file1", "file content data for upload progress", "test.txt",
  6352. "text/plain"}};
  6353. auto res = client_call(cli, endpoint, items,
  6354. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6355. progress_values.push_back(current);
  6356. return true;
  6357. });
  6358. ASSERT_TRUE(res);
  6359. EXPECT_EQ(200, res->status);
  6360. EXPECT_FALSE(progress_values.empty());
  6361. }
  6362. TEST(UploadProgressTest, PostMultipartProgress) {
  6363. TestMultipartUploadProgress(
  6364. [](Server &svr) {
  6365. svr.Post("/multipart", [](const Request &req, Response &res) {
  6366. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6367. res.set_content("multipart received", "text/plain");
  6368. });
  6369. },
  6370. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6371. UploadProgress progress_callback) {
  6372. return cli.Post(endpoint, items, progress_callback);
  6373. },
  6374. "/multipart");
  6375. }
  6376. // Helper function for basic download progress tests
  6377. template <typename SetupHandler, typename ClientCall>
  6378. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6379. ClientCall &&client_call, const string &endpoint,
  6380. size_t expected_content_size) {
  6381. Server svr;
  6382. setup_handler(svr);
  6383. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6384. auto se = detail::scope_exit([&] {
  6385. svr.stop();
  6386. t.join();
  6387. });
  6388. svr.wait_until_ready();
  6389. Client cli(HOST, PORT);
  6390. vector<uint64_t> progress_values;
  6391. auto res = client_call(cli, endpoint,
  6392. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6393. progress_values.push_back(current);
  6394. return true;
  6395. });
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ(200, res->status);
  6398. EXPECT_FALSE(progress_values.empty());
  6399. EXPECT_EQ(expected_content_size, res->body.size());
  6400. }
  6401. TEST(DownloadProgressTest, GetBasic) {
  6402. TestBasicDownloadProgress(
  6403. [](Server &svr) {
  6404. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6405. string content(1000, 'D');
  6406. res.set_content(content, "text/plain");
  6407. });
  6408. },
  6409. [](Client &cli, const string &endpoint,
  6410. DownloadProgress progress_callback) {
  6411. return cli.Get(endpoint, progress_callback);
  6412. },
  6413. "/download", 1000u);
  6414. }
  6415. // Helper function for content receiver download progress tests
  6416. template <typename SetupHandler, typename ClientCall>
  6417. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6418. ClientCall &&client_call,
  6419. const string &endpoint,
  6420. size_t expected_content_size) {
  6421. Server svr;
  6422. setup_handler(svr);
  6423. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6424. auto se = detail::scope_exit([&] {
  6425. svr.stop();
  6426. t.join();
  6427. });
  6428. svr.wait_until_ready();
  6429. Client cli(HOST, PORT);
  6430. vector<uint64_t> progress_values;
  6431. string received_body;
  6432. auto res = client_call(
  6433. cli, endpoint,
  6434. [&](const char *data, size_t data_length) -> bool {
  6435. received_body.append(data, data_length);
  6436. return true;
  6437. },
  6438. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6439. progress_values.push_back(current);
  6440. return true;
  6441. });
  6442. ASSERT_TRUE(res);
  6443. EXPECT_EQ(200, res->status);
  6444. EXPECT_FALSE(progress_values.empty());
  6445. EXPECT_EQ(expected_content_size, received_body.size());
  6446. EXPECT_TRUE(res->body.empty());
  6447. }
  6448. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6449. TestContentReceiverDownloadProgress(
  6450. [](Server &svr) {
  6451. svr.Get("/download-receiver",
  6452. [](const Request & /*req*/, Response &res) {
  6453. string content(2000, 'R');
  6454. res.set_content(content, "text/plain");
  6455. });
  6456. },
  6457. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6458. DownloadProgress progress_callback) {
  6459. return cli.Get(endpoint, content_receiver, progress_callback);
  6460. },
  6461. "/download-receiver", 2000u);
  6462. }
  6463. TEST(StreamingTest, NoContentLengthStreaming) {
  6464. Server svr;
  6465. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6466. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6467. if (offset < 6) {
  6468. sink.os << (offset < 3 ? "a" : "b");
  6469. } else {
  6470. sink.done();
  6471. }
  6472. return true;
  6473. });
  6474. });
  6475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6476. auto listen_se = detail::scope_exit([&] {
  6477. svr.stop();
  6478. listen_thread.join();
  6479. ASSERT_FALSE(svr.is_running());
  6480. });
  6481. svr.wait_until_ready();
  6482. Client client(HOST, PORT);
  6483. auto get_thread = std::thread([&client]() {
  6484. std::string s;
  6485. auto res =
  6486. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6487. s += std::string(data, len);
  6488. return true;
  6489. });
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("aaabbb", s);
  6493. });
  6494. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6495. // Give GET time to get a few messages.
  6496. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6497. }
  6498. TEST(MountTest, Unmount) {
  6499. Server svr;
  6500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6501. auto se = detail::scope_exit([&] {
  6502. svr.stop();
  6503. listen_thread.join();
  6504. ASSERT_FALSE(svr.is_running());
  6505. });
  6506. svr.wait_until_ready();
  6507. Client cli("localhost", PORT);
  6508. svr.set_mount_point("/mount2", "./www2");
  6509. auto res = cli.Get("/");
  6510. ASSERT_TRUE(res);
  6511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6512. res = cli.Get("/mount2/dir/test.html");
  6513. ASSERT_TRUE(res);
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. svr.set_mount_point("/", "./www");
  6516. res = cli.Get("/dir/");
  6517. ASSERT_TRUE(res);
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. svr.remove_mount_point("/");
  6520. res = cli.Get("/dir/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. svr.remove_mount_point("/mount2");
  6524. res = cli.Get("/mount2/dir/test.html");
  6525. ASSERT_TRUE(res);
  6526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6527. }
  6528. TEST(MountTest, Redicect) {
  6529. Server svr;
  6530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6531. auto se = detail::scope_exit([&] {
  6532. svr.stop();
  6533. listen_thread.join();
  6534. ASSERT_FALSE(svr.is_running());
  6535. });
  6536. svr.set_mount_point("/", "./www");
  6537. svr.wait_until_ready();
  6538. Client cli("localhost", PORT);
  6539. auto res = cli.Get("/dir/");
  6540. ASSERT_TRUE(res);
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. res = cli.Get("/dir");
  6543. ASSERT_TRUE(res);
  6544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6545. res = cli.Get("/file");
  6546. ASSERT_TRUE(res);
  6547. EXPECT_EQ(StatusCode::OK_200, res->status);
  6548. res = cli.Get("/file/");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. cli.set_follow_location(true);
  6552. res = cli.Get("/dir");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. }
  6556. TEST(MountTest, MultibytesPathName) {
  6557. Server svr;
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.set_mount_point("/", "./www");
  6565. svr.wait_until_ready();
  6566. Client cli("localhost", PORT);
  6567. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6568. ASSERT_TRUE(res);
  6569. EXPECT_EQ(StatusCode::OK_200, res->status);
  6570. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6571. }
  6572. TEST(KeepAliveTest, ReadTimeout) {
  6573. Server svr;
  6574. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6575. std::this_thread::sleep_for(std::chrono::seconds(2));
  6576. res.set_content("a", "text/plain");
  6577. });
  6578. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6579. res.set_content("b", "text/plain");
  6580. });
  6581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6582. auto se = detail::scope_exit([&] {
  6583. svr.stop();
  6584. listen_thread.join();
  6585. ASSERT_FALSE(svr.is_running());
  6586. });
  6587. svr.wait_until_ready();
  6588. Client cli("localhost", PORT);
  6589. cli.set_keep_alive(true);
  6590. cli.set_read_timeout(std::chrono::seconds(1));
  6591. auto resa = cli.Get("/a");
  6592. ASSERT_FALSE(resa);
  6593. EXPECT_EQ(Error::Read, resa.error());
  6594. auto resb = cli.Get("/b");
  6595. ASSERT_TRUE(resb);
  6596. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6597. EXPECT_EQ("b", resb->body);
  6598. }
  6599. TEST(KeepAliveTest, MaxCount) {
  6600. size_t keep_alive_max_count = 3;
  6601. Server svr;
  6602. svr.set_keep_alive_max_count(keep_alive_max_count);
  6603. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6604. res.set_content("Hello World!", "text/plain");
  6605. });
  6606. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. listen_thread.join();
  6610. ASSERT_FALSE(svr.is_running());
  6611. });
  6612. svr.wait_until_ready();
  6613. Client cli(HOST, PORT);
  6614. cli.set_keep_alive(true);
  6615. for (size_t i = 0; i < 5; i++) {
  6616. auto result = cli.Get("/hi");
  6617. ASSERT_TRUE(result);
  6618. EXPECT_EQ(StatusCode::OK_200, result->status);
  6619. if (i == keep_alive_max_count - 1) {
  6620. EXPECT_EQ("close", result->get_header_value("Connection"));
  6621. } else {
  6622. EXPECT_FALSE(result->has_header("Connection"));
  6623. }
  6624. }
  6625. }
  6626. TEST(KeepAliveTest, Issue1041) {
  6627. Server svr;
  6628. svr.set_keep_alive_timeout(3);
  6629. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6630. res.set_content("Hello World!", "text/plain");
  6631. });
  6632. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6633. auto se = detail::scope_exit([&] {
  6634. svr.stop();
  6635. listen_thread.join();
  6636. ASSERT_FALSE(svr.is_running());
  6637. });
  6638. svr.wait_until_ready();
  6639. Client cli(HOST, PORT);
  6640. cli.set_keep_alive(true);
  6641. auto result = cli.Get("/hi");
  6642. ASSERT_TRUE(result);
  6643. EXPECT_EQ(StatusCode::OK_200, result->status);
  6644. std::this_thread::sleep_for(std::chrono::seconds(5));
  6645. result = cli.Get("/hi");
  6646. ASSERT_TRUE(result);
  6647. EXPECT_EQ(StatusCode::OK_200, result->status);
  6648. }
  6649. TEST(KeepAliveTest, Issue1959) {
  6650. Server svr;
  6651. svr.set_keep_alive_timeout(5);
  6652. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6653. res.set_content("a", "text/plain");
  6654. });
  6655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6656. auto se = detail::scope_exit([&] {
  6657. if (!svr.is_running()) return;
  6658. svr.stop();
  6659. listen_thread.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. });
  6662. svr.wait_until_ready();
  6663. Client cli("localhost", PORT);
  6664. cli.set_keep_alive(true);
  6665. using namespace std::chrono;
  6666. auto start = steady_clock::now();
  6667. cli.Get("/a");
  6668. svr.stop();
  6669. listen_thread.join();
  6670. auto end = steady_clock::now();
  6671. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6672. EXPECT_LT(elapsed, 5000);
  6673. }
  6674. #ifdef CPPHTTPLIB_SSL_ENABLED
  6675. TEST(KeepAliveTest, SSLClientReconnection) {
  6676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6677. ASSERT_TRUE(svr.is_valid());
  6678. svr.set_keep_alive_timeout(1);
  6679. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6680. res.set_content("Hello World!", "text/plain");
  6681. });
  6682. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6683. auto se = detail::scope_exit([&] {
  6684. svr.stop();
  6685. listen_thread.join();
  6686. ASSERT_FALSE(svr.is_running());
  6687. });
  6688. svr.wait_until_ready();
  6689. SSLClient cli(HOST, PORT);
  6690. cli.enable_server_certificate_verification(false);
  6691. cli.set_keep_alive(true);
  6692. auto result = cli.Get("/hi");
  6693. ASSERT_TRUE(result);
  6694. EXPECT_EQ(StatusCode::OK_200, result->status);
  6695. result = cli.Get("/hi");
  6696. ASSERT_TRUE(result);
  6697. EXPECT_EQ(StatusCode::OK_200, result->status);
  6698. std::this_thread::sleep_for(std::chrono::seconds(2));
  6699. // Recoonect
  6700. result = cli.Get("/hi");
  6701. ASSERT_TRUE(result);
  6702. EXPECT_EQ(StatusCode::OK_200, result->status);
  6703. result = cli.Get("/hi");
  6704. ASSERT_TRUE(result);
  6705. EXPECT_EQ(StatusCode::OK_200, result->status);
  6706. }
  6707. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6709. ASSERT_TRUE(svr.is_valid());
  6710. svr.set_keep_alive_timeout(1);
  6711. std::string content = "reconnect";
  6712. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6713. res.set_content("Hello World!", "text/plain");
  6714. });
  6715. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6716. auto se = detail::scope_exit([&] {
  6717. svr.stop();
  6718. listen_thread.join();
  6719. ASSERT_FALSE(svr.is_running());
  6720. });
  6721. svr.wait_until_ready();
  6722. SSLClient cli(HOST, PORT);
  6723. cli.enable_server_certificate_verification(false);
  6724. cli.set_keep_alive(true);
  6725. auto result = cli.Post(
  6726. "/hi", content.size(),
  6727. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6728. sink.write(content.c_str(), content.size());
  6729. return true;
  6730. },
  6731. "text/plain");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(200, result->status);
  6734. std::this_thread::sleep_for(std::chrono::seconds(2));
  6735. // Recoonect
  6736. result = cli.Post(
  6737. "/hi", content.size(),
  6738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6739. sink.write(content.c_str(), content.size());
  6740. return true;
  6741. },
  6742. "text/plain");
  6743. ASSERT_TRUE(result);
  6744. EXPECT_EQ(200, result->status);
  6745. result = cli.Post(
  6746. "/hi", content.size(),
  6747. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6748. sink.write(content.c_str(), content.size());
  6749. return true;
  6750. },
  6751. "text/plain");
  6752. ASSERT_TRUE(result);
  6753. EXPECT_EQ(200, result->status);
  6754. }
  6755. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6756. using namespace httplib::tls;
  6757. {
  6758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6759. ASSERT_TRUE(svr.is_valid());
  6760. svr.Get("/sni", [&](const Request &req, Response &res) {
  6761. std::string expected = req.sni();
  6762. EXPECT_EQ(expected, req.get_param_value("expected"));
  6763. res.set_content("ok", "text/plain");
  6764. });
  6765. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6766. auto se = detail::scope_exit([&] {
  6767. svr.stop();
  6768. listen_thread.join();
  6769. ASSERT_FALSE(svr.is_running());
  6770. });
  6771. svr.wait_until_ready();
  6772. {
  6773. SSLClient cli("localhost", PORT);
  6774. cli.enable_server_certificate_verification(false);
  6775. auto res = cli.Get("/sni?expected=localhost");
  6776. ASSERT_TRUE(res);
  6777. }
  6778. {
  6779. SSLClient cli("::1", PORT);
  6780. cli.enable_server_certificate_verification(false);
  6781. auto res = cli.Get("/sni?expected=");
  6782. // NOTE: This may fail if the server is listening on IPv4 only
  6783. // (e.g., when localhost resolves to 127.0.0.1 only)
  6784. if (res) {
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. } else {
  6787. EXPECT_EQ(Error::Connection, res.error());
  6788. }
  6789. }
  6790. }
  6791. }
  6792. #endif
  6793. TEST(ClientProblemDetectionTest, ContentProvider) {
  6794. Server svr;
  6795. size_t content_length = 1024 * 1024;
  6796. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6797. res.set_content_provider(
  6798. content_length, "text/plain",
  6799. [&](size_t offset, size_t length, DataSink &sink) {
  6800. auto out_len = std::min(length, static_cast<size_t>(1024));
  6801. std::string out(out_len, '@');
  6802. sink.write(out.data(), out_len);
  6803. return offset < 4096;
  6804. },
  6805. [](bool success) { ASSERT_FALSE(success); });
  6806. });
  6807. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content_provider(
  6809. 0, "text/plain",
  6810. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6811. EXPECT_TRUE(false);
  6812. return true;
  6813. },
  6814. [](bool success) { ASSERT_FALSE(success); });
  6815. });
  6816. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6817. auto se = detail::scope_exit([&] {
  6818. svr.stop();
  6819. listen_thread.join();
  6820. ASSERT_FALSE(svr.is_running());
  6821. });
  6822. svr.wait_until_ready();
  6823. Client cli("localhost", PORT);
  6824. {
  6825. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6826. size_t /*data_length*/) { return false; });
  6827. ASSERT_FALSE(res);
  6828. }
  6829. {
  6830. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6831. size_t /*data_length*/) { return false; });
  6832. ASSERT_TRUE(res);
  6833. }
  6834. }
  6835. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6836. Server svr;
  6837. svr.set_error_handler([](Request const &, Response &res) -> void {
  6838. res.set_chunked_content_provider(
  6839. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6840. sink.os << "hello";
  6841. sink.os << "world";
  6842. sink.done();
  6843. return true;
  6844. });
  6845. });
  6846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6847. auto se = detail::scope_exit([&] {
  6848. svr.stop();
  6849. listen_thread.join();
  6850. ASSERT_FALSE(svr.is_running());
  6851. });
  6852. svr.wait_until_ready();
  6853. Client cli("localhost", PORT);
  6854. auto res = cli.Get("/");
  6855. ASSERT_TRUE(res);
  6856. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6857. EXPECT_EQ("helloworld", res->body);
  6858. }
  6859. TEST(LongPollingTest, ClientCloseDetection) {
  6860. Server svr;
  6861. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6862. res.set_chunked_content_provider(
  6863. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6864. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6865. sink.os << "hello";
  6866. auto count = 10;
  6867. while (count > 0 && sink.is_writable()) {
  6868. this_thread::sleep_for(chrono::milliseconds(10));
  6869. count--;
  6870. }
  6871. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6872. return true;
  6873. });
  6874. });
  6875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6876. auto se = detail::scope_exit([&] {
  6877. svr.stop();
  6878. listen_thread.join();
  6879. ASSERT_FALSE(svr.is_running());
  6880. });
  6881. svr.wait_until_ready();
  6882. Client cli("localhost", PORT);
  6883. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6884. EXPECT_EQ("hello", string(data, data_length));
  6885. return false; // close the socket immediately.
  6886. });
  6887. ASSERT_FALSE(res);
  6888. }
  6889. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6890. Server svr;
  6891. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6892. res.set_chunked_content_provider(
  6893. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6894. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6895. sink.os << "hello";
  6896. EXPECT_TRUE(sink.os.good());
  6897. // Wait for the client to close the connection
  6898. auto count = 10;
  6899. while (count > 0 && sink.is_writable()) {
  6900. this_thread::sleep_for(chrono::milliseconds(10));
  6901. count--;
  6902. }
  6903. // After client disconnect, write repeatedly until the socket
  6904. // write actually fails (small writes may be absorbed by the
  6905. // kernel buffer)
  6906. std::string chunk(1024, 'x');
  6907. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6908. sink.os << chunk;
  6909. }
  6910. EXPECT_TRUE(sink.os.fail());
  6911. return true;
  6912. });
  6913. });
  6914. auto port = svr.bind_to_any_port("localhost");
  6915. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6916. auto se = detail::scope_exit([&] {
  6917. svr.stop();
  6918. listen_thread.join();
  6919. ASSERT_FALSE(svr.is_running());
  6920. });
  6921. svr.wait_until_ready();
  6922. Client cli("localhost", port);
  6923. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6924. EXPECT_EQ("hello", string(data, data_length));
  6925. return false; // close the socket immediately.
  6926. });
  6927. ASSERT_FALSE(res);
  6928. }
  6929. TEST(GetWithParametersTest, GetWithParameters) {
  6930. Server svr;
  6931. svr.Get("/", [&](const Request &req, Response &) {
  6932. EXPECT_EQ("world", req.get_param_value("hello"));
  6933. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6934. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6935. });
  6936. svr.Get("/params", [&](const Request &req, Response &) {
  6937. EXPECT_EQ("world", req.get_param_value("hello"));
  6938. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6939. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6940. });
  6941. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6942. EXPECT_EQ("resource-id", req.matches[1]);
  6943. EXPECT_EQ("foo", req.get_param_value("param1"));
  6944. EXPECT_EQ("bar", req.get_param_value("param2"));
  6945. });
  6946. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6947. EXPECT_EQ("user-id", req.path_params.at("id"));
  6948. EXPECT_EQ("foo", req.get_param_value("param1"));
  6949. EXPECT_EQ("bar", req.get_param_value("param2"));
  6950. });
  6951. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6952. auto se = detail::scope_exit([&] {
  6953. svr.stop();
  6954. listen_thread.join();
  6955. ASSERT_FALSE(svr.is_running());
  6956. });
  6957. svr.wait_until_ready();
  6958. {
  6959. Client cli(HOST, PORT);
  6960. Params params;
  6961. params.emplace("hello", "world");
  6962. params.emplace("hello2", "world2");
  6963. params.emplace("hello3", "world3");
  6964. auto res = cli.Get("/", params, Headers{});
  6965. ASSERT_TRUE(res);
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. {
  6969. Client cli(HOST, PORT);
  6970. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6971. ASSERT_TRUE(res);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. {
  6975. Client cli(HOST, PORT);
  6976. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6977. ASSERT_TRUE(res);
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. {
  6981. Client cli(HOST, PORT);
  6982. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6983. ASSERT_TRUE(res);
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. }
  6986. }
  6987. TEST(GetWithParametersTest, GetWithParameters2) {
  6988. Server svr;
  6989. svr.Get("/", [&](const Request &req, Response &res) {
  6990. auto text = req.get_param_value("hello");
  6991. res.set_content(text, "text/plain");
  6992. });
  6993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6994. auto se = detail::scope_exit([&] {
  6995. svr.stop();
  6996. listen_thread.join();
  6997. ASSERT_FALSE(svr.is_running());
  6998. });
  6999. svr.wait_until_ready();
  7000. Client cli("localhost", PORT);
  7001. Params params;
  7002. params.emplace("hello", "world");
  7003. std::string body;
  7004. auto res = cli.Get("/", params, Headers{},
  7005. [&](const char *data, size_t data_length) {
  7006. body.append(data, data_length);
  7007. return true;
  7008. });
  7009. ASSERT_TRUE(res);
  7010. EXPECT_EQ(StatusCode::OK_200, res->status);
  7011. EXPECT_EQ("world", body);
  7012. }
  7013. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7014. auto host = "httpbingo.org";
  7015. auto path = std::string{"/range/32"};
  7016. #ifdef CPPHTTPLIB_SSL_ENABLED
  7017. SSLClient cli(host);
  7018. #else
  7019. Client cli(host);
  7020. #endif
  7021. cli.set_default_headers({make_range_header({{1, 10}})});
  7022. cli.set_connection_timeout(5);
  7023. {
  7024. auto res = cli.Get(path);
  7025. ASSERT_TRUE(res);
  7026. EXPECT_EQ("bcdefghijk", res->body);
  7027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7028. }
  7029. {
  7030. auto res = cli.Get(path);
  7031. ASSERT_TRUE(res);
  7032. EXPECT_EQ("bcdefghijk", res->body);
  7033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7034. }
  7035. }
  7036. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7037. Server svr;
  7038. svr.set_default_headers({{"Hello", "World"}});
  7039. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7040. res.set_content("ok", "text/plain");
  7041. });
  7042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7043. auto se = detail::scope_exit([&] {
  7044. svr.stop();
  7045. listen_thread.join();
  7046. ASSERT_FALSE(svr.is_running());
  7047. });
  7048. svr.wait_until_ready();
  7049. Client cli("localhost", PORT);
  7050. auto res = cli.Get("/");
  7051. ASSERT_TRUE(res);
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("ok", res->body);
  7054. EXPECT_EQ("World", res->get_header_value("Hello"));
  7055. }
  7056. #ifdef CPPHTTPLIB_SSL_ENABLED
  7057. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7059. ASSERT_TRUE(svr.is_valid());
  7060. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7061. std::this_thread::sleep_for(std::chrono::seconds(2));
  7062. res.set_content("a", "text/plain");
  7063. });
  7064. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7065. res.set_content("b", "text/plain");
  7066. });
  7067. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7068. auto se = detail::scope_exit([&] {
  7069. svr.stop();
  7070. listen_thread.join();
  7071. ASSERT_FALSE(svr.is_running());
  7072. });
  7073. svr.wait_until_ready();
  7074. SSLClient cli("localhost", PORT);
  7075. cli.enable_server_certificate_verification(false);
  7076. cli.set_keep_alive(true);
  7077. cli.set_read_timeout(std::chrono::seconds(1));
  7078. auto resa = cli.Get("/a");
  7079. ASSERT_TRUE(!resa);
  7080. EXPECT_EQ(Error::Read, resa.error());
  7081. auto resb = cli.Get("/b");
  7082. ASSERT_TRUE(resb);
  7083. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7084. EXPECT_EQ("b", resb->body);
  7085. }
  7086. #endif
  7087. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7088. protected:
  7089. ServerTestWithAI_PASSIVE()
  7090. : cli_(HOST, PORT)
  7091. #ifdef CPPHTTPLIB_SSL_ENABLED
  7092. ,
  7093. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7094. #endif
  7095. {
  7096. #ifdef CPPHTTPLIB_SSL_ENABLED
  7097. cli_.enable_server_certificate_verification(false);
  7098. #endif
  7099. }
  7100. virtual void SetUp() {
  7101. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7102. res.set_content("Hello World!", "text/plain");
  7103. });
  7104. t_ = thread(
  7105. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7106. svr_.wait_until_ready();
  7107. }
  7108. virtual void TearDown() {
  7109. svr_.stop();
  7110. t_.join();
  7111. }
  7112. #ifdef CPPHTTPLIB_SSL_ENABLED
  7113. SSLClient cli_;
  7114. SSLServer svr_;
  7115. #else
  7116. Client cli_;
  7117. Server svr_;
  7118. #endif
  7119. thread t_;
  7120. };
  7121. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7122. auto res = cli_.Get("/hi");
  7123. ASSERT_TRUE(res);
  7124. EXPECT_EQ(StatusCode::OK_200, res->status);
  7125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7126. EXPECT_EQ("Hello World!", res->body);
  7127. }
  7128. class ServerUpDownTest : public ::testing::Test {
  7129. protected:
  7130. ServerUpDownTest() : cli_(HOST, PORT) {}
  7131. virtual void SetUp() {
  7132. t_ = thread([&]() {
  7133. svr_.bind_to_any_port(HOST);
  7134. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7135. ASSERT_TRUE(svr_.listen_after_bind());
  7136. });
  7137. svr_.wait_until_ready();
  7138. }
  7139. virtual void TearDown() {
  7140. svr_.stop();
  7141. t_.join();
  7142. }
  7143. Client cli_;
  7144. Server svr_;
  7145. thread t_;
  7146. };
  7147. TEST_F(ServerUpDownTest, QuickStartStop) {
  7148. // Should not crash, especially when run with
  7149. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7150. }
  7151. class PayloadMaxLengthTest : public ::testing::Test {
  7152. protected:
  7153. PayloadMaxLengthTest()
  7154. : cli_(HOST, PORT)
  7155. #ifdef CPPHTTPLIB_SSL_ENABLED
  7156. ,
  7157. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7158. #endif
  7159. {
  7160. #ifdef CPPHTTPLIB_SSL_ENABLED
  7161. cli_.enable_server_certificate_verification(false);
  7162. #endif
  7163. }
  7164. virtual void SetUp() {
  7165. svr_.set_payload_max_length(8);
  7166. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7167. res.set_content("test", "text/plain");
  7168. });
  7169. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7170. svr_.wait_until_ready();
  7171. }
  7172. virtual void TearDown() {
  7173. svr_.stop();
  7174. t_.join();
  7175. }
  7176. #ifdef CPPHTTPLIB_SSL_ENABLED
  7177. SSLClient cli_;
  7178. SSLServer svr_;
  7179. #else
  7180. Client cli_;
  7181. Server svr_;
  7182. #endif
  7183. thread t_;
  7184. };
  7185. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7186. auto res = cli_.Post("/test", "123456789", "text/plain");
  7187. ASSERT_TRUE(res);
  7188. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7189. res = cli_.Post("/test", "12345678", "text/plain");
  7190. ASSERT_TRUE(res);
  7191. EXPECT_EQ(StatusCode::OK_200, res->status);
  7192. }
  7193. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7194. // Test chunked encoding with payload exceeding the 8-byte limit
  7195. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7196. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7197. ASSERT_TRUE(res);
  7198. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7199. }
  7200. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7201. // Test chunked encoding with payload within the 8-byte limit
  7202. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7203. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7204. ASSERT_TRUE(res);
  7205. EXPECT_EQ(StatusCode::OK_200, res->status);
  7206. }
  7207. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7208. // Test using send_request to send chunked data exceeding payload limit
  7209. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7210. "Host: " +
  7211. std::string(HOST) + ":" + std::to_string(PORT) +
  7212. "\r\n"
  7213. "Transfer-Encoding: chunked\r\n"
  7214. "Connection: close\r\n"
  7215. "\r\n"
  7216. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7217. "0123456789\r\n"
  7218. "0\r\n" // End chunk
  7219. "\r\n";
  7220. std::string response;
  7221. bool result = send_request(1, chunked_request, &response);
  7222. if (!result) {
  7223. // If send_request fails, it might be because the server closed the
  7224. // connection due to payload limit enforcement, which is acceptable
  7225. SUCCEED()
  7226. << "Server rejected oversized chunked request (connection closed)";
  7227. } else {
  7228. // If we got a response, check if it's an error response or connection was
  7229. // closed early Short response length indicates connection was closed due to
  7230. // payload limit
  7231. if (response.length() <= 10) {
  7232. SUCCEED() << "Server closed connection for oversized chunked request";
  7233. } else {
  7234. // Check for error status codes
  7235. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7236. response.find("Payload Too Large") != std::string::npos ||
  7237. response.find("400") != std::string::npos);
  7238. }
  7239. }
  7240. }
  7241. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7242. // Test request without Content-Length header exceeding payload limit
  7243. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7244. "Host: " +
  7245. std::string(HOST) + ":" +
  7246. std::to_string(PORT) +
  7247. "\r\n"
  7248. "Connection: close\r\n"
  7249. "\r\n";
  7250. // Add payload exceeding the 8-byte limit
  7251. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7252. request_without_content_length += large_payload;
  7253. std::string response;
  7254. bool result = send_request(1, request_without_content_length, &response);
  7255. if (!result) {
  7256. // If send_request fails, server likely closed connection due to payload
  7257. // limit
  7258. SUCCEED() << "Server rejected oversized request without Content-Length "
  7259. "(connection closed)";
  7260. } else {
  7261. // Check if server responded with error or closed connection early
  7262. if (response.length() <= 10) {
  7263. SUCCEED() << "Server closed connection for oversized request without "
  7264. "Content-Length";
  7265. } else {
  7266. // Check for error status codes
  7267. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7268. response.find("Payload Too Large") != std::string::npos ||
  7269. response.find("400") != std::string::npos);
  7270. }
  7271. }
  7272. }
  7273. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7274. // Test request without Content-Length header within payload limit
  7275. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7276. "Host: " +
  7277. std::string(HOST) + ":" +
  7278. std::to_string(PORT) +
  7279. "\r\n"
  7280. "Connection: close\r\n"
  7281. "\r\n";
  7282. // Add payload within the 8-byte limit
  7283. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7284. request_without_content_length += small_payload;
  7285. std::string response;
  7286. bool result = send_request(1, request_without_content_length, &response);
  7287. // For requests without Content-Length, the server may have different behavior
  7288. // The key is that it should not reject due to payload limit for small
  7289. // payloads
  7290. if (result) {
  7291. // Check for any HTTP response (success or error, but not connection closed)
  7292. if (response.length() > 10) {
  7293. SUCCEED()
  7294. << "Server processed request without Content-Length within limit";
  7295. } else {
  7296. // Short response might indicate connection closed, which is acceptable
  7297. SUCCEED() << "Server closed connection for request without "
  7298. "Content-Length (acceptable behavior)";
  7299. }
  7300. } else {
  7301. // Connection failure might be due to protocol requirements
  7302. SUCCEED() << "Connection issue with request without Content-Length "
  7303. "(environment-specific)";
  7304. }
  7305. }
  7306. class LargePayloadMaxLengthTest : public ::testing::Test {
  7307. protected:
  7308. LargePayloadMaxLengthTest()
  7309. : cli_(HOST, PORT)
  7310. #ifdef CPPHTTPLIB_SSL_ENABLED
  7311. ,
  7312. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7313. #endif
  7314. {
  7315. #ifdef CPPHTTPLIB_SSL_ENABLED
  7316. cli_.enable_server_certificate_verification(false);
  7317. #endif
  7318. }
  7319. virtual void SetUp() {
  7320. // Set 10MB payload limit
  7321. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7322. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7323. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7324. res.set_content("Large payload test", "text/plain");
  7325. });
  7326. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7327. svr_.wait_until_ready();
  7328. }
  7329. virtual void TearDown() {
  7330. svr_.stop();
  7331. t_.join();
  7332. }
  7333. #ifdef CPPHTTPLIB_SSL_ENABLED
  7334. SSLClient cli_;
  7335. SSLServer svr_;
  7336. #else
  7337. Client cli_;
  7338. Server svr_;
  7339. #endif
  7340. thread t_;
  7341. };
  7342. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7343. // Test chunked encoding with payload within 10MB limit
  7344. std::string medium_payload(5 * 1024 * 1024,
  7345. 'A'); // 5MB payload, within 10MB limit
  7346. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7347. ASSERT_TRUE(res);
  7348. EXPECT_EQ(StatusCode::OK_200, res->status);
  7349. }
  7350. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7351. // Test chunked encoding with payload exceeding 10MB limit
  7352. std::string large_payload(12 * 1024 * 1024,
  7353. 'B'); // 12MB payload, exceeds 10MB limit
  7354. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7355. // Server may either return 413 or close the connection
  7356. if (res) {
  7357. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7358. } else {
  7359. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7360. }
  7361. }
  7362. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7363. // Test request without Content-Length header within 10MB limit
  7364. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7365. "Host: " +
  7366. std::string(HOST) + ":" +
  7367. std::to_string(PORT) +
  7368. "\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. // Add 1MB payload (within 10MB limit)
  7372. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7373. request_without_content_length += medium_payload;
  7374. std::string response;
  7375. bool result = send_request(5, request_without_content_length, &response);
  7376. if (result) {
  7377. // Should get a proper HTTP response for payloads within limit
  7378. if (response.length() > 10) {
  7379. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7380. "10MB limit";
  7381. } else {
  7382. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7383. "Content-Length)";
  7384. }
  7385. } else {
  7386. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7387. }
  7388. }
  7389. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7390. // Test request without Content-Length header exceeding 10MB limit
  7391. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7392. "Host: " +
  7393. std::string(HOST) + ":" +
  7394. std::to_string(PORT) +
  7395. "\r\n"
  7396. "Connection: close\r\n"
  7397. "\r\n";
  7398. // Add 12MB payload (exceeds 10MB limit)
  7399. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7400. request_without_content_length += large_payload;
  7401. std::string response;
  7402. bool result = send_request(10, request_without_content_length, &response);
  7403. if (!result) {
  7404. // Server should close connection due to payload limit
  7405. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7406. "(connection closed)";
  7407. } else {
  7408. // Check for error response
  7409. if (response.length() <= 10) {
  7410. SUCCEED()
  7411. << "Server closed connection for 12MB request exceeding 10MB limit";
  7412. } else {
  7413. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7414. response.find("Payload Too Large") != std::string::npos ||
  7415. response.find("400") != std::string::npos);
  7416. }
  7417. }
  7418. }
  7419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7420. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7421. // path.
  7422. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7423. Server svr;
  7424. const size_t LIMIT = 64 * 1024; // 64KB
  7425. svr.set_payload_max_length(LIMIT);
  7426. size_t total = 0;
  7427. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7428. const ContentReader &content_reader) {
  7429. content_reader([&](const char * /*data*/, size_t len) {
  7430. total += len;
  7431. return true;
  7432. });
  7433. res.status = 200;
  7434. res.set_content("stream_ok", "text/plain");
  7435. });
  7436. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7437. auto se = detail::scope_exit([&] {
  7438. svr.stop();
  7439. thread.join();
  7440. ASSERT_FALSE(svr.is_running());
  7441. });
  7442. svr.wait_until_ready();
  7443. // Prepare 256KB raw data and gzip-compress it
  7444. std::string raw(256 * 1024, 'A');
  7445. std::string gz;
  7446. {
  7447. z_stream zs{};
  7448. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7449. Z_DEFAULT_STRATEGY);
  7450. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7451. zs.avail_in = static_cast<uInt>(raw.size());
  7452. char outbuf[4096];
  7453. int ret;
  7454. do {
  7455. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7456. zs.avail_out = sizeof(outbuf);
  7457. ret = deflate(&zs, Z_FINISH);
  7458. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7459. } while (ret != Z_STREAM_END);
  7460. deflateEnd(&zs);
  7461. }
  7462. Client cli(HOST, PORT);
  7463. cli.set_connection_timeout(std::chrono::seconds(5));
  7464. Headers headers = {{"Content-Encoding", "gzip"}};
  7465. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7466. "application/octet-stream");
  7467. ASSERT_TRUE(res);
  7468. // Server must reject oversized decompressed payloads with 413.
  7469. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7470. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7471. EXPECT_LE(total, LIMIT);
  7472. }
  7473. #endif
  7474. // Regression test for DoS vulnerability: a malicious server sending a response
  7475. // without Content-Length header must not cause unbounded memory consumption on
  7476. // the client side. The client should stop reading after a reasonable limit,
  7477. // similar to the server-side set_payload_max_length protection.
  7478. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7479. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7480. #ifndef _WIN32
  7481. signal(SIGPIPE, SIG_IGN);
  7482. #endif
  7483. auto server_thread = std::thread([] {
  7484. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7485. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7486. default_socket_options(srv);
  7487. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7489. sockaddr_in addr{};
  7490. addr.sin_family = AF_INET;
  7491. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7492. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7493. int opt = 1;
  7494. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7495. #ifdef _WIN32
  7496. reinterpret_cast<const char *>(&opt),
  7497. #else
  7498. &opt,
  7499. #endif
  7500. sizeof(opt));
  7501. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7502. ::listen(srv, 1);
  7503. sockaddr_in cli_addr{};
  7504. socklen_t cli_len = sizeof(cli_addr);
  7505. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7506. if (cli != INVALID_SOCKET) {
  7507. char buf[4096];
  7508. ::recv(cli, buf, sizeof(buf), 0);
  7509. // Malicious response: no Content-Length, no chunked encoding
  7510. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7511. "Connection: close\r\n"
  7512. "\r\n";
  7513. ::send(cli,
  7514. #ifdef _WIN32
  7515. static_cast<const char *>(response_header.c_str()),
  7516. static_cast<int>(response_header.size()),
  7517. #else
  7518. response_header.c_str(), response_header.size(),
  7519. #endif
  7520. 0);
  7521. // Send 10MB of data
  7522. std::string chunk(64 * 1024, 'A');
  7523. size_t total_sent = 0;
  7524. while (total_sent < MALICIOUS_DATA_SIZE) {
  7525. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7526. auto sent = ::send(cli,
  7527. #ifdef _WIN32
  7528. static_cast<const char *>(chunk.c_str()),
  7529. static_cast<int>(to_send),
  7530. #else
  7531. chunk.c_str(), to_send,
  7532. #endif
  7533. 0);
  7534. if (sent <= 0) break;
  7535. total_sent += static_cast<size_t>(sent);
  7536. }
  7537. detail::close_socket(cli);
  7538. }
  7539. detail::close_socket(srv);
  7540. });
  7541. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7542. size_t total_read = 0;
  7543. {
  7544. Client cli("127.0.0.1", PORT + 2);
  7545. cli.set_read_timeout(5, 0);
  7546. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7547. auto stream = cli.open_stream("GET", "/malicious");
  7548. ASSERT_TRUE(stream.is_valid());
  7549. char buffer[64 * 1024];
  7550. ssize_t n;
  7551. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7552. total_read += static_cast<size_t>(n);
  7553. }
  7554. } // StreamHandle and Client destroyed here, closing the socket
  7555. server_thread.join();
  7556. // With set_payload_max_length, the client must stop reading before consuming
  7557. // all 10MB. The read loop should be cut off at or near the configured limit.
  7558. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7559. << "Client read " << total_read << " bytes, exceeding the configured "
  7560. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7561. }
  7562. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7563. // the entire response body without truncation.
  7564. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7565. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7566. #ifndef _WIN32
  7567. signal(SIGPIPE, SIG_IGN);
  7568. #endif
  7569. auto server_thread = std::thread([] {
  7570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7571. default_socket_options(srv);
  7572. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7573. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7574. sockaddr_in addr{};
  7575. addr.sin_family = AF_INET;
  7576. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7577. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7578. int opt = 1;
  7579. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7580. #ifdef _WIN32
  7581. reinterpret_cast<const char *>(&opt),
  7582. #else
  7583. &opt,
  7584. #endif
  7585. sizeof(opt));
  7586. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7587. ::listen(srv, 1);
  7588. sockaddr_in cli_addr{};
  7589. socklen_t cli_len = sizeof(cli_addr);
  7590. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7591. if (cli != INVALID_SOCKET) {
  7592. char buf[4096];
  7593. ::recv(cli, buf, sizeof(buf), 0);
  7594. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7595. "Connection: close\r\n"
  7596. "\r\n";
  7597. ::send(cli,
  7598. #ifdef _WIN32
  7599. static_cast<const char *>(response_header.c_str()),
  7600. static_cast<int>(response_header.size()),
  7601. #else
  7602. response_header.c_str(), response_header.size(),
  7603. #endif
  7604. 0);
  7605. std::string chunk(64 * 1024, 'A');
  7606. size_t total_sent = 0;
  7607. while (total_sent < DATA_SIZE) {
  7608. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7609. auto sent = ::send(cli,
  7610. #ifdef _WIN32
  7611. static_cast<const char *>(chunk.c_str()),
  7612. static_cast<int>(to_send),
  7613. #else
  7614. chunk.c_str(), to_send,
  7615. #endif
  7616. 0);
  7617. if (sent <= 0) break;
  7618. total_sent += static_cast<size_t>(sent);
  7619. }
  7620. #ifdef _WIN32
  7621. ::shutdown(cli, SD_SEND);
  7622. #else
  7623. ::shutdown(cli, SHUT_WR);
  7624. #endif
  7625. // Drain until the client closes its end, ensuring all data is delivered
  7626. char drain[1024];
  7627. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7628. detail::close_socket(cli);
  7629. }
  7630. detail::close_socket(srv);
  7631. });
  7632. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7633. size_t total_read = 0;
  7634. {
  7635. Client cli("127.0.0.1", PORT + 2);
  7636. cli.set_read_timeout(5, 0);
  7637. cli.set_payload_max_length(0); // 0 means no limit
  7638. auto stream = cli.open_stream("GET", "/data");
  7639. ASSERT_TRUE(stream.is_valid());
  7640. char buffer[64 * 1024];
  7641. ssize_t n;
  7642. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7643. total_read += static_cast<size_t>(n);
  7644. }
  7645. }
  7646. server_thread.join();
  7647. EXPECT_EQ(total_read, DATA_SIZE)
  7648. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7649. << " bytes without truncation, but only read " << total_read << " bytes.";
  7650. }
  7651. // Verify that content_receiver bypasses the default payload_max_length,
  7652. // allowing streaming downloads larger than 100MB without requiring an explicit
  7653. // set_payload_max_length call.
  7654. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7655. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7656. #ifndef _WIN32
  7657. signal(SIGPIPE, SIG_IGN);
  7658. #endif
  7659. auto server_thread = std::thread([] {
  7660. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7661. default_socket_options(srv);
  7662. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7663. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7664. sockaddr_in addr{};
  7665. addr.sin_family = AF_INET;
  7666. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7667. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7668. int opt = 1;
  7669. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7670. #ifdef _WIN32
  7671. reinterpret_cast<const char *>(&opt),
  7672. #else
  7673. &opt,
  7674. #endif
  7675. sizeof(opt));
  7676. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7677. ::listen(srv, 1);
  7678. sockaddr_in cli_addr{};
  7679. socklen_t cli_len = sizeof(cli_addr);
  7680. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7681. if (cli != INVALID_SOCKET) {
  7682. char buf[4096];
  7683. ::recv(cli, buf, sizeof(buf), 0);
  7684. // Response with Content-Length larger than default 100MB limit
  7685. auto content_length = std::to_string(DATA_SIZE);
  7686. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7687. "Content-Length: " +
  7688. content_length +
  7689. "\r\n"
  7690. "Connection: close\r\n"
  7691. "\r\n";
  7692. ::send(cli,
  7693. #ifdef _WIN32
  7694. static_cast<const char *>(response_header.c_str()),
  7695. static_cast<int>(response_header.size()),
  7696. #else
  7697. response_header.c_str(), response_header.size(),
  7698. #endif
  7699. 0);
  7700. std::string chunk(64 * 1024, 'A');
  7701. size_t total_sent = 0;
  7702. while (total_sent < DATA_SIZE) {
  7703. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7704. auto sent = ::send(cli,
  7705. #ifdef _WIN32
  7706. static_cast<const char *>(chunk.c_str()),
  7707. static_cast<int>(to_send),
  7708. #else
  7709. chunk.c_str(), to_send,
  7710. #endif
  7711. 0);
  7712. if (sent <= 0) break;
  7713. total_sent += static_cast<size_t>(sent);
  7714. }
  7715. detail::close_socket(cli);
  7716. }
  7717. detail::close_socket(srv);
  7718. });
  7719. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7720. size_t total_received = 0;
  7721. {
  7722. Client cli("127.0.0.1", PORT + 2);
  7723. cli.set_read_timeout(10, 0);
  7724. // Do NOT call set_payload_max_length — use the default 100MB limit
  7725. auto res =
  7726. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7727. total_received += data_length;
  7728. return true;
  7729. });
  7730. ASSERT_TRUE(res);
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. }
  7733. server_thread.join();
  7734. EXPECT_EQ(total_received, DATA_SIZE)
  7735. << "With content_receiver, the client should read all " << DATA_SIZE
  7736. << " bytes despite the default 100MB payload_max_length, but only read "
  7737. << total_received << " bytes.";
  7738. }
  7739. // Verify that an explicit set_payload_max_length smaller than the response is
  7740. // enforced even when a content_receiver is used.
  7741. TEST(ClientVulnerabilityTest,
  7742. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7743. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7744. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7745. #ifndef _WIN32
  7746. signal(SIGPIPE, SIG_IGN);
  7747. #endif
  7748. auto server_thread = std::thread([] {
  7749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7750. default_socket_options(srv);
  7751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7753. sockaddr_in addr{};
  7754. addr.sin_family = AF_INET;
  7755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7757. int opt = 1;
  7758. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7759. #ifdef _WIN32
  7760. reinterpret_cast<const char *>(&opt),
  7761. #else
  7762. &opt,
  7763. #endif
  7764. sizeof(opt));
  7765. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7766. ::listen(srv, 1);
  7767. sockaddr_in cli_addr{};
  7768. socklen_t cli_len = sizeof(cli_addr);
  7769. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7770. if (cli != INVALID_SOCKET) {
  7771. char buf[4096];
  7772. ::recv(cli, buf, sizeof(buf), 0);
  7773. auto content_length = std::to_string(DATA_SIZE);
  7774. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7775. "Content-Length: " +
  7776. content_length +
  7777. "\r\n"
  7778. "Connection: close\r\n"
  7779. "\r\n";
  7780. ::send(cli,
  7781. #ifdef _WIN32
  7782. static_cast<const char *>(response_header.c_str()),
  7783. static_cast<int>(response_header.size()),
  7784. #else
  7785. response_header.c_str(), response_header.size(),
  7786. #endif
  7787. 0);
  7788. std::string chunk(64 * 1024, 'A');
  7789. size_t total_sent = 0;
  7790. while (total_sent < DATA_SIZE) {
  7791. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7792. auto sent = ::send(cli,
  7793. #ifdef _WIN32
  7794. static_cast<const char *>(chunk.c_str()),
  7795. static_cast<int>(to_send),
  7796. #else
  7797. chunk.c_str(), to_send,
  7798. #endif
  7799. 0);
  7800. if (sent <= 0) break;
  7801. total_sent += static_cast<size_t>(sent);
  7802. }
  7803. detail::close_socket(cli);
  7804. }
  7805. detail::close_socket(srv);
  7806. });
  7807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7808. size_t total_received = 0;
  7809. {
  7810. Client cli("127.0.0.1", PORT + 2);
  7811. cli.set_read_timeout(10, 0);
  7812. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7813. auto res =
  7814. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7815. total_received += data_length;
  7816. return true;
  7817. });
  7818. // Should fail because 200MB exceeds the explicit 150MB limit
  7819. EXPECT_FALSE(res);
  7820. }
  7821. server_thread.join();
  7822. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7823. << "Client with content_receiver should respect the explicit "
  7824. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7825. << total_received << " bytes.";
  7826. }
  7827. // Verify that an explicit set_payload_max_length larger than the response
  7828. // allows the content_receiver to read all data successfully.
  7829. TEST(ClientVulnerabilityTest,
  7830. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7831. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7832. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7833. #ifndef _WIN32
  7834. signal(SIGPIPE, SIG_IGN);
  7835. #endif
  7836. auto server_thread = std::thread([] {
  7837. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7838. default_socket_options(srv);
  7839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7840. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7841. sockaddr_in addr{};
  7842. addr.sin_family = AF_INET;
  7843. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7844. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7845. int opt = 1;
  7846. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7847. #ifdef _WIN32
  7848. reinterpret_cast<const char *>(&opt),
  7849. #else
  7850. &opt,
  7851. #endif
  7852. sizeof(opt));
  7853. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7854. ::listen(srv, 1);
  7855. sockaddr_in cli_addr{};
  7856. socklen_t cli_len = sizeof(cli_addr);
  7857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7858. if (cli != INVALID_SOCKET) {
  7859. char buf[4096];
  7860. ::recv(cli, buf, sizeof(buf), 0);
  7861. auto content_length = std::to_string(DATA_SIZE);
  7862. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7863. "Content-Length: " +
  7864. content_length +
  7865. "\r\n"
  7866. "Connection: close\r\n"
  7867. "\r\n";
  7868. ::send(cli,
  7869. #ifdef _WIN32
  7870. static_cast<const char *>(response_header.c_str()),
  7871. static_cast<int>(response_header.size()),
  7872. #else
  7873. response_header.c_str(), response_header.size(),
  7874. #endif
  7875. 0);
  7876. std::string chunk(64 * 1024, 'A');
  7877. size_t total_sent = 0;
  7878. while (total_sent < DATA_SIZE) {
  7879. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7880. auto sent = ::send(cli,
  7881. #ifdef _WIN32
  7882. static_cast<const char *>(chunk.c_str()),
  7883. static_cast<int>(to_send),
  7884. #else
  7885. chunk.c_str(), to_send,
  7886. #endif
  7887. 0);
  7888. if (sent <= 0) break;
  7889. total_sent += static_cast<size_t>(sent);
  7890. }
  7891. #ifdef _WIN32
  7892. ::shutdown(cli, SD_SEND);
  7893. #else
  7894. ::shutdown(cli, SHUT_WR);
  7895. #endif
  7896. char drain[1024];
  7897. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7898. detail::close_socket(cli);
  7899. }
  7900. detail::close_socket(srv);
  7901. });
  7902. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7903. size_t total_received = 0;
  7904. {
  7905. Client cli("127.0.0.1", PORT + 2);
  7906. cli.set_read_timeout(10, 0);
  7907. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7908. auto res =
  7909. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7910. total_received += data_length;
  7911. return true;
  7912. });
  7913. ASSERT_TRUE(res);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. server_thread.join();
  7917. EXPECT_EQ(total_received, DATA_SIZE)
  7918. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7919. << " bytes (larger than " << DATA_SIZE
  7920. << " bytes response), content_receiver should read all data, but only "
  7921. "read "
  7922. << total_received << " bytes.";
  7923. }
  7924. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7925. // Regression test for "zip bomb" attack on the client side: a malicious server
  7926. // sends a small gzip-compressed response that decompresses to a huge payload.
  7927. // The client must enforce payload_max_length on the decompressed size.
  7928. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7929. constexpr size_t DECOMPRESSED_SIZE =
  7930. 10 * 1024 * 1024; // 10MB after decompression
  7931. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7932. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7933. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7934. std::string compressed;
  7935. {
  7936. httplib::detail::gzip_compressor compressor;
  7937. bool ok =
  7938. compressor.compress(uncompressed.data(), uncompressed.size(),
  7939. /*last=*/true, [&](const char *buf, size_t len) {
  7940. compressed.append(buf, len);
  7941. return true;
  7942. });
  7943. ASSERT_TRUE(ok);
  7944. }
  7945. // Sanity: compressed data should be much smaller than the decompressed size
  7946. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7947. #ifndef _WIN32
  7948. signal(SIGPIPE, SIG_IGN);
  7949. #endif
  7950. // Set up the listening socket in the main thread so the server is guaranteed
  7951. // to be ready before the client connects (eliminates race condition).
  7952. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7953. default_socket_options(srv);
  7954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7955. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7956. sockaddr_in addr{};
  7957. addr.sin_family = AF_INET;
  7958. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7959. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7960. int opt = 1;
  7961. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7962. #ifdef _WIN32
  7963. reinterpret_cast<const char *>(&opt),
  7964. #else
  7965. &opt,
  7966. #endif
  7967. sizeof(opt));
  7968. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7969. ASSERT_EQ(0, ::listen(srv, 1));
  7970. auto server_thread = std::thread([&compressed, srv] {
  7971. sockaddr_in cli_addr{};
  7972. socklen_t cli_len = sizeof(cli_addr);
  7973. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7974. if (cli != INVALID_SOCKET) {
  7975. // Read the full HTTP request (until \r\n\r\n)
  7976. char buf[4096];
  7977. size_t total = 0;
  7978. while (total < sizeof(buf)) {
  7979. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7980. if (n <= 0) break;
  7981. total += static_cast<size_t>(n);
  7982. // Check for end of headers
  7983. if (total >= 4) {
  7984. std::string req(buf, total);
  7985. if (req.find("\r\n\r\n") != std::string::npos) break;
  7986. }
  7987. }
  7988. // Malicious response: gzip-compressed body, no Content-Length
  7989. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7990. "Content-Encoding: gzip\r\n"
  7991. "Connection: close\r\n"
  7992. "\r\n";
  7993. ::send(cli,
  7994. #ifdef _WIN32
  7995. static_cast<const char *>(response_header.c_str()),
  7996. static_cast<int>(response_header.size()),
  7997. #else
  7998. response_header.c_str(), response_header.size(),
  7999. #endif
  8000. 0);
  8001. // Send the compressed payload (small on the wire, huge when decompressed)
  8002. size_t total_sent = 0;
  8003. while (total_sent < compressed.size()) {
  8004. auto to_send = std::min(compressed.size() - total_sent,
  8005. static_cast<size_t>(64 * 1024));
  8006. auto sent =
  8007. ::send(cli,
  8008. #ifdef _WIN32
  8009. static_cast<const char *>(compressed.c_str() + total_sent),
  8010. static_cast<int>(to_send),
  8011. #else
  8012. compressed.c_str() + total_sent, to_send,
  8013. #endif
  8014. 0);
  8015. if (sent <= 0) break;
  8016. total_sent += static_cast<size_t>(sent);
  8017. }
  8018. detail::close_socket(cli);
  8019. }
  8020. });
  8021. auto se = detail::scope_exit([&] {
  8022. detail::close_socket(srv);
  8023. server_thread.join();
  8024. });
  8025. size_t total_decompressed = 0;
  8026. {
  8027. Client cli("127.0.0.1", PORT + 3);
  8028. cli.set_read_timeout(5, 0);
  8029. cli.set_decompress(true);
  8030. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8031. auto stream = cli.open_stream("GET", "/zipbomb");
  8032. ASSERT_TRUE(stream.is_valid());
  8033. char buffer[64 * 1024];
  8034. ssize_t n;
  8035. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8036. total_decompressed += static_cast<size_t>(n);
  8037. }
  8038. }
  8039. // The decompressed size must be capped by payload_max_length. Without
  8040. // protection, the client would decompress the full 10MB from a tiny
  8041. // compressed payload, enabling a zip bomb DoS attack.
  8042. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8043. << "Client decompressed " << total_decompressed
  8044. << " bytes from a gzip response. The decompressed size should be "
  8045. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8046. }
  8047. #endif
  8048. TEST(HostAndPortPropertiesTest, NoSSL) {
  8049. httplib::Client cli("www.google.com", 1234);
  8050. ASSERT_EQ("www.google.com", cli.host());
  8051. ASSERT_EQ(1234, cli.port());
  8052. }
  8053. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8054. httplib::Client cli("www.google.com:1234");
  8055. ASSERT_EQ("www.google.com", cli.host());
  8056. ASSERT_EQ(1234, cli.port());
  8057. }
  8058. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8059. // Port number that overflows int — should not crash, client becomes invalid
  8060. httplib::Client cli("http://www.google.com:99999999999999999999");
  8061. ASSERT_FALSE(cli.is_valid());
  8062. }
  8063. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8064. // Port 99999 exceeds valid range (1-65535) — should not crash
  8065. httplib::Client cli("http://www.google.com:99999");
  8066. ASSERT_FALSE(cli.is_valid());
  8067. }
  8068. #ifdef CPPHTTPLIB_SSL_ENABLED
  8069. TEST(HostAndPortPropertiesTest, SSL) {
  8070. httplib::SSLClient cli("www.google.com");
  8071. ASSERT_EQ("www.google.com", cli.host());
  8072. ASSERT_EQ(443, cli.port());
  8073. }
  8074. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8075. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8076. std::string cert;
  8077. read_file(CA_CERT_FILE, cert);
  8078. httplib::SSLClient httplib_client("www.google.com");
  8079. // Load CA store first time
  8080. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8081. // Load CA store second time (update)
  8082. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8083. // Verify client is still valid and can make connections
  8084. httplib_client.enable_server_certificate_verification(true);
  8085. auto res = httplib_client.Get("/");
  8086. ASSERT_TRUE(res);
  8087. // Google may return 200 or 301 depending on various factors
  8088. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8089. res->status == StatusCode::MovedPermanently_301);
  8090. }
  8091. TEST(SSLClientTest, ServerNameIndication_Online) {
  8092. auto host = "httpbingo.org";
  8093. auto path = std::string{"/get"};
  8094. SSLClient cli(host, 443);
  8095. auto res = cli.Get(path);
  8096. ASSERT_TRUE(res);
  8097. ASSERT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8100. // Use a site that will cause SSL verification failure due to self-signed cert
  8101. SSLClient cli("self-signed.badssl.com", 443);
  8102. cli.enable_server_certificate_verification(true);
  8103. auto res = cli.Get("/");
  8104. ASSERT_TRUE(!res);
  8105. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8106. // Verify backend error is captured for SSLServerVerification
  8107. // This occurs when certificate verification fails
  8108. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8109. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8110. EXPECT_NE(0UL, res.ssl_backend_error());
  8111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8112. // For OpenSSL, ssl_error is 0 for verification errors
  8113. EXPECT_EQ(0, res.ssl_error());
  8114. #if !defined(_WIN32) || \
  8115. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8116. // On non-Windows or when Windows Schannel is disabled, the error comes
  8117. // from OpenSSL's verification
  8118. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8119. res.ssl_backend_error());
  8120. #endif
  8121. #endif
  8122. }
  8123. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8124. // Use a site where hostname doesn't match the certificate
  8125. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8126. SSLClient cli("wrong.host.badssl.com", 443);
  8127. cli.enable_server_certificate_verification(true);
  8128. cli.enable_server_hostname_verification(true);
  8129. auto res = cli.Get("/");
  8130. ASSERT_TRUE(!res);
  8131. // The error type depends on when hostname verification occurs:
  8132. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8133. // - Mbed TLS: SSLServerVerification (during handshake)
  8134. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8135. res.error() == Error::SSLServerVerification);
  8136. // Verify backend error is captured for hostname verification failure
  8137. EXPECT_NE(0UL, res.ssl_backend_error());
  8138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8139. // For OpenSSL, ssl_error is 0 for verification errors
  8140. EXPECT_EQ(0, res.ssl_error());
  8141. #if !defined(_WIN32) || \
  8142. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8143. // On non-Windows or when Windows Schannel is disabled, the error comes
  8144. // from OpenSSL's hostname verification
  8145. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8146. res.ssl_backend_error());
  8147. #endif
  8148. #endif
  8149. }
  8150. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8151. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8152. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8153. SSLClient cli("www.google.com", 443);
  8154. cli.enable_server_certificate_verification(true);
  8155. auto res = cli.Get("/");
  8156. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8157. }
  8158. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8159. SSLClient cli("www.google.com", 443);
  8160. cli.enable_server_certificate_verification(true);
  8161. cli.enable_windows_certificate_verification(false);
  8162. auto res = cli.Get("/");
  8163. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8164. }
  8165. #endif
  8166. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8167. Client cli("https://google.com");
  8168. auto res = cli.Get("/");
  8169. ASSERT_TRUE(res);
  8170. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8171. }
  8172. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8173. SSLClient cli("google.com");
  8174. cli.set_ca_cert_path(CA_CERT_FILE);
  8175. auto res = cli.Get("/");
  8176. ASSERT_TRUE(res);
  8177. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8178. }
  8179. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8180. SSLClient cli("google.com");
  8181. cli.enable_server_certificate_verification(true);
  8182. cli.set_ca_cert_path("hello");
  8183. auto res = cli.Get("/");
  8184. ASSERT_TRUE(!res);
  8185. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8186. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8187. // should be set
  8188. EXPECT_EQ(0, res.ssl_error());
  8189. // Verify backend error is captured for SSLLoadingCerts
  8190. // This error occurs when loading CA certificates fails
  8191. EXPECT_NE(0UL, res.ssl_backend_error());
  8192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8193. // OpenSSL specific error codes:
  8194. // > openssl errstr 0x80000002
  8195. // error:80000002:system library::No such file or directory
  8196. // > openssl errstr 0xA000126
  8197. // error:0A000126:SSL routines::unexpected eof while reading
  8198. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8199. res.ssl_backend_error() == 0xA000126);
  8200. #endif
  8201. }
  8202. TEST(SSLClientTest, ServerCertificateVerification4) {
  8203. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8204. ASSERT_TRUE(svr.is_valid());
  8205. svr.Get("/test", [&](const Request &, Response &res) {
  8206. res.set_content("test", "text/plain");
  8207. svr.stop();
  8208. ASSERT_TRUE(true);
  8209. });
  8210. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8211. auto se = detail::scope_exit([&] {
  8212. t.join();
  8213. ASSERT_FALSE(svr.is_running());
  8214. });
  8215. svr.wait_until_ready();
  8216. SSLClient cli("127.0.0.1", PORT);
  8217. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8218. cli.enable_server_certificate_verification(true);
  8219. cli.set_connection_timeout(30);
  8220. auto res = cli.Get("/test");
  8221. ASSERT_TRUE(res);
  8222. ASSERT_EQ(StatusCode::OK_200, res->status);
  8223. }
  8224. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8225. std::string cert;
  8226. read_file(CA_CERT_FILE, cert);
  8227. SSLClient cli("google.com");
  8228. cli.load_ca_cert_store(cert.data(), cert.size());
  8229. const auto res = cli.Get("/");
  8230. ASSERT_TRUE(res);
  8231. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8232. }
  8233. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8234. // clang-format off
  8235. static constexpr char cert[] =
  8236. "GlobalSign Root CA\n"
  8237. "==================\n"
  8238. "-----BEGIN CERTIFICATE-----\n"
  8239. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8240. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8241. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8242. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8243. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8244. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8245. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8246. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8247. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8248. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8249. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8250. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8251. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8252. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8253. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8254. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8255. "-----END CERTIFICATE-----\n";
  8256. // clang-format on
  8257. SSLClient cli("google.com");
  8258. cli.load_ca_cert_store(cert, sizeof(cert));
  8259. const auto res = cli.Get("/");
  8260. ASSERT_TRUE(res);
  8261. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8262. }
  8263. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8264. SSLClient cli("www.youtube.com");
  8265. cli.set_ca_cert_path(CA_CERT_FILE);
  8266. cli.enable_server_certificate_verification(true);
  8267. cli.set_follow_location(true);
  8268. auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8273. SSLClient cli("wWw.YouTube.Com");
  8274. cli.set_ca_cert_path(CA_CERT_FILE);
  8275. cli.enable_server_certificate_verification(true);
  8276. cli.enable_server_hostname_verification(true);
  8277. cli.set_follow_location(true);
  8278. auto res = cli.Get("/");
  8279. ASSERT_TRUE(res);
  8280. ASSERT_EQ(StatusCode::OK_200, res->status);
  8281. }
  8282. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8283. SSLClient cli("gOoGlE.COm");
  8284. cli.enable_server_certificate_verification(true);
  8285. cli.enable_server_hostname_verification(true);
  8286. cli.set_follow_location(true);
  8287. auto res = cli.Get("/");
  8288. ASSERT_TRUE(res);
  8289. ASSERT_EQ(StatusCode::OK_200, res->status);
  8290. }
  8291. TEST(SSLClientTest, Issue2004_Online) {
  8292. Client client("https://google.com");
  8293. client.set_follow_location(true);
  8294. auto res = client.Get("/");
  8295. ASSERT_TRUE(res);
  8296. ASSERT_EQ(StatusCode::OK_200, res->status);
  8297. auto body = res->body;
  8298. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8299. }
  8300. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8301. // Create SSLClient with invalid cert/key to make is_valid() return false
  8302. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8303. "nonexistent_key.pem");
  8304. // is_valid() should be false due to cert loading failure
  8305. ASSERT_FALSE(cli.is_valid());
  8306. auto res = cli.Get("/");
  8307. ASSERT_FALSE(res);
  8308. EXPECT_EQ(Error::SSLConnection, res.error());
  8309. }
  8310. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8311. // Test for Issue #2251: SSL error not properly reported when client cert
  8312. // and key paths are swapped or mismatched
  8313. // This simulates the scenario where user accidentally swaps the cert and key
  8314. // files
  8315. // Using client cert file as private key and vice versa (completely wrong)
  8316. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8317. // Should fail validation due to cert/key mismatch
  8318. ASSERT_FALSE(cli.is_valid());
  8319. // Attempt to make a request should fail with proper error
  8320. auto res = cli.Get("/");
  8321. ASSERT_FALSE(res);
  8322. EXPECT_EQ(Error::SSLConnection, res.error());
  8323. // SSL error should be recorded in the Result object (this is the key fix for
  8324. // Issue #2251)
  8325. auto backend_error = res.ssl_backend_error();
  8326. EXPECT_NE(0u, backend_error);
  8327. }
  8328. // Tests cert/key mismatch detection at the TLS context level
  8329. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8330. // Test that using mismatched cert/key causes connection failure.
  8331. // We verify this at the SSLClient level rather than through internal
  8332. // TLS API functions.
  8333. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8334. cli.enable_server_certificate_verification(false);
  8335. cli.set_connection_timeout(2);
  8336. // The mismatch should cause a connection or handshake error
  8337. auto res = cli.Get("/test");
  8338. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8339. // Either way, the request should fail
  8340. EXPECT_FALSE(res);
  8341. }
  8342. #endif
  8343. #if 0
  8344. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8345. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8346. ASSERT_TRUE(cli != nullptr);
  8347. cli->set_address_family(AF_INET6);
  8348. cli->set_interface("en0");
  8349. auto res = cli->Get("/get");
  8350. ASSERT_TRUE(res);
  8351. ASSERT_EQ(StatusCode::OK_200, res->status);
  8352. }
  8353. #endif
  8354. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8355. #ifdef CPPHTTPLIB_SSL_ENABLED
  8356. void ClientCertPresent(
  8357. const std::string &client_cert_file,
  8358. const std::string &client_private_key_file,
  8359. const std::string &client_encrypted_private_key_pass = std::string()) {
  8360. using namespace httplib::tls;
  8361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8362. CLIENT_CA_CERT_DIR);
  8363. ASSERT_TRUE(svr.is_valid());
  8364. svr.Get("/test", [&](const Request &req, Response &res) {
  8365. res.set_content("test", "text/plain");
  8366. auto cert = req.peer_cert();
  8367. ASSERT_TRUE(static_cast<bool>(cert));
  8368. std::string common_name = cert.subject_cn();
  8369. EXPECT_EQ("Common Name", common_name);
  8370. });
  8371. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8372. auto se = detail::scope_exit([&] {
  8373. svr.stop();
  8374. t.join();
  8375. ASSERT_FALSE(svr.is_running());
  8376. });
  8377. svr.wait_until_ready();
  8378. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8379. client_encrypted_private_key_pass);
  8380. cli.enable_server_certificate_verification(false);
  8381. cli.set_connection_timeout(30);
  8382. auto res = cli.Get("/test");
  8383. ASSERT_TRUE(res);
  8384. ASSERT_EQ(StatusCode::OK_200, res->status);
  8385. }
  8386. TEST(SSLClientServerTest, ClientCertPresent) {
  8387. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8388. }
  8389. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8390. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8391. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8392. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8393. }
  8394. // PEM memory-based constructor tests (works with all TLS backends)
  8395. void PemMemoryClientCertPresent(
  8396. const std::string &client_cert_file,
  8397. const std::string &client_private_key_file,
  8398. const std::string &client_encrypted_private_key_pass = std::string()) {
  8399. // Read PEM files into memory
  8400. std::string server_cert_pem, server_key_pem;
  8401. std::string client_ca_pem;
  8402. std::string client_cert_pem, client_key_pem;
  8403. read_file(SERVER_CERT_FILE, server_cert_pem);
  8404. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8405. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8406. read_file(client_cert_file, client_cert_pem);
  8407. read_file(client_private_key_file, client_key_pem);
  8408. // Create server with PEM memory
  8409. SSLServer::PemMemory server_pem = {
  8410. server_cert_pem.c_str(),
  8411. server_cert_pem.size(),
  8412. server_key_pem.c_str(),
  8413. server_key_pem.size(),
  8414. client_ca_pem.c_str(),
  8415. client_ca_pem.size(),
  8416. nullptr // no password for server key
  8417. };
  8418. SSLServer svr(server_pem);
  8419. ASSERT_TRUE(svr.is_valid());
  8420. svr.Get("/test", [&](const Request &, Response &res) {
  8421. res.set_content("test", "text/plain");
  8422. });
  8423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8424. auto se = detail::scope_exit([&] {
  8425. svr.stop();
  8426. t.join();
  8427. ASSERT_FALSE(svr.is_running());
  8428. });
  8429. svr.wait_until_ready();
  8430. // Create client with PEM memory
  8431. const char *password = client_encrypted_private_key_pass.empty()
  8432. ? nullptr
  8433. : client_encrypted_private_key_pass.c_str();
  8434. SSLClient::PemMemory client_pem = {
  8435. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8436. client_key_pem.size(), password};
  8437. SSLClient cli(HOST, PORT, client_pem);
  8438. cli.enable_server_certificate_verification(false);
  8439. cli.set_connection_timeout(30);
  8440. auto res = cli.Get("/test");
  8441. ASSERT_TRUE(res);
  8442. ASSERT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8445. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8446. }
  8447. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8448. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8449. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8450. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8451. }
  8452. TEST(SSLClientServerTest, ClientCertMissing) {
  8453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8454. CLIENT_CA_CERT_DIR);
  8455. ASSERT_TRUE(svr.is_valid());
  8456. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8458. auto se = detail::scope_exit([&] {
  8459. svr.stop();
  8460. t.join();
  8461. ASSERT_FALSE(svr.is_running());
  8462. });
  8463. svr.wait_until_ready();
  8464. SSLClient cli(HOST, PORT);
  8465. cli.set_connection_timeout(30);
  8466. auto res = cli.Get("/test");
  8467. ASSERT_TRUE(!res);
  8468. // When client cert is missing and server requires it, connection fails
  8469. // Error type depends on backend implementation
  8470. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8471. res.error() == Error::SSLConnection);
  8472. // Verify backend error is captured
  8473. // Note: This test may have different error codes depending on the exact
  8474. // verification failure
  8475. EXPECT_NE(0UL, res.ssl_backend_error());
  8476. }
  8477. TEST(SSLClientServerTest, TrustDirOptional) {
  8478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &, Response &res) {
  8481. res.set_content("test", "text/plain");
  8482. });
  8483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8484. auto se = detail::scope_exit([&] {
  8485. svr.stop();
  8486. t.join();
  8487. ASSERT_FALSE(svr.is_running());
  8488. });
  8489. svr.wait_until_ready();
  8490. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8491. cli.enable_server_certificate_verification(false);
  8492. cli.set_connection_timeout(30);
  8493. auto res = cli.Get("/test");
  8494. ASSERT_TRUE(res);
  8495. ASSERT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8498. class NoListenSSLServer : public SSLServer {
  8499. public:
  8500. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8501. const char *client_ca_cert_file_path,
  8502. const char *client_ca_cert_dir_path = nullptr)
  8503. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8504. client_ca_cert_dir_path),
  8505. stop_(false) {}
  8506. std::atomic_bool stop_;
  8507. private:
  8508. bool process_and_close_socket(socket_t /*sock*/) override {
  8509. // Don't create SSL context
  8510. while (!stop_.load()) {
  8511. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8512. }
  8513. return true;
  8514. }
  8515. };
  8516. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8517. CLIENT_CA_CERT_FILE);
  8518. ASSERT_TRUE(svr.is_valid());
  8519. svr.Get("/test", [&](const Request &, Response &res) {
  8520. res.set_content("test", "text/plain");
  8521. });
  8522. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8523. auto se = detail::scope_exit([&] {
  8524. svr.stop_ = true;
  8525. svr.stop();
  8526. t.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. });
  8529. svr.wait_until_ready();
  8530. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8531. cli.enable_server_certificate_verification(false);
  8532. cli.set_connection_timeout(1);
  8533. auto res = cli.Get("/test");
  8534. ASSERT_TRUE(!res);
  8535. EXPECT_EQ(Error::SSLConnection, res.error());
  8536. // Timeout results in WantRead error code (maps to backend-specific value)
  8537. EXPECT_NE(0, res.ssl_error());
  8538. }
  8539. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8540. // Test SSLServer with client certificate verification using the standard
  8541. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8543. CLIENT_CA_CERT_DIR);
  8544. ASSERT_TRUE(svr.is_valid());
  8545. svr.Get("/test", [&](const Request &req, Response &res) {
  8546. res.set_content("test", "text/plain");
  8547. auto cert = req.peer_cert();
  8548. ASSERT_TRUE(static_cast<bool>(cert));
  8549. auto common_name = cert.subject_cn();
  8550. EXPECT_EQ("Common Name", common_name);
  8551. });
  8552. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8553. auto se = detail::scope_exit([&] {
  8554. svr.stop();
  8555. t.join();
  8556. ASSERT_FALSE(svr.is_running());
  8557. });
  8558. svr.wait_until_ready();
  8559. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8560. cli.enable_server_certificate_verification(false);
  8561. cli.set_connection_timeout(30);
  8562. auto res = cli.Get("/test");
  8563. ASSERT_TRUE(res);
  8564. ASSERT_EQ(StatusCode::OK_200, res->status);
  8565. }
  8566. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8567. // Verifies that wildcard matching and exact matching work consistently
  8568. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8569. using namespace httplib::tls;
  8570. // We need a running server to test against
  8571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8572. ASSERT_TRUE(svr.is_valid());
  8573. svr.Get("/test", [](const Request &, Response &res) {
  8574. res.set_content("ok", "text/plain");
  8575. });
  8576. thread t([&]() { svr.listen(HOST, PORT); });
  8577. auto se = detail::scope_exit([&] {
  8578. svr.stop();
  8579. t.join();
  8580. });
  8581. svr.wait_until_ready();
  8582. bool verify_callback_called = false;
  8583. bool verify_result_wrong = false;
  8584. SSLClient cli(HOST, PORT);
  8585. cli.enable_server_certificate_verification(true);
  8586. cli.set_ca_cert_path(CA_CERT_FILE);
  8587. cli.set_connection_timeout(5);
  8588. // Note: Test certificate has CN="Common Name", not "localhost"
  8589. bool verify_result_cn = false;
  8590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8591. verify_callback_called = true;
  8592. if (!ctx.cert) return false;
  8593. // Test 1: "Common Name" should match (our test server cert CN)
  8594. verify_result_cn = ctx.check_hostname("Common Name");
  8595. // Test 2: wrong hostname should not match
  8596. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8597. return true; // Accept for the purpose of this test
  8598. });
  8599. auto res = cli.Get("/test");
  8600. // The request may succeed or fail depending on cert configuration
  8601. // but the callback should have been called
  8602. ASSERT_TRUE(verify_callback_called)
  8603. << "Verify callback should have been called";
  8604. // CN="Common Name" should match our test certificate
  8605. EXPECT_TRUE(verify_result_cn)
  8606. << "verify_hostname should match 'Common Name' (certificate CN)";
  8607. // Wrong hostname should not match
  8608. EXPECT_FALSE(verify_result_wrong)
  8609. << "verify_hostname should not match 'wronghost.example.com'";
  8610. }
  8611. #endif
  8612. // mbedTLS-specific callback constructor test
  8613. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8614. #ifdef CPPHTTPLIB_SSL_ENABLED
  8615. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8617. ASSERT_TRUE(svr.is_valid());
  8618. // Set up a handler to verify client certificate is present
  8619. bool client_cert_verified = false;
  8620. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8621. // Verify that client certificate was provided
  8622. client_cert_verified = true;
  8623. res.set_content("success", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. ASSERT_FALSE(svr.is_running());
  8630. });
  8631. svr.wait_until_ready();
  8632. // Client with certificate
  8633. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8634. cli.enable_server_certificate_verification(false);
  8635. cli.set_connection_timeout(30);
  8636. auto res = cli.Get("/test");
  8637. ASSERT_TRUE(res);
  8638. ASSERT_EQ(StatusCode::OK_200, res->status);
  8639. ASSERT_TRUE(client_cert_verified);
  8640. EXPECT_EQ("success", res->body);
  8641. }
  8642. #endif
  8643. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8644. // backends
  8645. #ifdef CPPHTTPLIB_SSL_ENABLED
  8646. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8647. using namespace httplib::tls;
  8648. // Test that when client CA cert file is provided,
  8649. // the server properly requests and validates client certificates
  8650. // Create a server with client authentication
  8651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8652. ASSERT_TRUE(svr.is_valid());
  8653. bool handler_called = false;
  8654. svr.Get("/test", [&](const Request &req, Response &res) {
  8655. handler_called = true;
  8656. // Verify that a client certificate was provided
  8657. auto cert = req.peer_cert();
  8658. ASSERT_TRUE(static_cast<bool>(cert));
  8659. // Get the issuer name
  8660. std::string issuer_str = cert.issuer_name();
  8661. ASSERT_FALSE(issuer_str.empty());
  8662. // The client certificate should be issued by our test CA
  8663. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8664. res.set_content("authenticated", "text/plain");
  8665. });
  8666. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. t.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. // Connect with a client certificate issued by the CA
  8674. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8675. cli.enable_server_certificate_verification(false);
  8676. cli.set_connection_timeout(30);
  8677. auto res = cli.Get("/test");
  8678. ASSERT_TRUE(res);
  8679. ASSERT_EQ(StatusCode::OK_200, res->status);
  8680. ASSERT_TRUE(handler_called);
  8681. EXPECT_EQ("authenticated", res->body);
  8682. }
  8683. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8684. using namespace httplib::tls;
  8685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8686. ASSERT_TRUE(svr.is_valid());
  8687. svr.Get("/test", [](const Request &, Response &res) {
  8688. res.set_content("ok", "text/plain");
  8689. });
  8690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. t.join();
  8694. });
  8695. svr.wait_until_ready();
  8696. SSLClient cli(HOST, PORT);
  8697. cli.enable_server_certificate_verification(false);
  8698. cli.set_connection_timeout(30);
  8699. bool cert_checked = false;
  8700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8701. if (ctx.cert) {
  8702. auto sans = ctx.sans();
  8703. // Test certificate may or may not have SANs - just verify the API
  8704. // works If SANs exist, verify the types are valid
  8705. for (const auto &san : sans) {
  8706. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8707. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8708. san.type == SanType::OTHER);
  8709. EXPECT_FALSE(san.value.empty());
  8710. }
  8711. cert_checked = true;
  8712. }
  8713. return true;
  8714. });
  8715. auto res = cli.Get("/test");
  8716. ASSERT_TRUE(res);
  8717. EXPECT_TRUE(cert_checked);
  8718. }
  8719. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8720. using namespace httplib::tls;
  8721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8722. ASSERT_TRUE(svr.is_valid());
  8723. svr.Get("/test", [](const Request &, Response &res) {
  8724. res.set_content("ok", "text/plain");
  8725. });
  8726. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8727. auto se = detail::scope_exit([&] {
  8728. svr.stop();
  8729. t.join();
  8730. });
  8731. svr.wait_until_ready();
  8732. SSLClient cli(HOST, PORT);
  8733. cli.enable_server_certificate_verification(false);
  8734. cli.set_connection_timeout(30);
  8735. bool validity_checked = false;
  8736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8737. if (ctx.cert) {
  8738. time_t not_before = 0, not_after = 0;
  8739. bool result = ctx.validity(not_before, not_after);
  8740. EXPECT_TRUE(result);
  8741. // Verify that not_before < now < not_after for a valid cert
  8742. time_t now = time(nullptr);
  8743. EXPECT_LT(not_before, now);
  8744. EXPECT_GT(not_after, now);
  8745. validity_checked = true;
  8746. }
  8747. return true;
  8748. });
  8749. auto res = cli.Get("/test");
  8750. ASSERT_TRUE(res);
  8751. EXPECT_TRUE(validity_checked);
  8752. }
  8753. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8754. using namespace httplib::tls;
  8755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8756. ASSERT_TRUE(svr.is_valid());
  8757. svr.Get("/test", [](const Request &, Response &res) {
  8758. res.set_content("ok", "text/plain");
  8759. });
  8760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8761. auto se = detail::scope_exit([&] {
  8762. svr.stop();
  8763. t.join();
  8764. });
  8765. svr.wait_until_ready();
  8766. SSLClient cli(HOST, PORT);
  8767. cli.enable_server_certificate_verification(false);
  8768. cli.set_connection_timeout(30);
  8769. bool serial_checked = false;
  8770. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8771. if (ctx.cert) {
  8772. std::string serial = ctx.serial();
  8773. EXPECT_FALSE(serial.empty());
  8774. // Serial should be a hex string
  8775. for (char c : serial) {
  8776. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8777. (c >= 'a' && c <= 'f'));
  8778. }
  8779. serial_checked = true;
  8780. }
  8781. return true;
  8782. });
  8783. auto res = cli.Get("/test");
  8784. ASSERT_TRUE(res);
  8785. EXPECT_TRUE(serial_checked);
  8786. }
  8787. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8788. // Test 1: Valid CA file - no error should be recorded
  8789. {
  8790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8791. CLIENT_CA_CERT_FILE);
  8792. ASSERT_TRUE(svr.is_valid());
  8793. // With valid setup, last_ssl_error should be 0
  8794. EXPECT_EQ(0, svr.ssl_last_error());
  8795. }
  8796. // Test 2: Invalid CA file content
  8797. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8798. {
  8799. // Create a temporary file with completely invalid content
  8800. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8801. {
  8802. std::ofstream ofs(temp_invalid_ca);
  8803. ofs << "This is not a certificate file at all\n";
  8804. ofs << "Just plain text content\n";
  8805. }
  8806. // Create server with invalid CA file
  8807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8808. // Clean up temporary file
  8809. std::remove(temp_invalid_ca);
  8810. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8811. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8812. // Note: SSL_CTX_load_verify_locations typically fails first,
  8813. // but our error handling code path is still exercised
  8814. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8815. }
  8816. }
  8817. TEST(VerifyCallbackTest, VerifyContextFields) {
  8818. using namespace httplib::tls;
  8819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8820. ASSERT_TRUE(svr.is_valid());
  8821. svr.Get("/test", [](const Request &, Response &res) {
  8822. res.set_content("ok", "text/plain");
  8823. });
  8824. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. t.join();
  8828. });
  8829. svr.wait_until_ready();
  8830. SSLClient cli(HOST, PORT);
  8831. cli.enable_server_certificate_verification(false);
  8832. cli.set_connection_timeout(30);
  8833. int callback_count = 0;
  8834. bool saw_leaf_cert = false;
  8835. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8836. if (ctx.cert) {
  8837. callback_count++;
  8838. // We should see at least one certificate (the leaf)
  8839. std::string cn = ctx.subject_cn();
  8840. if (!cn.empty()) { saw_leaf_cert = true; }
  8841. // Verify context fields are populated
  8842. EXPECT_NE(ctx.session, nullptr);
  8843. EXPECT_GE(ctx.depth, 0);
  8844. }
  8845. return true;
  8846. });
  8847. auto res = cli.Get("/test");
  8848. ASSERT_TRUE(res);
  8849. EXPECT_GT(callback_count, 0);
  8850. EXPECT_TRUE(saw_leaf_cert);
  8851. }
  8852. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8853. using httplib::tls::TlsError;
  8854. // Test that verify_error_to_string returns empty for success
  8855. std::string success_str = TlsError::verify_error_to_string(0);
  8856. EXPECT_TRUE(success_str.empty());
  8857. // Test that verify_error_to_string returns non-empty for error codes
  8858. // Using a common error code (certificate expired)
  8859. std::string error_str =
  8860. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8861. EXPECT_FALSE(error_str.empty());
  8862. }
  8863. TEST(SessionVerifierTest, CertificateAccepted) {
  8864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8865. ASSERT_TRUE(svr.is_valid());
  8866. svr.Get("/test", [](const Request &, Response &res) {
  8867. res.set_content("ok", "text/plain");
  8868. });
  8869. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8870. auto se = detail::scope_exit([&] {
  8871. svr.stop();
  8872. t.join();
  8873. });
  8874. svr.wait_until_ready();
  8875. SSLClient cli(HOST, PORT);
  8876. cli.enable_server_certificate_verification(false);
  8877. cli.set_connection_timeout(30);
  8878. bool callback_called = false;
  8879. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8880. EXPECT_NE(session, nullptr);
  8881. callback_called = true;
  8882. return SSLVerifierResponse::CertificateAccepted;
  8883. });
  8884. auto res = cli.Get("/test");
  8885. ASSERT_TRUE(res);
  8886. EXPECT_EQ(200, res->status);
  8887. EXPECT_TRUE(callback_called);
  8888. }
  8889. TEST(SessionVerifierTest, CertificateRejected) {
  8890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8891. ASSERT_TRUE(svr.is_valid());
  8892. svr.Get("/test", [](const Request &, Response &res) {
  8893. res.set_content("ok", "text/plain");
  8894. });
  8895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8896. auto se = detail::scope_exit([&] {
  8897. svr.stop();
  8898. t.join();
  8899. });
  8900. svr.wait_until_ready();
  8901. SSLClient cli(HOST, PORT);
  8902. cli.enable_server_certificate_verification(false);
  8903. cli.set_connection_timeout(30);
  8904. bool callback_called = false;
  8905. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8906. EXPECT_NE(session, nullptr);
  8907. callback_called = true;
  8908. return SSLVerifierResponse::CertificateRejected;
  8909. });
  8910. auto res = cli.Get("/test");
  8911. EXPECT_FALSE(res);
  8912. EXPECT_TRUE(callback_called);
  8913. }
  8914. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8916. ASSERT_TRUE(svr.is_valid());
  8917. svr.Get("/test", [](const Request &, Response &res) {
  8918. res.set_content("ok", "text/plain");
  8919. });
  8920. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8921. auto se = detail::scope_exit([&] {
  8922. svr.stop();
  8923. t.join();
  8924. });
  8925. svr.wait_until_ready();
  8926. // NoDecisionMade with verification disabled should succeed (no default check)
  8927. SSLClient cli(HOST, PORT);
  8928. cli.enable_server_certificate_verification(false);
  8929. cli.set_connection_timeout(30);
  8930. bool callback_called = false;
  8931. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8932. EXPECT_NE(session, nullptr);
  8933. callback_called = true;
  8934. return SSLVerifierResponse::NoDecisionMade;
  8935. });
  8936. auto res = cli.Get("/test");
  8937. ASSERT_TRUE(res);
  8938. EXPECT_EQ(200, res->status);
  8939. EXPECT_TRUE(callback_called);
  8940. }
  8941. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8943. ASSERT_TRUE(svr.is_valid());
  8944. svr.Get("/test", [](const Request &, Response &res) {
  8945. res.set_content("ok", "text/plain");
  8946. });
  8947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. t.join();
  8951. });
  8952. svr.wait_until_ready();
  8953. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8954. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8955. // so we only check that the request fails, not whether the callback was
  8956. // called.
  8957. SSLClient cli(HOST, PORT);
  8958. cli.enable_server_certificate_verification(true);
  8959. cli.set_connection_timeout(30);
  8960. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8961. EXPECT_NE(session, nullptr);
  8962. return SSLVerifierResponse::NoDecisionMade;
  8963. });
  8964. auto res = cli.Get("/test");
  8965. EXPECT_FALSE(res);
  8966. }
  8967. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8968. // Test SSL server using PemMemory constructor with client CA certificates
  8969. // Read PEM files
  8970. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8971. read_file(SERVER_CERT_FILE, server_cert_pem);
  8972. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8973. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8974. // Create SSLServer with PemMemory constructor including client CA
  8975. SSLServer::PemMemory server_pem = {
  8976. server_cert_pem.c_str(),
  8977. server_cert_pem.size(),
  8978. server_key_pem.c_str(),
  8979. server_key_pem.size(),
  8980. client_ca_pem.c_str(),
  8981. client_ca_pem.size(),
  8982. nullptr // no password for server key
  8983. };
  8984. SSLServer svr(server_pem);
  8985. ASSERT_TRUE(svr.is_valid());
  8986. // No SSL error should be recorded for valid setup
  8987. EXPECT_EQ(0, svr.ssl_last_error());
  8988. // Set up server endpoints
  8989. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8990. res.set_content("ok", "text/plain");
  8991. });
  8992. // Start server in a thread
  8993. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8994. svr.wait_until_ready();
  8995. // Connect with client certificate (using constructor with paths)
  8996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8997. cli.enable_server_certificate_verification(false);
  8998. auto res = cli.Get("/test-pem-ca");
  8999. ASSERT_TRUE(res);
  9000. EXPECT_EQ(200, res->status);
  9001. EXPECT_EQ("ok", res->body);
  9002. svr.stop();
  9003. server_thread.join();
  9004. }
  9005. #endif
  9006. #ifdef _WIN32
  9007. TEST(CleanupTest, WSACleanup) {
  9008. int ret = WSACleanup();
  9009. ASSERT_EQ(0, ret);
  9010. }
  9011. #endif
  9012. #ifndef CPPHTTPLIB_SSL_ENABLED
  9013. TEST(NoSSLSupport, SimpleInterface) {
  9014. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9015. }
  9016. #endif
  9017. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9018. TEST(InvalidScheme, SimpleInterface) {
  9019. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9020. }
  9021. #endif
  9022. TEST(NoScheme, SimpleInterface) {
  9023. Client cli("yahoo.com:80");
  9024. ASSERT_TRUE(cli.is_valid());
  9025. }
  9026. TEST(SendAPI, SimpleInterface_Online) {
  9027. Client cli("http://yahoo.com");
  9028. Request req;
  9029. req.method = "GET";
  9030. req.path = "/";
  9031. auto res = cli.send(req);
  9032. ASSERT_TRUE(res);
  9033. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9034. }
  9035. TEST(SendAPI, WithParamsInRequest) {
  9036. Server svr;
  9037. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9038. EXPECT_TRUE(req.has_param("test"));
  9039. EXPECT_EQ("test_value", req.get_param_value("test"));
  9040. });
  9041. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9042. auto se = detail::scope_exit([&] {
  9043. svr.stop();
  9044. t.join();
  9045. ASSERT_FALSE(svr.is_running());
  9046. });
  9047. svr.wait_until_ready();
  9048. Client cli(HOST, PORT);
  9049. {
  9050. Request req;
  9051. req.method = "GET";
  9052. req.path = "/";
  9053. req.params.emplace("test", "test_value");
  9054. auto res = cli.send(req);
  9055. ASSERT_TRUE(res);
  9056. }
  9057. {
  9058. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9059. ASSERT_TRUE(res);
  9060. }
  9061. }
  9062. TEST(ClientImplMethods, GetSocketTest) {
  9063. httplib::Server svr;
  9064. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9065. res.status = StatusCode::OK_200;
  9066. });
  9067. auto port = svr.bind_to_any_port("127.0.0.1");
  9068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9069. auto se = detail::scope_exit([&] {
  9070. svr.stop();
  9071. thread.join();
  9072. ASSERT_FALSE(svr.is_running());
  9073. });
  9074. svr.wait_until_ready();
  9075. {
  9076. httplib::Client cli("127.0.0.1", port);
  9077. cli.set_keep_alive(true);
  9078. // Use the behavior of cpp-httplib of opening the connection
  9079. // only when the first request happens. If that changes,
  9080. // this test would be obsolete.
  9081. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9082. // This also implicitly tests the server. But other tests would fail much
  9083. // earlier than this one to be considered.
  9084. auto res = cli.Get("/");
  9085. ASSERT_TRUE(res);
  9086. EXPECT_EQ(StatusCode::OK_200, res->status);
  9087. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9088. }
  9089. }
  9090. #ifdef CPPHTTPLIB_SSL_ENABLED
  9091. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9092. Client cli("http://yahoo.com");
  9093. auto res = cli.Get("/");
  9094. ASSERT_TRUE(res);
  9095. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9096. cli.set_follow_location(true);
  9097. res = cli.Get("/");
  9098. ASSERT_TRUE(res);
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9101. }
  9102. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9103. Client cli("https://yahoo.com");
  9104. auto res = cli.Get("/");
  9105. ASSERT_TRUE(res);
  9106. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9107. cli.set_follow_location(true);
  9108. res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9112. }
  9113. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9114. Client cli("https://yahoo.com");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(res);
  9117. ASSERT_FALSE(!res);
  9118. ASSERT_TRUE(res);
  9119. ASSERT_FALSE(res == nullptr);
  9120. ASSERT_TRUE(res != nullptr);
  9121. EXPECT_EQ(Error::Success, res.error());
  9122. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9123. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9124. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9125. cli.set_follow_location(true);
  9126. res = cli.Get("/");
  9127. ASSERT_TRUE(res);
  9128. EXPECT_EQ(Error::Success, res.error());
  9129. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9130. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9131. EXPECT_EQ(StatusCode::OK_200, res->status);
  9132. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9133. }
  9134. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9135. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9136. Client cli("https://cdnjs.cloudflare.com");
  9137. auto res =
  9138. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9139. ASSERT_TRUE(res);
  9140. EXPECT_EQ(StatusCode::OK_200, res->status);
  9141. EXPECT_EQ(287630U, res->body.size());
  9142. EXPECT_EQ("application/javascript; charset=utf-8",
  9143. res->get_header_value("Content-Type"));
  9144. }
  9145. #endif
  9146. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9147. #undef REDIR_HOST // Silence compiler warning
  9148. #define REDIR_HOST "https://httpbingo.org"
  9149. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9150. Client cli(REDIR_HOST);
  9151. cli.set_follow_location(true);
  9152. auto res =
  9153. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9154. ASSERT_TRUE(res);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. Params params;
  9161. params.emplace("url", "http://example.com");
  9162. params.emplace("status_code", "302");
  9163. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9164. ASSERT_TRUE(res);
  9165. EXPECT_EQ(StatusCode::OK_200, res->status);
  9166. }
  9167. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9168. Client cli(REDIR_HOST);
  9169. cli.set_follow_location(true);
  9170. Params params;
  9171. params.emplace("url", "http://example.com");
  9172. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9173. ASSERT_TRUE(res);
  9174. EXPECT_EQ(StatusCode::OK_200, res->status);
  9175. }
  9176. TEST(HttpToHttpsRedirectTest, CertFile) {
  9177. auto ssl_port = PORT + 1;
  9178. Server svr;
  9179. ASSERT_TRUE(svr.is_valid());
  9180. svr.Get("/index", [&](const Request &, Response &res) {
  9181. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9182. "/index");
  9183. svr.stop();
  9184. });
  9185. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9186. ASSERT_TRUE(ssl_svr.is_valid());
  9187. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9188. res.set_content("test", "text/plain");
  9189. ssl_svr.stop();
  9190. });
  9191. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9192. thread t2 =
  9193. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9194. auto se = detail::scope_exit([&] {
  9195. t2.join();
  9196. t.join();
  9197. ASSERT_FALSE(svr.is_running());
  9198. });
  9199. svr.wait_until_ready();
  9200. ssl_svr.wait_until_ready();
  9201. Client cli("127.0.0.1", PORT);
  9202. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9203. cli.enable_server_certificate_verification(true);
  9204. cli.set_follow_location(true);
  9205. cli.set_connection_timeout(30);
  9206. auto res = cli.Get("/index");
  9207. ASSERT_TRUE(res);
  9208. ASSERT_EQ(StatusCode::OK_200, res->status);
  9209. }
  9210. TEST(SSLClientRedirectTest, CertFile) {
  9211. auto ssl_port = PORT + 1;
  9212. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9213. ASSERT_TRUE(ssl_svr1.is_valid());
  9214. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9215. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9216. "/index");
  9217. ssl_svr1.stop();
  9218. });
  9219. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9220. ASSERT_TRUE(ssl_svr2.is_valid());
  9221. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9222. res.set_content("test", "text/plain");
  9223. ssl_svr2.stop();
  9224. });
  9225. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9226. thread t2 =
  9227. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9228. auto se = detail::scope_exit([&] {
  9229. t2.join();
  9230. t.join();
  9231. ASSERT_FALSE(ssl_svr1.is_running());
  9232. });
  9233. ssl_svr1.wait_until_ready();
  9234. ssl_svr2.wait_until_ready();
  9235. SSLClient cli("127.0.0.1", PORT);
  9236. std::string cert;
  9237. read_file(SERVER_CERT2_FILE, cert);
  9238. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9239. cli.enable_server_certificate_verification(true);
  9240. cli.set_follow_location(true);
  9241. cli.set_connection_timeout(30);
  9242. auto res = cli.Get("/index");
  9243. ASSERT_TRUE(res);
  9244. ASSERT_EQ(StatusCode::OK_200, res->status);
  9245. }
  9246. #endif
  9247. #ifdef CPPHTTPLIB_SSL_ENABLED
  9248. // Test that set_ca_cert_store() skips system certs (consistent with
  9249. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9250. // should be trusted - system certs should NOT be loaded.
  9251. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9252. // Load a specific cert that is NOT a system CA cert
  9253. std::string cert;
  9254. read_file(SERVER_CERT2_FILE, cert);
  9255. SSLClient cli("google.com");
  9256. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9257. cli.enable_server_certificate_verification(true);
  9258. // This should FAIL because:
  9259. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9260. // 2. System certs should NOT be loaded when custom store is set
  9261. // If system certs WERE loaded, this would succeed
  9262. auto res = cli.Get("/");
  9263. ASSERT_FALSE(res);
  9264. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9265. }
  9266. TEST(MultipartFormDataTest, LargeData) {
  9267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9268. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9269. const ContentReader &content_reader) {
  9270. if (req.is_multipart_form_data()) {
  9271. std::vector<FormData> items;
  9272. content_reader(
  9273. [&](const FormData &file) {
  9274. items.push_back(file);
  9275. return true;
  9276. },
  9277. [&](const char *data, size_t data_length) {
  9278. items.back().content.append(data, data_length);
  9279. return true;
  9280. });
  9281. EXPECT_TRUE(std::string(items[0].name) == "document");
  9282. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9283. EXPECT_TRUE(items[0].filename == "2MB_data");
  9284. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9285. EXPECT_TRUE(items[1].name == "hello");
  9286. EXPECT_TRUE(items[1].content == "world");
  9287. EXPECT_TRUE(items[1].filename == "");
  9288. EXPECT_TRUE(items[1].content_type == "");
  9289. } else {
  9290. std::string body;
  9291. content_reader([&](const char *data, size_t data_length) {
  9292. body.append(data, data_length);
  9293. return true;
  9294. });
  9295. }
  9296. });
  9297. auto port = svr.bind_to_any_port(HOST);
  9298. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. ASSERT_FALSE(svr.is_running());
  9303. });
  9304. svr.wait_until_ready();
  9305. {
  9306. std::string data(1024 * 1024 * 2, '.');
  9307. std::stringstream buffer;
  9308. buffer << data;
  9309. SSLClient cli(HOST, port);
  9310. cli.enable_server_certificate_verification(false);
  9311. UploadFormDataItems items{
  9312. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9313. {"hello", "world", "", ""},
  9314. };
  9315. auto res = cli.Post("/post", items);
  9316. ASSERT_TRUE(res);
  9317. ASSERT_EQ(StatusCode::OK_200, res->status);
  9318. }
  9319. }
  9320. TEST(MultipartFormDataTest, DataProviderItems) {
  9321. std::random_device seed_gen;
  9322. std::mt19937 random(seed_gen());
  9323. std::string rand1;
  9324. rand1.resize(1000);
  9325. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9326. std::string rand2;
  9327. rand2.resize(3000);
  9328. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9330. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9331. const ContentReader &content_reader) {
  9332. ASSERT_FALSE(req.is_multipart_form_data());
  9333. std::string body;
  9334. content_reader([&](const char *data, size_t data_length) {
  9335. body.append(data, data_length);
  9336. return true;
  9337. });
  9338. EXPECT_EQ(body, "");
  9339. });
  9340. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9341. const ContentReader &content_reader) {
  9342. ASSERT_TRUE(req.is_multipart_form_data());
  9343. std::vector<FormData> items;
  9344. content_reader(
  9345. [&](const FormData &file) {
  9346. items.push_back(file);
  9347. return true;
  9348. },
  9349. [&](const char *data, size_t data_length) {
  9350. items.back().content.append(data, data_length);
  9351. return true;
  9352. });
  9353. ASSERT_TRUE(items.size() == 2);
  9354. EXPECT_EQ(std::string(items[0].name), "name1");
  9355. EXPECT_EQ(items[0].content, "Testing123");
  9356. EXPECT_EQ(items[0].filename, "filename1");
  9357. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9358. EXPECT_EQ(items[1].name, "name2");
  9359. EXPECT_EQ(items[1].content, "Testing456");
  9360. EXPECT_EQ(items[1].filename, "");
  9361. EXPECT_EQ(items[1].content_type, "");
  9362. });
  9363. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9364. const ContentReader &content_reader) {
  9365. ASSERT_TRUE(req.is_multipart_form_data());
  9366. std::vector<FormData> items;
  9367. content_reader(
  9368. [&](const FormData &file) {
  9369. items.push_back(file);
  9370. return true;
  9371. },
  9372. [&](const char *data, size_t data_length) {
  9373. items.back().content.append(data, data_length);
  9374. return true;
  9375. });
  9376. ASSERT_TRUE(items.size() == 2);
  9377. EXPECT_EQ(items[0].name, "name3");
  9378. EXPECT_EQ(items[0].content, rand1);
  9379. EXPECT_EQ(items[0].filename, "filename3");
  9380. EXPECT_EQ(items[0].content_type, "");
  9381. EXPECT_EQ(items[1].name, "name4");
  9382. EXPECT_EQ(items[1].content, rand2);
  9383. EXPECT_EQ(items[1].filename, "filename4");
  9384. EXPECT_EQ(items[1].content_type, "");
  9385. });
  9386. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9387. const ContentReader &content_reader) {
  9388. ASSERT_TRUE(req.is_multipart_form_data());
  9389. std::vector<FormData> items;
  9390. content_reader(
  9391. [&](const FormData &file) {
  9392. items.push_back(file);
  9393. return true;
  9394. },
  9395. [&](const char *data, size_t data_length) {
  9396. items.back().content.append(data, data_length);
  9397. return true;
  9398. });
  9399. ASSERT_TRUE(items.size() == 4);
  9400. EXPECT_EQ(std::string(items[0].name), "name1");
  9401. EXPECT_EQ(items[0].content, "Testing123");
  9402. EXPECT_EQ(items[0].filename, "filename1");
  9403. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9404. EXPECT_EQ(items[1].name, "name2");
  9405. EXPECT_EQ(items[1].content, "Testing456");
  9406. EXPECT_EQ(items[1].filename, "");
  9407. EXPECT_EQ(items[1].content_type, "");
  9408. EXPECT_EQ(items[2].name, "name3");
  9409. EXPECT_EQ(items[2].content, rand1);
  9410. EXPECT_EQ(items[2].filename, "filename3");
  9411. EXPECT_EQ(items[2].content_type, "");
  9412. EXPECT_EQ(items[3].name, "name4");
  9413. EXPECT_EQ(items[3].content, rand2);
  9414. EXPECT_EQ(items[3].filename, "filename4");
  9415. EXPECT_EQ(items[3].content_type, "");
  9416. });
  9417. auto port = svr.bind_to_any_port("localhost");
  9418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. {
  9426. SSLClient cli("localhost", port);
  9427. cli.enable_server_certificate_verification(false);
  9428. UploadFormDataItems items{
  9429. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9430. {"name2", "Testing456", "", ""}, // not a file
  9431. };
  9432. {
  9433. auto res = cli.Post("/post-none", {}, {}, {});
  9434. ASSERT_TRUE(res);
  9435. ASSERT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. FormDataProviderItems providers;
  9438. {
  9439. auto res =
  9440. cli.Post("/post-items", {}, items, providers); // empty providers
  9441. ASSERT_TRUE(res);
  9442. ASSERT_EQ(StatusCode::OK_200, res->status);
  9443. }
  9444. providers.push_back({"name3",
  9445. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9446. // test the offset is given correctly at each step
  9447. if (!offset)
  9448. sink.os.write(rand1.data(), 30);
  9449. else if (offset == 30)
  9450. sink.os.write(rand1.data() + 30, 300);
  9451. else if (offset == 330)
  9452. sink.os.write(rand1.data() + 330, 670);
  9453. else if (offset == rand1.size())
  9454. sink.done();
  9455. return true;
  9456. },
  9457. "filename3",
  9458. {}});
  9459. providers.push_back({"name4",
  9460. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9461. // test the offset is given correctly at each step
  9462. if (!offset)
  9463. sink.os.write(rand2.data(), 2000);
  9464. else if (offset == 2000)
  9465. sink.os.write(rand2.data() + 2000, 1);
  9466. else if (offset == 2001)
  9467. sink.os.write(rand2.data() + 2001, 999);
  9468. else if (offset == rand2.size())
  9469. sink.done();
  9470. return true;
  9471. },
  9472. "filename4",
  9473. {}});
  9474. {
  9475. auto res = cli.Post("/post-providers", {}, {}, providers);
  9476. ASSERT_TRUE(res);
  9477. ASSERT_EQ(StatusCode::OK_200, res->status);
  9478. }
  9479. {
  9480. auto res = cli.Post("/post-both", {}, items, providers);
  9481. ASSERT_TRUE(res);
  9482. ASSERT_EQ(StatusCode::OK_200, res->status);
  9483. }
  9484. }
  9485. }
  9486. TEST(MultipartFormDataTest, BadHeader) {
  9487. Server svr;
  9488. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9489. res.set_content("ok", "text/plain");
  9490. });
  9491. thread t = thread([&] { svr.listen(HOST, PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. const std::string body =
  9499. "This is the preamble. It is to be ignored, though it\r\n"
  9500. "is a handy place for composition agents to include an\r\n"
  9501. "explanatory note to non-MIME conformant readers.\r\n"
  9502. "\r\n"
  9503. "\r\n"
  9504. "--simple boundary\r\n"
  9505. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9506. ": BAD...\r\n"
  9507. "\r\n"
  9508. "value1\r\n"
  9509. "--simple boundary\r\n"
  9510. "Content-Disposition: form-data; name=\"field2\"; "
  9511. "filename=\"example.txt\"\r\n"
  9512. "\r\n"
  9513. "value2\r\n"
  9514. "--simple boundary--\r\n"
  9515. "This is the epilogue. It is also to be ignored.\r\n";
  9516. std::string content_type =
  9517. R"(multipart/form-data; boundary="simple boundary")";
  9518. Client cli(HOST, PORT);
  9519. auto res = cli.Post("/post", body, content_type.c_str());
  9520. ASSERT_TRUE(res);
  9521. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9522. }
  9523. TEST(MultipartFormDataTest, WithPreamble) {
  9524. Server svr;
  9525. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&] { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. ASSERT_FALSE(svr.is_running());
  9533. });
  9534. svr.wait_until_ready();
  9535. const std::string body =
  9536. "This is the preamble. It is to be ignored, though it\r\n"
  9537. "is a handy place for composition agents to include an\r\n"
  9538. "explanatory note to non-MIME conformant readers.\r\n"
  9539. "\r\n"
  9540. "\r\n"
  9541. "--simple boundary\r\n"
  9542. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9543. "\r\n"
  9544. "value1\r\n"
  9545. "--simple boundary\r\n"
  9546. "Content-Disposition: form-data; name=\"field2\"; "
  9547. "filename=\"example.txt\"\r\n"
  9548. "\r\n"
  9549. "value2\r\n"
  9550. "--simple boundary--\r\n"
  9551. "This is the epilogue. It is also to be ignored.\r\n";
  9552. std::string content_type =
  9553. R"(multipart/form-data; boundary="simple boundary")";
  9554. Client cli(HOST, PORT);
  9555. auto res = cli.Post("/post", body, content_type.c_str());
  9556. ASSERT_TRUE(res);
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. }
  9559. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9561. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9562. const ContentReader &content_reader) {
  9563. if (req.is_multipart_form_data()) {
  9564. std::vector<FormData> items;
  9565. content_reader(
  9566. [&](const FormData &file) {
  9567. items.push_back(file);
  9568. return true;
  9569. },
  9570. [&](const char *data, size_t data_length) {
  9571. items.back().content.append(data, data_length);
  9572. return true;
  9573. });
  9574. EXPECT_TRUE(std::string(items[0].name) == "document");
  9575. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9576. EXPECT_TRUE(items[0].filename == "2MB_data");
  9577. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9578. EXPECT_TRUE(items[1].name == "hello");
  9579. EXPECT_TRUE(items[1].content == "world");
  9580. EXPECT_TRUE(items[1].filename == "");
  9581. EXPECT_TRUE(items[1].content_type == "");
  9582. } else {
  9583. std::string body;
  9584. content_reader([&](const char *data, size_t data_length) {
  9585. body.append(data, data_length);
  9586. return true;
  9587. });
  9588. }
  9589. });
  9590. auto port = svr.bind_to_any_port("localhost");
  9591. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. {
  9599. std::string data(1024 * 1024 * 2, '.');
  9600. std::stringstream buffer;
  9601. buffer << data;
  9602. SSLClient cli("localhost", port);
  9603. cli.enable_server_certificate_verification(false);
  9604. UploadFormDataItems items{
  9605. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9606. {"hello", "world", "", ""},
  9607. };
  9608. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9609. ASSERT_TRUE(res);
  9610. ASSERT_EQ(StatusCode::OK_200, res->status);
  9611. }
  9612. }
  9613. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9614. std::string data(1024 * 1024 * 2, '&');
  9615. std::stringstream buffer;
  9616. buffer << data;
  9617. Client cli("https://localhost:8080");
  9618. UploadFormDataItems items{
  9619. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9620. {"hello", "world", "", ""},
  9621. };
  9622. for (const char &c : " \t\r\n") {
  9623. auto res =
  9624. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9625. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9626. ASSERT_FALSE(res);
  9627. }
  9628. }
  9629. TEST(MultipartFormDataTest, PutFormData) {
  9630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9631. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9632. const ContentReader &content_reader) {
  9633. if (req.is_multipart_form_data()) {
  9634. std::vector<FormData> items;
  9635. content_reader(
  9636. [&](const FormData &file) {
  9637. items.push_back(file);
  9638. return true;
  9639. },
  9640. [&](const char *data, size_t data_length) {
  9641. items.back().content.append(data, data_length);
  9642. return true;
  9643. });
  9644. EXPECT_TRUE(std::string(items[0].name) == "document");
  9645. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9646. EXPECT_TRUE(items[0].filename == "2MB_data");
  9647. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9648. EXPECT_TRUE(items[1].name == "hello");
  9649. EXPECT_TRUE(items[1].content == "world");
  9650. EXPECT_TRUE(items[1].filename == "");
  9651. EXPECT_TRUE(items[1].content_type == "");
  9652. } else {
  9653. std::string body;
  9654. content_reader([&](const char *data, size_t data_length) {
  9655. body.append(data, data_length);
  9656. return true;
  9657. });
  9658. }
  9659. });
  9660. auto port = svr.bind_to_any_port("localhost");
  9661. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. ASSERT_FALSE(svr.is_running());
  9666. });
  9667. svr.wait_until_ready();
  9668. {
  9669. std::string data(1024 * 1024 * 2, '&');
  9670. std::stringstream buffer;
  9671. buffer << data;
  9672. SSLClient cli("localhost", port);
  9673. cli.enable_server_certificate_verification(false);
  9674. UploadFormDataItems items{
  9675. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9676. {"hello", "world", "", ""},
  9677. };
  9678. auto res = cli.Put("/put", items);
  9679. ASSERT_TRUE(res);
  9680. ASSERT_EQ(StatusCode::OK_200, res->status);
  9681. }
  9682. }
  9683. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9685. svr.Put("/put_customboundary",
  9686. [&](const Request &req, const Response & /*res*/,
  9687. const ContentReader &content_reader) {
  9688. if (req.is_multipart_form_data()) {
  9689. std::vector<FormData> items;
  9690. content_reader(
  9691. [&](const FormData &file) {
  9692. items.push_back(file);
  9693. return true;
  9694. },
  9695. [&](const char *data, size_t data_length) {
  9696. items.back().content.append(data, data_length);
  9697. return true;
  9698. });
  9699. EXPECT_TRUE(std::string(items[0].name) == "document");
  9700. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9701. EXPECT_TRUE(items[0].filename == "2MB_data");
  9702. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9703. EXPECT_TRUE(items[1].name == "hello");
  9704. EXPECT_TRUE(items[1].content == "world");
  9705. EXPECT_TRUE(items[1].filename == "");
  9706. EXPECT_TRUE(items[1].content_type == "");
  9707. } else {
  9708. std::string body;
  9709. content_reader([&](const char *data, size_t data_length) {
  9710. body.append(data, data_length);
  9711. return true;
  9712. });
  9713. }
  9714. });
  9715. auto port = svr.bind_to_any_port("localhost");
  9716. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. {
  9724. std::string data(1024 * 1024 * 2, '&');
  9725. std::stringstream buffer;
  9726. buffer << data;
  9727. SSLClient cli("localhost", port);
  9728. cli.enable_server_certificate_verification(false);
  9729. UploadFormDataItems items{
  9730. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9731. {"hello", "world", "", ""},
  9732. };
  9733. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9734. ASSERT_TRUE(res);
  9735. ASSERT_EQ(StatusCode::OK_200, res->status);
  9736. }
  9737. }
  9738. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9739. std::string data(1024 * 1024 * 2, '&');
  9740. std::stringstream buffer;
  9741. buffer << data;
  9742. Client cli("https://localhost:8080");
  9743. cli.enable_server_certificate_verification(false);
  9744. UploadFormDataItems items{
  9745. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9746. {"hello", "world", "", ""},
  9747. };
  9748. for (const char &c : " \t\r\n") {
  9749. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9750. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9751. ASSERT_FALSE(res);
  9752. }
  9753. }
  9754. TEST(MultipartFormDataTest, AlternateFilename) {
  9755. auto handled = false;
  9756. Server svr;
  9757. svr.Post("/test", [&](const Request &req, Response &res) {
  9758. ASSERT_EQ(2u, req.form.files.size());
  9759. ASSERT_EQ(1u, req.form.fields.size());
  9760. // Test files
  9761. const auto &file1 = req.form.get_file("file1");
  9762. ASSERT_EQ("file1", file1.name);
  9763. ASSERT_EQ("A.txt", file1.filename);
  9764. ASSERT_EQ("text/plain", file1.content_type);
  9765. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9766. const auto &file2 = req.form.get_file("file2");
  9767. ASSERT_EQ("file2", file2.name);
  9768. ASSERT_EQ("a.html", file2.filename);
  9769. ASSERT_EQ("text/html", file2.content_type);
  9770. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9771. file2.content);
  9772. // Test text field
  9773. const auto &text = req.form.get_field("text");
  9774. ASSERT_EQ("text default", text);
  9775. res.set_content("ok", "text/plain");
  9776. handled = true;
  9777. });
  9778. thread t = thread([&] { svr.listen(HOST, PORT); });
  9779. auto se = detail::scope_exit([&] {
  9780. svr.stop();
  9781. t.join();
  9782. ASSERT_FALSE(svr.is_running());
  9783. ASSERT_TRUE(handled);
  9784. });
  9785. svr.wait_until_ready();
  9786. auto req = "POST /test HTTP/1.1\r\n"
  9787. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9788. "Content-Length: 399\r\n"
  9789. "\r\n"
  9790. "----------\r\n"
  9791. "Content-Disposition: form-data; name=\"text\"\r\n"
  9792. "\r\n"
  9793. "text default\r\n"
  9794. "----------\r\n"
  9795. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9796. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9797. "Content-Type: text/plain\r\n"
  9798. "\r\n"
  9799. "Content of a.txt.\r\n"
  9800. "\r\n"
  9801. "----------\r\n"
  9802. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9803. "\"a.html\"\r\n"
  9804. "Content-Type: text/html\r\n"
  9805. "\r\n"
  9806. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9807. "\r\n"
  9808. "------------\r\n";
  9809. ASSERT_TRUE(send_request(1, req));
  9810. }
  9811. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9812. auto handled = false;
  9813. Server svr;
  9814. svr.Post("/test", [&](const Request &req, Response &res) {
  9815. // Case-insensitive "utf-8''" prefix with a long value
  9816. const auto &file = req.form.get_file("file1");
  9817. ASSERT_EQ("file1", file.name);
  9818. // 8000 chars exercises both the Content-Disposition parser and the
  9819. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9820. // Prior to the fix, std::regex_match on this header would cause O(N)
  9821. // stack recursion in libstdc++, leading to SIGSEGV.
  9822. std::string expected_filename(8000, 'A');
  9823. ASSERT_EQ(expected_filename, file.filename);
  9824. res.set_content("ok", "text/plain");
  9825. handled = true;
  9826. });
  9827. thread t = thread([&] { svr.listen(HOST, PORT); });
  9828. auto se = detail::scope_exit([&] {
  9829. svr.stop();
  9830. t.join();
  9831. ASSERT_FALSE(svr.is_running());
  9832. ASSERT_TRUE(handled);
  9833. });
  9834. svr.wait_until_ready();
  9835. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9836. // Regression test for GHSA-qq6v-r583-3h69
  9837. std::string long_filename(8000, 'A');
  9838. std::string body = "----------\r\n"
  9839. "Content-Disposition: form-data; name=\"file1\"; "
  9840. "filename*=\"Utf-8''" +
  9841. long_filename +
  9842. "\"\r\n"
  9843. "\r\n"
  9844. "hello\r\n"
  9845. "------------\r\n";
  9846. auto req = "POST /test HTTP/1.1\r\n"
  9847. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9848. "Content-Length: " +
  9849. std::to_string(body.size()) + "\r\n\r\n" + body;
  9850. ASSERT_TRUE(send_request(1, req));
  9851. }
  9852. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9853. auto handled = false;
  9854. Server svr;
  9855. svr.Post("/test", [&](const Request &req, Response &) {
  9856. ASSERT_EQ(2u, req.form.fields.size());
  9857. const auto &text1 = req.form.get_field("text1");
  9858. ASSERT_EQ("text1", text1);
  9859. const auto &text2 = req.form.get_field("text2");
  9860. ASSERT_EQ("text2", text2);
  9861. handled = true;
  9862. });
  9863. thread t = thread([&] { svr.listen(HOST, PORT); });
  9864. auto se = detail::scope_exit([&] {
  9865. svr.stop();
  9866. t.join();
  9867. ASSERT_FALSE(svr.is_running());
  9868. ASSERT_TRUE(handled);
  9869. });
  9870. svr.wait_until_ready();
  9871. auto req = "POST /test HTTP/1.1\r\n"
  9872. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9873. "Content-Length: 146\r\n"
  9874. "\r\n----------\r\n"
  9875. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9876. "\r\n"
  9877. "text1"
  9878. "\r\n----------\r\n"
  9879. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9880. "\r\n"
  9881. "text2"
  9882. "\r\n------------";
  9883. std::string response;
  9884. ASSERT_TRUE(send_request(1, req, &response));
  9885. ASSERT_EQ("200", response.substr(9, 3));
  9886. }
  9887. TEST(MultipartFormDataTest, ContentLength) {
  9888. auto handled = false;
  9889. Server svr;
  9890. svr.Post("/test", [&](const Request &req, Response &) {
  9891. ASSERT_EQ(2u, req.form.fields.size());
  9892. const auto &text1 = req.form.get_field("text1");
  9893. ASSERT_EQ("text1", text1);
  9894. const auto &text2 = req.form.get_field("text2");
  9895. ASSERT_EQ("text2", text2);
  9896. handled = true;
  9897. });
  9898. thread t = thread([&] { svr.listen(HOST, PORT); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. t.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. ASSERT_TRUE(handled);
  9904. });
  9905. svr.wait_until_ready();
  9906. auto req = "POST /test HTTP/1.1\r\n"
  9907. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9908. "Content-Length: 167\r\n"
  9909. "\r\n----------\r\n"
  9910. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9911. "Content-Length: 5\r\n"
  9912. "\r\n"
  9913. "text1"
  9914. "\r\n----------\r\n"
  9915. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9916. "\r\n"
  9917. "text2"
  9918. "\r\n------------\r\n";
  9919. std::string response;
  9920. ASSERT_TRUE(send_request(1, req, &response));
  9921. ASSERT_EQ("200", response.substr(9, 3));
  9922. }
  9923. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9924. auto handled = false;
  9925. Server svr;
  9926. svr.Post("/test", [&](const Request &req, Response &) {
  9927. ASSERT_EQ(2u, req.form.fields.size());
  9928. const auto &text1 = req.form.get_field("text1");
  9929. ASSERT_EQ("text1", text1);
  9930. // TODO: Add header access for text fields if needed
  9931. const auto &text2 = req.form.get_field("text2");
  9932. ASSERT_EQ("text2", text2);
  9933. // TODO: Header access for text fields needs to be implemented
  9934. // auto &headers = it->second.headers;
  9935. // ASSERT_EQ(3U, headers.size());
  9936. // auto custom_header = headers.find("x-whatever");
  9937. // ASSERT_TRUE(custom_header != headers.end());
  9938. // ASSERT_NE("customvalue", custom_header->second);
  9939. // ASSERT_EQ("CustomValue", custom_header->second);
  9940. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9941. handled = true;
  9942. });
  9943. thread t = thread([&] { svr.listen(HOST, PORT); });
  9944. auto se = detail::scope_exit([&] {
  9945. svr.stop();
  9946. t.join();
  9947. ASSERT_FALSE(svr.is_running());
  9948. ASSERT_TRUE(handled);
  9949. });
  9950. svr.wait_until_ready();
  9951. auto req = "POST /test HTTP/1.1\r\n"
  9952. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9953. "Content-Length: 232\r\n"
  9954. "\r\n----------\r\n"
  9955. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9956. "Content-Length: 5\r\n"
  9957. "X-Test: 1\r\n"
  9958. "\r\n"
  9959. "text1"
  9960. "\r\n----------\r\n"
  9961. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9962. "Content-Type: text/plain\r\n"
  9963. "X-Whatever: CustomValue\r\n"
  9964. "\r\n"
  9965. "text2"
  9966. "\r\n------------\r\n"
  9967. "That should be disregarded. Not even read";
  9968. std::string response;
  9969. ASSERT_TRUE(send_request(1, req, &response));
  9970. ASSERT_EQ("200", response.substr(9, 3));
  9971. }
  9972. TEST(MultipartFormDataTest, LargeHeader) {
  9973. auto handled = false;
  9974. Server svr;
  9975. svr.Post("/test", [&](const Request &req, Response &) {
  9976. ASSERT_EQ(1u, req.form.fields.size());
  9977. const auto &text = req.form.get_field("name1");
  9978. ASSERT_EQ("text1", text);
  9979. handled = true;
  9980. });
  9981. thread t = thread([&] { svr.listen(HOST, PORT); });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. t.join();
  9985. ASSERT_FALSE(svr.is_running());
  9986. ASSERT_TRUE(handled);
  9987. });
  9988. svr.wait_until_ready();
  9989. auto boundary = std::string("cpp-httplib-multipart-data");
  9990. std::string content = "--" + boundary +
  9991. "\r\n"
  9992. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9993. "\r\n"
  9994. "text1\r\n"
  9995. "--" +
  9996. boundary + "--\r\n";
  9997. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9998. "Content-Type: multipart/form-data;boundary=" +
  9999. boundary +
  10000. "\r\n"
  10001. "Content-Length: " +
  10002. std::to_string(content.size()) +
  10003. "\r\n"
  10004. "Dummy-Header: ";
  10005. std::string header_suffix = "\r\n"
  10006. "\r\n";
  10007. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10008. size_t header_dummy_size =
  10009. read_buff_size -
  10010. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10011. auto header_dummy = std::string(header_dummy_size, '@');
  10012. auto req = header_prefix + header_dummy + header_suffix + content;
  10013. std::string response;
  10014. ASSERT_TRUE(send_request(1, req, &response));
  10015. ASSERT_EQ("200", response.substr(9, 3));
  10016. }
  10017. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10018. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10019. // (not chunked Transfer-Encoding) after the streaming refactor.
  10020. auto handled = false;
  10021. Server svr;
  10022. svr.Post("/upload", [&](const Request &req, Response &res) {
  10023. auto cl_it = req.headers.find("Content-Length");
  10024. EXPECT_TRUE(cl_it != req.headers.end());
  10025. auto te_it = req.headers.find("Transfer-Encoding");
  10026. EXPECT_TRUE(te_it == req.headers.end());
  10027. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10028. res.set_content("ok", "text/plain");
  10029. handled = true;
  10030. });
  10031. auto port = svr.bind_to_any_port(HOST);
  10032. auto t = thread([&] { svr.listen_after_bind(); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. ASSERT_TRUE(handled);
  10038. });
  10039. svr.wait_until_ready();
  10040. UploadFormDataItems items = {
  10041. {"field1", "hello", "", "text/plain"},
  10042. {"file1", "world", "test.txt", "application/octet-stream"},
  10043. };
  10044. Client cli(HOST, port);
  10045. auto res = cli.Post("/upload", {}, items);
  10046. ASSERT_TRUE(res);
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. }
  10049. TEST(MultipartFormDataTest, MakeFileProvider) {
  10050. // Verify make_file_provider sends a file's contents correctly.
  10051. const std::string file_content(4096, 'Z');
  10052. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10053. {
  10054. std::ofstream ofs(tmp_path, std::ios::binary);
  10055. ofs.write(file_content.data(),
  10056. static_cast<std::streamsize>(file_content.size()));
  10057. }
  10058. auto handled = false;
  10059. Server svr;
  10060. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10061. const ContentReader &content_reader) {
  10062. ASSERT_TRUE(req.is_multipart_form_data());
  10063. std::vector<FormData> items;
  10064. content_reader(
  10065. [&](const FormData &file) {
  10066. items.push_back(file);
  10067. return true;
  10068. },
  10069. [&](const char *data, size_t data_length) {
  10070. items.back().content.append(data, data_length);
  10071. return true;
  10072. });
  10073. ASSERT_EQ(1u, items.size());
  10074. EXPECT_EQ("myfile", items[0].name);
  10075. EXPECT_EQ("data.bin", items[0].filename);
  10076. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10077. EXPECT_EQ(file_content, items[0].content);
  10078. handled = true;
  10079. });
  10080. auto port = svr.bind_to_any_port(HOST);
  10081. auto t = thread([&] { svr.listen_after_bind(); });
  10082. auto se = detail::scope_exit([&] {
  10083. svr.stop();
  10084. t.join();
  10085. ASSERT_FALSE(svr.is_running());
  10086. ASSERT_TRUE(handled);
  10087. std::remove(tmp_path.c_str());
  10088. });
  10089. svr.wait_until_ready();
  10090. FormDataProviderItems providers;
  10091. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10092. "application/octet-stream"));
  10093. Client cli(HOST, port);
  10094. auto res = cli.Post("/upload", {}, {}, providers);
  10095. ASSERT_TRUE(res);
  10096. EXPECT_EQ(StatusCode::OK_200, res->status);
  10097. }
  10098. TEST(MakeFileBodyTest, Basic) {
  10099. const std::string file_content(4096, 'Z');
  10100. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10101. {
  10102. std::ofstream ofs(tmp_path, std::ios::binary);
  10103. ofs.write(file_content.data(),
  10104. static_cast<std::streamsize>(file_content.size()));
  10105. }
  10106. auto handled = false;
  10107. Server svr;
  10108. svr.Post("/upload", [&](const Request &req, Response &res) {
  10109. EXPECT_EQ(file_content, req.body);
  10110. handled = true;
  10111. res.status = StatusCode::OK_200;
  10112. });
  10113. auto port = svr.bind_to_any_port(HOST);
  10114. auto t = thread([&] { svr.listen_after_bind(); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. t.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. ASSERT_TRUE(handled);
  10120. std::remove(tmp_path.c_str());
  10121. });
  10122. svr.wait_until_ready();
  10123. auto fb = make_file_body(tmp_path);
  10124. ASSERT_GT(fb.first, 0u);
  10125. Client cli(HOST, port);
  10126. auto res =
  10127. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10128. ASSERT_TRUE(res);
  10129. EXPECT_EQ(StatusCode::OK_200, res->status);
  10130. }
  10131. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10132. static constexpr unsigned int number_of_tasks{1000000};
  10133. std::atomic_uint count{0};
  10134. std::unique_ptr<TaskQueue> task_queue{
  10135. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10136. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10137. auto queued = task_queue->enqueue(
  10138. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10139. EXPECT_TRUE(queued);
  10140. }
  10141. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10142. task_queue->shutdown();
  10143. #else
  10144. EXPECT_NO_THROW(task_queue->shutdown());
  10145. #endif
  10146. EXPECT_EQ(number_of_tasks, count.load());
  10147. }
  10148. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10149. static constexpr unsigned int number_of_tasks{1000000};
  10150. static constexpr unsigned int qlimit{2};
  10151. unsigned int queued_count{0};
  10152. std::atomic_uint count{0};
  10153. std::unique_ptr<TaskQueue> task_queue{
  10154. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10155. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10156. if (task_queue->enqueue(
  10157. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10158. queued_count++;
  10159. }
  10160. }
  10161. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10162. task_queue->shutdown();
  10163. #else
  10164. EXPECT_NO_THROW(task_queue->shutdown());
  10165. #endif
  10166. EXPECT_EQ(queued_count, count.load());
  10167. EXPECT_TRUE(queued_count <= number_of_tasks);
  10168. EXPECT_TRUE(queued_count >= qlimit);
  10169. }
  10170. TEST(TaskQueueTest, MaxQueuedRequests) {
  10171. static constexpr unsigned int qlimit{3};
  10172. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10173. std::condition_variable sem_cv;
  10174. std::mutex sem_mtx;
  10175. int credits = 0;
  10176. bool queued;
  10177. /* Fill up the queue with tasks that will block until we give them credits to
  10178. * complete. */
  10179. for (unsigned int n = 0; n <= qlimit;) {
  10180. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10181. std::unique_lock<std::mutex> lock(sem_mtx);
  10182. while (credits <= 0) {
  10183. sem_cv.wait(lock);
  10184. }
  10185. /* Consume the credit and signal the test code if they are all gone. */
  10186. if (--credits == 0) { sem_cv.notify_one(); }
  10187. });
  10188. if (n < qlimit) {
  10189. /* The first qlimit enqueues must succeed. */
  10190. EXPECT_TRUE(queued);
  10191. } else {
  10192. /* The last one will succeed only when the worker thread
  10193. * starts and dequeues the first blocking task. Although
  10194. * not necessary for the correctness of this test, we sleep for
  10195. * a short while to avoid busy waiting. */
  10196. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10197. }
  10198. if (queued) { n++; }
  10199. }
  10200. /* Further enqueues must fail since the queue is full. */
  10201. for (auto i = 0; i < 4; i++) {
  10202. queued = task_queue->enqueue([] {});
  10203. EXPECT_FALSE(queued);
  10204. }
  10205. /* Give the credits to allow the previous tasks to complete. */
  10206. {
  10207. std::unique_lock<std::mutex> lock(sem_mtx);
  10208. credits += qlimit + 1;
  10209. }
  10210. sem_cv.notify_all();
  10211. /* Wait for all the credits to be consumed. */
  10212. {
  10213. std::unique_lock<std::mutex> lock(sem_mtx);
  10214. while (credits > 0) {
  10215. sem_cv.wait(lock);
  10216. }
  10217. }
  10218. /* Check that we are able again to enqueue at least qlimit tasks. */
  10219. for (unsigned int i = 0; i < qlimit; i++) {
  10220. queued = task_queue->enqueue([] {});
  10221. EXPECT_TRUE(queued);
  10222. }
  10223. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10224. task_queue->shutdown();
  10225. #else
  10226. EXPECT_NO_THROW(task_queue->shutdown());
  10227. #endif
  10228. }
  10229. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10230. Server svr;
  10231. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10232. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10233. });
  10234. svr.Get("/hello", [](const Request &req, Response &res) {
  10235. res.set_content(req.get_param_value("key"), "text/plain");
  10236. });
  10237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10238. auto se = detail::scope_exit([&] {
  10239. svr.stop();
  10240. thread.join();
  10241. ASSERT_FALSE(svr.is_running());
  10242. });
  10243. svr.wait_until_ready();
  10244. {
  10245. Client cli(HOST, PORT);
  10246. cli.set_follow_location(true);
  10247. auto res = cli.Get("/");
  10248. ASSERT_TRUE(res);
  10249. EXPECT_EQ(StatusCode::OK_200, res->status);
  10250. EXPECT_EQ("val&key2=val2", res->body);
  10251. }
  10252. }
  10253. #endif
  10254. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10255. Server svr;
  10256. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10257. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10258. });
  10259. svr.Get("/hello", [](const Request &req, Response &res) {
  10260. res.set_content(req.get_param_value("key"), "text/plain");
  10261. });
  10262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10263. auto se = detail::scope_exit([&] {
  10264. svr.stop();
  10265. thread.join();
  10266. ASSERT_FALSE(svr.is_running());
  10267. });
  10268. svr.wait_until_ready();
  10269. {
  10270. Client cli(HOST, PORT);
  10271. cli.set_follow_location(true);
  10272. auto res = cli.Get("/");
  10273. ASSERT_TRUE(res);
  10274. EXPECT_EQ(StatusCode::OK_200, res->status);
  10275. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10276. }
  10277. }
  10278. #ifdef CPPHTTPLIB_SSL_ENABLED
  10279. TEST(RedirectTest, Issue2185_Online) {
  10280. SSLClient client("github.com");
  10281. client.set_follow_location(true);
  10282. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10283. "Coollab-Windows.zip");
  10284. ASSERT_TRUE(res);
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ(9920427U, res->body.size());
  10287. }
  10288. #endif
  10289. TEST(VulnerabilityTest, CRLFInjection) {
  10290. Server svr;
  10291. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10292. res.set_content("Hello 1", "text/plain");
  10293. });
  10294. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10295. res.set_content("Hello 2", "text/plain");
  10296. });
  10297. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10298. res.set_content("Hello 3", "text/plain");
  10299. });
  10300. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10301. res.set_content("Hello 4", "text/plain");
  10302. });
  10303. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10304. for (const auto &x : req.headers) {
  10305. auto key = x.first;
  10306. EXPECT_STRNE("evil", key.c_str());
  10307. }
  10308. });
  10309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10310. auto se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. {
  10317. Client cli(HOST, PORT);
  10318. cli.Post("/test1", "A=B",
  10319. "application/x-www-form-urlencoded\r\nevil: hello1");
  10320. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10321. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10322. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10323. }
  10324. }
  10325. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10326. auto server_thread = std::thread([] {
  10327. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10328. default_socket_options(srv);
  10329. sockaddr_in addr{};
  10330. addr.sin_family = AF_INET;
  10331. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10332. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10333. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10334. ::listen(srv, 1);
  10335. sockaddr_in cli_addr{};
  10336. socklen_t cli_len = sizeof(cli_addr);
  10337. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10338. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10339. std::string buf_all;
  10340. char buf[2048];
  10341. ssize_t n;
  10342. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10343. buf_all.append(buf, static_cast<size_t>(n));
  10344. size_t pos;
  10345. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10346. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10347. auto e = request_block.find("\r\n");
  10348. if (e != std::string::npos) {
  10349. auto request_line = request_block.substr(0, e);
  10350. std::string msg =
  10351. "CRLF injection detected in request line: '" + request_line + "'";
  10352. EXPECT_FALSE(true) << msg;
  10353. }
  10354. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10355. ::send(cli,
  10356. #ifdef _WIN32
  10357. static_cast<const char *>(resp.c_str()),
  10358. static_cast<int>(resp.size()),
  10359. #else
  10360. resp.c_str(), resp.size(),
  10361. #endif
  10362. 0);
  10363. buf_all.erase(0, pos + 4);
  10364. }
  10365. }
  10366. detail::close_socket(cli);
  10367. detail::close_socket(srv);
  10368. });
  10369. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10370. auto cli = Client("127.0.0.1", PORT + 1);
  10371. auto headers = Headers{
  10372. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10373. {"Connection", "keep-alive"}};
  10374. auto res = cli.Get("/hi", headers);
  10375. EXPECT_FALSE(res);
  10376. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10377. server_thread.join();
  10378. }
  10379. TEST(PathParamsTest, StaticMatch) {
  10380. const auto pattern = "/users/all";
  10381. detail::PathParamsMatcher matcher(pattern);
  10382. Request request;
  10383. request.path = "/users/all";
  10384. ASSERT_TRUE(matcher.match(request));
  10385. std::unordered_map<std::string, std::string> expected_params = {};
  10386. EXPECT_EQ(request.path_params, expected_params);
  10387. }
  10388. TEST(PathParamsTest, StaticMismatch) {
  10389. const auto pattern = "/users/all";
  10390. detail::PathParamsMatcher matcher(pattern);
  10391. Request request;
  10392. request.path = "/users/1";
  10393. ASSERT_FALSE(matcher.match(request));
  10394. }
  10395. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10396. const auto pattern = "/users/:id/subscriptions";
  10397. detail::PathParamsMatcher matcher(pattern);
  10398. Request request;
  10399. request.path = "/users/42/subscriptions";
  10400. ASSERT_TRUE(matcher.match(request));
  10401. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10402. EXPECT_EQ(request.path_params, expected_params);
  10403. }
  10404. TEST(PathParamsTest, SingleParamInTheEnd) {
  10405. const auto pattern = "/users/:id";
  10406. detail::PathParamsMatcher matcher(pattern);
  10407. Request request;
  10408. request.path = "/users/24";
  10409. ASSERT_TRUE(matcher.match(request));
  10410. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10411. EXPECT_EQ(request.path_params, expected_params);
  10412. }
  10413. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10414. const auto pattern = "/users/:id/";
  10415. detail::PathParamsMatcher matcher(pattern);
  10416. Request request;
  10417. request.path = "/users/42/";
  10418. ASSERT_TRUE(matcher.match(request));
  10419. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10420. EXPECT_EQ(request.path_params, expected_params);
  10421. }
  10422. TEST(PathParamsTest, EmptyParam) {
  10423. const auto pattern = "/users/:id/";
  10424. detail::PathParamsMatcher matcher(pattern);
  10425. Request request;
  10426. request.path = "/users//";
  10427. ASSERT_TRUE(matcher.match(request));
  10428. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10429. EXPECT_EQ(request.path_params, expected_params);
  10430. }
  10431. TEST(PathParamsTest, FragmentMismatch) {
  10432. const auto pattern = "/users/:id/";
  10433. detail::PathParamsMatcher matcher(pattern);
  10434. Request request;
  10435. request.path = "/admins/24/";
  10436. ASSERT_FALSE(matcher.match(request));
  10437. }
  10438. TEST(PathParamsTest, ExtraFragments) {
  10439. const auto pattern = "/users/:id";
  10440. detail::PathParamsMatcher matcher(pattern);
  10441. Request request;
  10442. request.path = "/users/42/subscriptions";
  10443. ASSERT_FALSE(matcher.match(request));
  10444. }
  10445. TEST(PathParamsTest, MissingTrailingParam) {
  10446. const auto pattern = "/users/:id";
  10447. detail::PathParamsMatcher matcher(pattern);
  10448. Request request;
  10449. request.path = "/users";
  10450. ASSERT_FALSE(matcher.match(request));
  10451. }
  10452. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10453. const auto pattern = "/users/:id/subscriptions";
  10454. detail::PathParamsMatcher matcher(pattern);
  10455. Request request;
  10456. request.path = "/users/subscriptions";
  10457. ASSERT_FALSE(matcher.match(request));
  10458. }
  10459. TEST(PathParamsTest, MultipleParams) {
  10460. const auto pattern = "/users/:userid/subscriptions/:subid";
  10461. detail::PathParamsMatcher matcher(pattern);
  10462. Request request;
  10463. request.path = "/users/42/subscriptions/2";
  10464. ASSERT_TRUE(matcher.match(request));
  10465. std::unordered_map<std::string, std::string> expected_params = {
  10466. {"userid", "42"}, {"subid", "2"}};
  10467. EXPECT_EQ(request.path_params, expected_params);
  10468. }
  10469. TEST(PathParamsTest, SequenceOfParams) {
  10470. const auto pattern = "/values/:x/:y/:z";
  10471. detail::PathParamsMatcher matcher(pattern);
  10472. Request request;
  10473. request.path = "/values/1/2/3";
  10474. ASSERT_TRUE(matcher.match(request));
  10475. std::unordered_map<std::string, std::string> expected_params = {
  10476. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10477. EXPECT_EQ(request.path_params, expected_params);
  10478. }
  10479. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10480. const auto pattern = "/prefix:suffix";
  10481. detail::PathParamsMatcher matcher(pattern);
  10482. Request request;
  10483. request.path = "/prefix:suffix";
  10484. ASSERT_TRUE(matcher.match(request));
  10485. const std::unordered_map<std::string, std::string> expected_params = {};
  10486. EXPECT_EQ(request.path_params, expected_params);
  10487. }
  10488. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10489. // If ipv6 regex working, regex match codepath is taken.
  10490. // else port will default to 80 in Client impl
  10491. int clientImplMagicPort = 80;
  10492. int port = 4321;
  10493. // above ports must be different to avoid false negative
  10494. EXPECT_NE(clientImplMagicPort, port);
  10495. std::string ipV6TestURL = "http://[ff06::c3]";
  10496. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10497. CLIENT_PRIVATE_KEY_FILE);
  10498. EXPECT_EQ(cli.port(), port);
  10499. }
  10500. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10501. auto file_path = "./www/dir/index.html";
  10502. auto dir_path = "./www/dir";
  10503. detail::FileStat stat_file(file_path);
  10504. EXPECT_TRUE(stat_file.is_file());
  10505. EXPECT_FALSE(stat_file.is_dir());
  10506. detail::FileStat stat_dir(dir_path);
  10507. EXPECT_FALSE(stat_dir.is_file());
  10508. EXPECT_TRUE(stat_dir.is_dir());
  10509. }
  10510. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10511. // IPv4 with default HTTP port (80)
  10512. EXPECT_EQ("example.com",
  10513. detail::make_host_and_port_string("example.com", 80, false));
  10514. // IPv4 with default HTTPS port (443)
  10515. EXPECT_EQ("example.com",
  10516. detail::make_host_and_port_string("example.com", 443, true));
  10517. // IPv4 with non-default HTTP port
  10518. EXPECT_EQ("example.com:8080",
  10519. detail::make_host_and_port_string("example.com", 8080, false));
  10520. // IPv4 with non-default HTTPS port
  10521. EXPECT_EQ("example.com:8443",
  10522. detail::make_host_and_port_string("example.com", 8443, true));
  10523. // IPv6 with default HTTP port (80)
  10524. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10525. // IPv6 with default HTTPS port (443)
  10526. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10527. // IPv6 with non-default HTTP port
  10528. EXPECT_EQ("[::1]:8080",
  10529. detail::make_host_and_port_string("::1", 8080, false));
  10530. // IPv6 with non-default HTTPS port
  10531. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10532. // IPv6 full address with default port
  10533. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10534. detail::make_host_and_port_string(
  10535. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10536. // IPv6 full address with non-default port
  10537. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10538. detail::make_host_and_port_string(
  10539. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10540. // IPv6 localhost with non-default port
  10541. EXPECT_EQ("[::1]:3000",
  10542. detail::make_host_and_port_string("::1", 3000, false));
  10543. // IPv6 with zone ID (link-local address) with default port
  10544. EXPECT_EQ("[fe80::1%eth0]",
  10545. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10546. // IPv6 with zone ID (link-local address) with non-default port
  10547. EXPECT_EQ("[fe80::1%eth0]:8080",
  10548. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10549. // Edge case: Port 443 with is_ssl=false (should add port)
  10550. EXPECT_EQ("example.com:443",
  10551. detail::make_host_and_port_string("example.com", 443, false));
  10552. // Edge case: Port 80 with is_ssl=true (should add port)
  10553. EXPECT_EQ("example.com:80",
  10554. detail::make_host_and_port_string("example.com", 80, true));
  10555. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10556. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10557. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10558. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10559. // Security fix: Already bracketed IPv6 should not get double brackets
  10560. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10561. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10562. EXPECT_EQ("[::1]:8080",
  10563. detail::make_host_and_port_string("[::1]", 8080, false));
  10564. EXPECT_EQ("[2001:db8::1]:8080",
  10565. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10566. EXPECT_EQ("[fe80::1%eth0]",
  10567. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10568. EXPECT_EQ("[fe80::1%eth0]:8080",
  10569. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10570. // Edge case: Empty host (should return as-is)
  10571. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10572. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10573. // This is a known limitation but shouldn't crash
  10574. EXPECT_EQ("[host:name]",
  10575. detail::make_host_and_port_string("host:name", 80, false));
  10576. // Port number edge cases (no validation, but should not crash)
  10577. EXPECT_EQ("example.com:0",
  10578. detail::make_host_and_port_string("example.com", 0, false));
  10579. EXPECT_EQ("example.com:-1",
  10580. detail::make_host_and_port_string("example.com", -1, false));
  10581. EXPECT_EQ("example.com:65535",
  10582. detail::make_host_and_port_string("example.com", 65535, false));
  10583. EXPECT_EQ("example.com:65536",
  10584. detail::make_host_and_port_string("example.com", 65536, false));
  10585. }
  10586. #ifdef CPPHTTPLIB_SSL_ENABLED
  10587. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10588. httplib::SSLClient cli("roblox.com", 443);
  10589. cli.set_follow_location(true);
  10590. auto res = cli.Get("/");
  10591. ASSERT_TRUE(res);
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. }
  10594. #endif
  10595. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10596. Server svr;
  10597. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10598. EXPECT_EQ(res.status, 400);
  10599. });
  10600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10601. auto se = detail::scope_exit([&] {
  10602. svr.stop();
  10603. thread.join();
  10604. ASSERT_FALSE(svr.is_running());
  10605. });
  10606. svr.wait_until_ready();
  10607. Client cli(HOST, PORT);
  10608. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10609. }
  10610. TEST(InvalidHeaderCharsTest, is_field_name) {
  10611. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10612. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10613. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10614. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10615. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10616. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10617. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10618. EXPECT_FALSE(detail::fields::is_field_name(""));
  10619. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10620. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10621. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10622. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10623. }
  10624. TEST(InvalidHeaderCharsTest, is_field_value) {
  10625. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10626. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10627. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10628. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10629. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10630. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10631. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10632. EXPECT_TRUE(detail::fields::is_field_value(""));
  10633. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10634. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10635. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10636. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10637. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10638. }
  10639. TEST(InvalidHeaderCharsTest, OnServer) {
  10640. Server svr;
  10641. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10642. std::string header = "Not Set";
  10643. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10644. res.set_header(header, "value");
  10645. res.set_content("Page Content Page Content", "text/plain");
  10646. });
  10647. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10648. std::string header = "Not Set";
  10649. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10650. res.set_header("X-Test", header);
  10651. res.set_content("Page Content Page Content", "text/plain");
  10652. });
  10653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. thread.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.wait_until_ready();
  10660. Client cli(HOST, PORT);
  10661. {
  10662. auto res = cli.Get(
  10663. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10664. ASSERT_TRUE(res);
  10665. EXPECT_EQ("Page Content Page Content", res->body);
  10666. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10667. }
  10668. {
  10669. auto res = cli.Get(
  10670. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10671. ASSERT_TRUE(res);
  10672. EXPECT_EQ("Page Content Page Content", res->body);
  10673. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10674. }
  10675. }
  10676. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10677. auto handled = false;
  10678. Server svr;
  10679. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10680. thread t = thread([&] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. t.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. ASSERT_FALSE(handled);
  10686. });
  10687. svr.wait_until_ready();
  10688. auto req = "POST /test HTTP/1.1\r\n"
  10689. "Content-Length: x\r\n"
  10690. "\r\n";
  10691. std::string response;
  10692. ASSERT_TRUE(send_request(1, req, &response));
  10693. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10694. response.substr(0, response.find("\r\n")));
  10695. }
  10696. #ifndef _WIN32
  10697. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10698. static constexpr char reject[] = "Unauthorized";
  10699. static constexpr char accept[] = "Upload accepted";
  10700. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10701. Server svr;
  10702. svr.set_expect_100_continue_handler(
  10703. [](const Request & /*req*/, Response &res) {
  10704. res.status = StatusCode::Unauthorized_401;
  10705. res.set_content(reject, "text/plain");
  10706. return res.status;
  10707. });
  10708. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10709. res.set_content(accept, "text/plain");
  10710. });
  10711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10712. auto se = detail::scope_exit([&] {
  10713. svr.stop();
  10714. thread.join();
  10715. ASSERT_FALSE(svr.is_running());
  10716. });
  10717. svr.wait_until_ready();
  10718. {
  10719. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10720. curl_easy_init(), &curl_easy_cleanup};
  10721. ASSERT_NE(curl, nullptr);
  10722. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10723. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10724. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10725. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10726. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10727. &curl_slist_free_all};
  10728. ASSERT_NE(list, nullptr);
  10729. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10730. struct read_data {
  10731. size_t read_size;
  10732. size_t total_size;
  10733. } data = {0, total_size};
  10734. using read_callback_t =
  10735. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10736. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10737. void *userdata) -> size_t {
  10738. read_data *data = (read_data *)userdata;
  10739. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10740. std::fill_n(ptr, size * nmemb, 'A');
  10741. data->read_size += size * nmemb;
  10742. return size * nmemb;
  10743. };
  10744. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10745. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10746. std::vector<char> buffer;
  10747. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10748. using write_callback_t =
  10749. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10750. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10751. void *userdata) -> size_t {
  10752. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10753. buffer->reserve(buffer->size() + size * nmemb + 1);
  10754. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10755. return size * nmemb;
  10756. };
  10757. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10758. {
  10759. const auto res = curl_easy_perform(curl.get());
  10760. ASSERT_EQ(res, CURLE_OK);
  10761. }
  10762. {
  10763. auto response_code = long{};
  10764. const auto res =
  10765. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10766. ASSERT_EQ(res, CURLE_OK);
  10767. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10768. }
  10769. {
  10770. auto dl = curl_off_t{};
  10771. const auto res =
  10772. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10773. ASSERT_EQ(res, CURLE_OK);
  10774. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10775. }
  10776. {
  10777. buffer.push_back('\0');
  10778. ASSERT_STRCASEEQ(buffer.data(), reject);
  10779. }
  10780. }
  10781. }
  10782. #endif
  10783. template <typename S, typename C>
  10784. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10785. svr.Get("/stream", [&](const Request &, Response &res) {
  10786. auto data = new std::string("01234567890123456789");
  10787. res.set_content_provider(
  10788. data->size(), "text/plain",
  10789. [&, data](size_t offset, size_t length, DataSink &sink) {
  10790. const size_t DATA_CHUNK_SIZE = 4;
  10791. const auto &d = *data;
  10792. std::this_thread::sleep_for(std::chrono::seconds(1));
  10793. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10794. return true;
  10795. },
  10796. [data](bool success) {
  10797. EXPECT_FALSE(success);
  10798. delete data;
  10799. });
  10800. });
  10801. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10802. auto i = new size_t(0);
  10803. res.set_content_provider(
  10804. "text/plain",
  10805. [i](size_t, DataSink &sink) {
  10806. if (*i < 5) {
  10807. std::this_thread::sleep_for(std::chrono::seconds(1));
  10808. sink.write("abcd", 4);
  10809. (*i)++;
  10810. } else {
  10811. sink.done();
  10812. }
  10813. return true;
  10814. },
  10815. [i](bool success) {
  10816. EXPECT_FALSE(success);
  10817. delete i;
  10818. });
  10819. });
  10820. svr.Get("/chunked", [&](const Request &, Response &res) {
  10821. auto i = new size_t(0);
  10822. res.set_chunked_content_provider(
  10823. "text/plain",
  10824. [i](size_t, DataSink &sink) {
  10825. if (*i < 5) {
  10826. std::this_thread::sleep_for(std::chrono::seconds(1));
  10827. sink.os << "abcd";
  10828. (*i)++;
  10829. } else {
  10830. sink.done();
  10831. }
  10832. return true;
  10833. },
  10834. [i](bool success) {
  10835. EXPECT_FALSE(success);
  10836. delete i;
  10837. });
  10838. });
  10839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. listen_thread.join();
  10843. ASSERT_FALSE(svr.is_running());
  10844. });
  10845. svr.wait_until_ready();
  10846. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10847. {
  10848. auto start = std::chrono::steady_clock::now();
  10849. auto res = cli.Get("/stream");
  10850. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10851. std::chrono::steady_clock::now() - start)
  10852. .count();
  10853. ASSERT_FALSE(res);
  10854. EXPECT_EQ(Error::Read, res.error());
  10855. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10856. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10857. }
  10858. {
  10859. auto start = std::chrono::steady_clock::now();
  10860. auto res = cli.Get("/stream_without_length");
  10861. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10862. std::chrono::steady_clock::now() - start)
  10863. .count();
  10864. ASSERT_FALSE(res);
  10865. EXPECT_EQ(Error::Read, res.error());
  10866. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10867. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10868. }
  10869. {
  10870. auto start = std::chrono::steady_clock::now();
  10871. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10872. EXPECT_EQ("abcd", string(data, data_length));
  10873. return true;
  10874. });
  10875. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10876. std::chrono::steady_clock::now() - start)
  10877. .count();
  10878. ASSERT_FALSE(res);
  10879. EXPECT_EQ(Error::Read, res.error());
  10880. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10881. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10882. }
  10883. }
  10884. TEST(MaxTimeoutTest, ContentStream) {
  10885. time_t timeout = 2000;
  10886. time_t threshold = 200;
  10887. Server svr;
  10888. Client cli("localhost", PORT);
  10889. max_timeout_test(svr, cli, timeout, threshold);
  10890. }
  10891. #ifdef CPPHTTPLIB_SSL_ENABLED
  10892. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10893. time_t timeout = 2000;
  10894. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10896. SSLClient cli("localhost", PORT);
  10897. cli.enable_server_certificate_verification(false);
  10898. max_timeout_test(svr, cli, timeout, threshold);
  10899. }
  10900. #endif
  10901. class EventDispatcher {
  10902. public:
  10903. EventDispatcher() {}
  10904. bool wait_event(DataSink *sink) {
  10905. unique_lock<mutex> lk(m_);
  10906. int id = id_;
  10907. // Wait with timeout to prevent hanging if client disconnects
  10908. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10909. [&] { return cid_ == id; })) {
  10910. return false; // Timeout occurred
  10911. }
  10912. sink->write(message_.data(), message_.size());
  10913. return true;
  10914. }
  10915. void send_event(const string &message) {
  10916. lock_guard<mutex> lk(m_);
  10917. cid_ = id_++;
  10918. message_ = message;
  10919. cv_.notify_all();
  10920. }
  10921. private:
  10922. mutex m_;
  10923. condition_variable cv_;
  10924. atomic_int id_{0};
  10925. atomic_int cid_{-1};
  10926. string message_;
  10927. };
  10928. TEST(ClientInThreadTest, Issue2068) {
  10929. EventDispatcher ed;
  10930. Server svr;
  10931. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10932. res.set_chunked_content_provider("text/event-stream",
  10933. [&](size_t /*offset*/, DataSink &sink) {
  10934. return ed.wait_event(&sink);
  10935. });
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10938. svr.wait_until_ready();
  10939. thread event_thread([&] {
  10940. int id = 0;
  10941. while (svr.is_running()) {
  10942. this_thread::sleep_for(chrono::milliseconds(500));
  10943. std::stringstream ss;
  10944. ss << "data: " << id << "\n\n";
  10945. ed.send_event(ss.str());
  10946. id++;
  10947. }
  10948. });
  10949. auto se = detail::scope_exit([&] {
  10950. svr.stop();
  10951. listen_thread.join();
  10952. event_thread.join();
  10953. ASSERT_FALSE(svr.is_running());
  10954. });
  10955. {
  10956. auto client = detail::make_unique<Client>(HOST, PORT);
  10957. client->set_read_timeout(std::chrono::minutes(10));
  10958. std::atomic<bool> stop{false};
  10959. std::thread t([&] {
  10960. client->Get("/event1",
  10961. [&](const char *, size_t) -> bool { return !stop; });
  10962. });
  10963. std::this_thread::sleep_for(std::chrono::seconds(2));
  10964. stop = true;
  10965. client->stop();
  10966. t.join();
  10967. // Reset client after thread has finished
  10968. client.reset();
  10969. }
  10970. }
  10971. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10972. auto handled = false;
  10973. Server svr;
  10974. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10976. auto se = detail::scope_exit([&] {
  10977. svr.stop();
  10978. t.join();
  10979. ASSERT_FALSE(svr.is_running());
  10980. ASSERT_FALSE(handled);
  10981. });
  10982. svr.wait_until_ready();
  10983. // Two Content-Length headers with different values — must be rejected
  10984. auto req = "POST /test HTTP/1.1\r\n"
  10985. "Content-Length: 5\r\n"
  10986. "Content-Length: 10\r\n"
  10987. "\r\n"
  10988. "hello";
  10989. std::string response;
  10990. ASSERT_TRUE(send_request(1, req, &response));
  10991. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10992. response.substr(0, response.find("\r\n")));
  10993. }
  10994. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10995. auto handled = false;
  10996. Server svr;
  10997. svr.Post("/test", [&](const Request &, Response &res) {
  10998. handled = true;
  10999. res.set_content("ok", "text/plain");
  11000. });
  11001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11002. auto se = detail::scope_exit([&] {
  11003. svr.stop();
  11004. t.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. ASSERT_TRUE(handled);
  11007. });
  11008. svr.wait_until_ready();
  11009. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11010. auto req = "POST /test HTTP/1.1\r\n"
  11011. "Content-Length: 5\r\n"
  11012. "Content-Length: 5\r\n"
  11013. "\r\n"
  11014. "hello";
  11015. std::string response;
  11016. ASSERT_TRUE(send_request(1, req, &response));
  11017. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11018. }
  11019. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11020. Server svr;
  11021. svr.Get("/", [](const Request &req, Response &res) {
  11022. EXPECT_EQ(2U, req.trailers.size());
  11023. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11024. // Denied
  11025. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11026. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11027. // Accepted
  11028. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11029. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11030. EXPECT_TRUE(req.has_trailer("X-World"));
  11031. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11032. res.set_content("ok", "text/plain");
  11033. });
  11034. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11035. auto se = detail::scope_exit([&] {
  11036. svr.stop();
  11037. t.join();
  11038. ASSERT_FALSE(svr.is_running());
  11039. });
  11040. svr.wait_until_ready();
  11041. const std::string req = "GET / HTTP/1.1\r\n"
  11042. "Transfer-Encoding: chunked\r\n"
  11043. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11044. "\r\n"
  11045. "0\r\n"
  11046. "Content-Length: 10\r\n"
  11047. "Host: internal.local\r\n"
  11048. "Content-Type: malicious/content\r\n"
  11049. "Cookie: any\r\n"
  11050. "Set-Cookie: any\r\n"
  11051. "X-Forwarded-For: attacker.com\r\n"
  11052. "X-Real-Ip: 1.1.1.1\r\n"
  11053. "X-Hello: hello\r\n"
  11054. "X-World: world\r\n"
  11055. "\r\n";
  11056. std::string res;
  11057. ASSERT_TRUE(send_request(1, req, &res));
  11058. }
  11059. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11060. Server svr;
  11061. std::string observed_remote_addr;
  11062. std::string observed_xff;
  11063. svr.Get("/ip", [&](const Request &req, Response &res) {
  11064. observed_remote_addr = req.remote_addr;
  11065. observed_xff = req.get_header_value("X-Forwarded-For");
  11066. res.set_content("ok", "text/plain");
  11067. });
  11068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. Client cli(HOST, PORT);
  11076. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11077. ASSERT_TRUE(res);
  11078. EXPECT_EQ(StatusCode::OK_200, res->status);
  11079. EXPECT_EQ(observed_xff, "203.0.113.66");
  11080. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11081. observed_remote_addr == "127.0.0.1");
  11082. }
  11083. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11084. Server svr;
  11085. svr.set_trusted_proxies({"203.0.113.66"});
  11086. std::string observed_remote_addr;
  11087. std::string observed_xff;
  11088. svr.Get("/ip", [&](const Request &req, Response &res) {
  11089. observed_remote_addr = req.remote_addr;
  11090. observed_xff = req.get_header_value("X-Forwarded-For");
  11091. res.set_content("ok", "text/plain");
  11092. });
  11093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11094. auto se = detail::scope_exit([&] {
  11095. svr.stop();
  11096. t.join();
  11097. ASSERT_FALSE(svr.is_running());
  11098. });
  11099. svr.wait_until_ready();
  11100. Client cli(HOST, PORT);
  11101. auto res = cli.Get("/ip");
  11102. ASSERT_TRUE(res);
  11103. EXPECT_EQ(StatusCode::OK_200, res->status);
  11104. EXPECT_EQ(observed_xff, "");
  11105. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11106. observed_remote_addr == "127.0.0.1");
  11107. }
  11108. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11109. Server svr;
  11110. svr.set_trusted_proxies({"203.0.113.66"});
  11111. std::string observed_remote_addr;
  11112. std::string observed_xff;
  11113. svr.Get("/ip", [&](const Request &req, Response &res) {
  11114. observed_remote_addr = req.remote_addr;
  11115. observed_xff = req.get_header_value("X-Forwarded-For");
  11116. res.set_content("ok", "text/plain");
  11117. });
  11118. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. Client cli(HOST, PORT);
  11126. auto res =
  11127. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11128. ASSERT_TRUE(res);
  11129. EXPECT_EQ(StatusCode::OK_200, res->status);
  11130. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11131. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11132. }
  11133. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11134. Server svr;
  11135. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11136. std::string observed_remote_addr;
  11137. std::string observed_xff;
  11138. svr.Get("/ip", [&](const Request &req, Response &res) {
  11139. observed_remote_addr = req.remote_addr;
  11140. observed_xff = req.get_header_value("X-Forwarded-For");
  11141. res.set_content("ok", "text/plain");
  11142. });
  11143. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. Client cli(HOST, PORT);
  11151. auto res = cli.Get(
  11152. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11153. ASSERT_TRUE(res);
  11154. EXPECT_EQ(StatusCode::OK_200, res->status);
  11155. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11156. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11157. }
  11158. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11159. Server svr;
  11160. svr.set_trusted_proxies({"192.0.2.45"});
  11161. std::string observed_remote_addr;
  11162. std::string observed_xff;
  11163. svr.Get("/ip", [&](const Request &req, Response &res) {
  11164. observed_remote_addr = req.remote_addr;
  11165. observed_xff = req.get_header_value("X-Forwarded-For");
  11166. res.set_content("ok", "text/plain");
  11167. });
  11168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11169. auto se = detail::scope_exit([&] {
  11170. svr.stop();
  11171. t.join();
  11172. ASSERT_FALSE(svr.is_running());
  11173. });
  11174. svr.wait_until_ready();
  11175. Client cli(HOST, PORT);
  11176. auto res =
  11177. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11178. ASSERT_TRUE(res);
  11179. EXPECT_EQ(StatusCode::OK_200, res->status);
  11180. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11181. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11182. }
  11183. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11184. Server svr;
  11185. svr.set_trusted_proxies({"192.0.2.45"});
  11186. std::string observed_remote_addr;
  11187. std::string observed_xff;
  11188. svr.Get("/ip", [&](const Request &req, Response &res) {
  11189. observed_remote_addr = req.remote_addr;
  11190. observed_xff = req.get_header_value("X-Forwarded-For");
  11191. res.set_content("ok", "text/plain");
  11192. });
  11193. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11194. auto se = detail::scope_exit([&] {
  11195. svr.stop();
  11196. t.join();
  11197. ASSERT_FALSE(svr.is_running());
  11198. });
  11199. svr.wait_until_ready();
  11200. Client cli(HOST, PORT);
  11201. auto res = cli.Get(
  11202. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11203. ASSERT_TRUE(res);
  11204. EXPECT_EQ(StatusCode::OK_200, res->status);
  11205. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11206. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11207. }
  11208. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11209. Server svr;
  11210. svr.set_trusted_proxies({"192.0.2.45"});
  11211. std::string observed_remote_addr;
  11212. std::string observed_xff;
  11213. svr.Get("/ip", [&](const Request &req, Response &res) {
  11214. observed_remote_addr = req.remote_addr;
  11215. observed_xff = req.get_header_value("X-Forwarded-For");
  11216. res.set_content("ok", "text/plain");
  11217. });
  11218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. t.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. std::string raw_req =
  11226. "GET /ip HTTP/1.1\r\n"
  11227. "Host: localhost\r\n"
  11228. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11229. "Connection: close\r\n"
  11230. "\r\n";
  11231. std::string out;
  11232. ASSERT_TRUE(send_request(5, raw_req, &out));
  11233. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11234. // Header parser trims surrounding whitespace of the header value
  11235. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11236. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11237. }
  11238. #ifndef _WIN32
  11239. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11240. Server svr;
  11241. svr.Post("/post", [&](const Request &req, Response &res) {
  11242. res.set_content(req.body, "text/plain");
  11243. });
  11244. svr.Put("/put", [&](const Request &req, Response &res) {
  11245. res.set_content(req.body, "text/plain");
  11246. });
  11247. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11248. res.set_content(req.body, "text/plain");
  11249. });
  11250. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11251. res.set_content(req.body, "text/plain");
  11252. });
  11253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. t.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. });
  11259. svr.wait_until_ready();
  11260. std::string resp;
  11261. // POST without Content-Length
  11262. ASSERT_TRUE(send_request(5,
  11263. "POST /post HTTP/1.1\r\n"
  11264. "Host: localhost\r\n"
  11265. "Connection: close\r\n"
  11266. "\r\n",
  11267. &resp));
  11268. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11269. // PUT without Content-Length
  11270. resp.clear();
  11271. ASSERT_TRUE(send_request(5,
  11272. "PUT /put HTTP/1.1\r\n"
  11273. "Host: localhost\r\n"
  11274. "Connection: close\r\n"
  11275. "\r\n",
  11276. &resp));
  11277. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11278. // PATCH without Content-Length
  11279. resp.clear();
  11280. ASSERT_TRUE(send_request(5,
  11281. "PATCH /patch HTTP/1.1\r\n"
  11282. "Host: localhost\r\n"
  11283. "Connection: close\r\n"
  11284. "\r\n",
  11285. &resp));
  11286. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11287. // DELETE without Content-Length
  11288. resp.clear();
  11289. ASSERT_TRUE(send_request(5,
  11290. "DELETE /delete HTTP/1.1\r\n"
  11291. "Host: localhost\r\n"
  11292. "Connection: close\r\n"
  11293. "\r\n",
  11294. &resp));
  11295. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11296. }
  11297. #endif
  11298. //==============================================================================
  11299. // open_stream() Tests
  11300. //==============================================================================
  11301. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11302. std::string result;
  11303. char buf[8192];
  11304. ssize_t n;
  11305. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11306. result.append(buf, static_cast<size_t>(n));
  11307. }
  11308. return result;
  11309. }
  11310. // Mock stream for unit tests
  11311. class MockStream : public Stream {
  11312. public:
  11313. std::string data;
  11314. size_t pos = 0;
  11315. ssize_t error_after = -1; // -1 = no error
  11316. explicit MockStream(const std::string &d, ssize_t err = -1)
  11317. : data(d), error_after(err) {}
  11318. bool is_readable() const override { return true; }
  11319. bool wait_readable() const override { return true; }
  11320. bool wait_writable() const override { return true; }
  11321. ssize_t read(char *ptr, size_t size) override {
  11322. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11323. if (pos >= data.size()) return 0;
  11324. size_t limit =
  11325. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11326. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11327. std::memcpy(ptr, data.data() + pos, to_read);
  11328. pos += to_read;
  11329. return static_cast<ssize_t>(to_read);
  11330. }
  11331. ssize_t write(const char *, size_t) override { return -1; }
  11332. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11333. ip = "127.0.0.1";
  11334. port = 0;
  11335. }
  11336. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11337. ip = "127.0.0.1";
  11338. port = 0;
  11339. }
  11340. socket_t socket() const override { return INVALID_SOCKET; }
  11341. time_t duration() const override { return 0; }
  11342. };
  11343. TEST(StreamHandleTest, Basic) {
  11344. ClientImpl::StreamHandle handle;
  11345. EXPECT_FALSE(handle.is_valid());
  11346. handle.response = detail::make_unique<Response>();
  11347. handle.error = Error::Connection;
  11348. EXPECT_FALSE(handle.is_valid());
  11349. handle.error = Error::Success;
  11350. EXPECT_TRUE(handle.is_valid());
  11351. }
  11352. TEST(BodyReaderTest, Basic) {
  11353. MockStream stream("Hello, World!");
  11354. detail::BodyReader reader;
  11355. reader.stream = &stream;
  11356. reader.content_length = 13;
  11357. char buf[32];
  11358. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11359. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11360. EXPECT_TRUE(reader.eof);
  11361. }
  11362. TEST(BodyReaderTest, NoStream) {
  11363. detail::BodyReader reader;
  11364. char buf[32];
  11365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11366. EXPECT_EQ(Error::Connection, reader.last_error);
  11367. }
  11368. TEST(BodyReaderTest, Error) {
  11369. MockStream stream("Hello, World!", 5);
  11370. detail::BodyReader reader;
  11371. reader.stream = &stream;
  11372. reader.content_length = 13;
  11373. char buf[32];
  11374. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11375. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11376. EXPECT_EQ(Error::Read, reader.last_error);
  11377. }
  11378. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11379. // Mock-based StreamHandle tests relying on private internals are removed.
  11380. class OpenStreamTest : public ::testing::Test {
  11381. protected:
  11382. void SetUp() override {
  11383. svr_.Get("/hello", [](const Request &, Response &res) {
  11384. res.set_content("Hello World!", "text/plain");
  11385. });
  11386. svr_.Get("/large", [](const Request &, Response &res) {
  11387. res.set_content(std::string(10000, 'X'), "text/plain");
  11388. });
  11389. svr_.Get("/chunked", [](const Request &, Response &res) {
  11390. res.set_chunked_content_provider("text/plain",
  11391. [](size_t offset, DataSink &sink) {
  11392. if (offset < 15) {
  11393. sink.write("chunk", 5);
  11394. return true;
  11395. }
  11396. sink.done();
  11397. return true;
  11398. });
  11399. });
  11400. svr_.Get("/compressible", [](const Request &, Response &res) {
  11401. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11402. DataSink &sink) {
  11403. if (offset < 100 * 1024) {
  11404. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11405. sink.write(chunk.data(), chunk.size());
  11406. return true;
  11407. }
  11408. sink.done();
  11409. return true;
  11410. });
  11411. });
  11412. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11413. [](const Request & /*req*/, Response &res) {
  11414. auto i = new int(0);
  11415. res.set_header("Trailer", "Content-Length, X-Allowed");
  11416. res.set_chunked_content_provider(
  11417. "text/plain",
  11418. [i](size_t /*offset*/, DataSink &sink) {
  11419. switch (*i) {
  11420. case 0: sink.os << "123"; break;
  11421. case 1: sink.os << "456"; break;
  11422. case 2: sink.os << "789"; break;
  11423. case 3: {
  11424. sink.done_with_trailer(
  11425. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11426. } break;
  11427. }
  11428. (*i)++;
  11429. return true;
  11430. },
  11431. [i](bool success) {
  11432. EXPECT_TRUE(success);
  11433. delete i;
  11434. });
  11435. });
  11436. // Echo headers endpoint for header-related tests
  11437. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11438. std::string body;
  11439. for (const auto &h : req.headers) {
  11440. body.append(h.first);
  11441. body.push_back(':');
  11442. body.append(h.second);
  11443. body.push_back('\n');
  11444. }
  11445. res.set_content(body, "text/plain");
  11446. });
  11447. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11448. std::string body;
  11449. for (const auto &h : req.headers) {
  11450. body.append(h.first);
  11451. body.push_back(':');
  11452. body.append(h.second);
  11453. body.push_back('\n');
  11454. }
  11455. res.set_content(body, "text/plain");
  11456. });
  11457. port_ = svr_.bind_to_any_port("127.0.0.1");
  11458. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11459. svr_.wait_until_ready();
  11460. }
  11461. void TearDown() override {
  11462. svr_.stop();
  11463. if (thread_.joinable()) thread_.join();
  11464. }
  11465. Server svr_;
  11466. std::thread thread_;
  11467. int port_ = 0;
  11468. };
  11469. TEST_F(OpenStreamTest, Basic) {
  11470. Client cli("127.0.0.1", port_);
  11471. auto handle = cli.open_stream("GET", "/hello");
  11472. EXPECT_TRUE(handle.is_valid());
  11473. EXPECT_EQ("Hello World!", read_all(handle));
  11474. }
  11475. TEST_F(OpenStreamTest, SmallBuffer) {
  11476. Client cli("127.0.0.1", port_);
  11477. auto handle = cli.open_stream("GET", "/hello");
  11478. std::string result;
  11479. char buf[4];
  11480. ssize_t n;
  11481. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11482. result.append(buf, static_cast<size_t>(n));
  11483. EXPECT_EQ("Hello World!", result);
  11484. }
  11485. TEST_F(OpenStreamTest, DefaultHeaders) {
  11486. Client cli("127.0.0.1", port_);
  11487. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11488. {
  11489. auto handle = cli.open_stream("GET", "/echo-headers");
  11490. ASSERT_TRUE(handle.is_valid());
  11491. auto body = read_all(handle);
  11492. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11493. std::string::npos);
  11494. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11495. std::string::npos);
  11496. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11497. }
  11498. // open_stream POST with body and no explicit content_type should NOT add
  11499. // text/plain Content-Type (behavior differs from non-streaming path), but
  11500. // should include Content-Length
  11501. {
  11502. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11503. ASSERT_TRUE(handle.is_valid());
  11504. auto body = read_all(handle);
  11505. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11506. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11507. }
  11508. // open_stream POST with explicit Content-Type should preserve it
  11509. {
  11510. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11511. {{"Content-Type", "application/custom"}},
  11512. "{}", "application/custom");
  11513. ASSERT_TRUE(handle.is_valid());
  11514. auto body = read_all(handle);
  11515. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11516. }
  11517. // User-specified User-Agent must not be overwritten for stream API
  11518. {
  11519. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11520. {{"User-Agent", "MyAgent/1.2"}});
  11521. ASSERT_TRUE(handle.is_valid());
  11522. auto body = read_all(handle);
  11523. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11524. }
  11525. }
  11526. TEST_F(OpenStreamTest, Large) {
  11527. Client cli("127.0.0.1", port_);
  11528. auto handle = cli.open_stream("GET", "/large");
  11529. EXPECT_EQ(10000u, read_all(handle).size());
  11530. }
  11531. TEST_F(OpenStreamTest, ConnectionError) {
  11532. Client cli("127.0.0.1", 9999);
  11533. auto handle = cli.open_stream("GET", "/hello");
  11534. EXPECT_FALSE(handle.is_valid());
  11535. }
  11536. TEST_F(OpenStreamTest, Chunked) {
  11537. Client cli("127.0.0.1", port_);
  11538. auto handle = cli.open_stream("GET", "/chunked");
  11539. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11540. "Transfer-Encoding") == "chunked");
  11541. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11542. }
  11543. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11544. Client cli("127.0.0.1", port_);
  11545. auto handle =
  11546. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11547. ASSERT_TRUE(handle.is_valid());
  11548. // Consume body to allow trailers to be received/parsed
  11549. auto body = read_all(handle);
  11550. // Explicitly parse trailers (ensure trailers are available for assertion)
  11551. handle.parse_trailers_if_needed();
  11552. EXPECT_EQ(std::string("123456789"), body);
  11553. // The response should include a Trailer header declaring both names
  11554. ASSERT_TRUE(handle.response);
  11555. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11556. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11557. handle.response->get_header_value("Trailer"));
  11558. // Prohibited trailer must not be present
  11559. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11560. // Allowed trailer should be present
  11561. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11562. EXPECT_EQ(std::string("yes"),
  11563. handle.response->get_trailer_value("X-Allowed"));
  11564. // Verify trailers are NOT present as regular headers
  11565. EXPECT_EQ(std::string(""),
  11566. handle.response->get_header_value("Content-Length"));
  11567. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11568. }
  11569. static std::thread serve_single_response(std::promise<int> &port_promise,
  11570. const std::string &response) {
  11571. return std::thread([&port_promise, response] {
  11572. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11573. default_socket_options(srv);
  11574. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11575. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11576. sockaddr_in addr{};
  11577. addr.sin_family = AF_INET;
  11578. addr.sin_port = htons(0); // Let OS assign a free port
  11579. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11580. int opt = 1;
  11581. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11582. #ifdef _WIN32
  11583. reinterpret_cast<const char *>(&opt),
  11584. #else
  11585. &opt,
  11586. #endif
  11587. sizeof(opt));
  11588. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11589. ::listen(srv, 1) != 0) {
  11590. port_promise.set_value(-1);
  11591. detail::close_socket(srv);
  11592. return;
  11593. }
  11594. socklen_t addr_len = sizeof(addr);
  11595. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11596. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11597. sockaddr_in cli_addr{};
  11598. socklen_t cli_len = sizeof(cli_addr);
  11599. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11600. if (cli != INVALID_SOCKET) {
  11601. char buf[4096];
  11602. ::recv(cli, buf, sizeof(buf), 0);
  11603. ::send(cli,
  11604. #ifdef _WIN32
  11605. static_cast<const char *>(response.c_str()),
  11606. static_cast<int>(response.size()),
  11607. #else
  11608. response.c_str(), response.size(),
  11609. #endif
  11610. 0);
  11611. detail::close_socket(cli);
  11612. }
  11613. detail::close_socket(srv);
  11614. });
  11615. }
  11616. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11617. #ifndef _WIN32
  11618. signal(SIGPIPE, SIG_IGN);
  11619. #endif
  11620. std::promise<int> port_promise;
  11621. auto port_future = port_promise.get_future();
  11622. auto server_thread =
  11623. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11624. "Content-Type: text/plain\r\n"
  11625. "Content-Length: not-a-number\r\n"
  11626. "Connection: close\r\n"
  11627. "\r\n"
  11628. "hello");
  11629. auto port = port_future.get();
  11630. ASSERT_GT(port, 0);
  11631. Client cli("127.0.0.1", port);
  11632. auto handle = cli.open_stream("GET", "/");
  11633. EXPECT_FALSE(handle.is_valid());
  11634. server_thread.join();
  11635. }
  11636. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11637. #ifndef _WIN32
  11638. signal(SIGPIPE, SIG_IGN);
  11639. #endif
  11640. std::promise<int> port_promise;
  11641. auto port_future = port_promise.get_future();
  11642. auto server_thread = serve_single_response(
  11643. port_promise, "HTTP/1.1 200 OK\r\n"
  11644. "Content-Type: text/plain\r\n"
  11645. "Content-Length: 99999999999999999999999999\r\n"
  11646. "Connection: close\r\n"
  11647. "\r\n"
  11648. "hello");
  11649. auto port = port_future.get();
  11650. ASSERT_GT(port, 0);
  11651. // Before the fix, std::stoull would throw std::out_of_range here and
  11652. // crash the process. After the fix, strtoull silently clamps to
  11653. // ULLONG_MAX so the stream opens without crashing. The important thing
  11654. // is that the process does NOT terminate.
  11655. Client cli("127.0.0.1", port);
  11656. auto handle = cli.open_stream("GET", "/");
  11657. EXPECT_TRUE(handle.is_valid());
  11658. server_thread.join();
  11659. }
  11660. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11661. TEST_F(OpenStreamTest, Gzip) {
  11662. Client cli("127.0.0.1", port_);
  11663. auto handle = cli.open_stream("GET", "/compressible", {},
  11664. {{"Accept-Encoding", "gzip"}});
  11665. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11666. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11667. }
  11668. #endif
  11669. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11670. TEST_F(OpenStreamTest, Brotli) {
  11671. Client cli("127.0.0.1", port_);
  11672. auto handle =
  11673. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11674. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11675. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11676. }
  11677. #endif
  11678. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11679. TEST_F(OpenStreamTest, Zstd) {
  11680. Client cli("127.0.0.1", port_);
  11681. auto handle = cli.open_stream("GET", "/compressible", {},
  11682. {{"Accept-Encoding", "zstd"}});
  11683. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11684. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11685. }
  11686. #endif
  11687. #ifdef CPPHTTPLIB_SSL_ENABLED
  11688. class SSLOpenStreamTest : public ::testing::Test {
  11689. protected:
  11690. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11691. void SetUp() override {
  11692. svr_.Get("/hello", [](const Request &, Response &res) {
  11693. res.set_content("Hello SSL World!", "text/plain");
  11694. });
  11695. svr_.Get("/chunked", [](const Request &, Response &res) {
  11696. res.set_chunked_content_provider("text/plain",
  11697. [](size_t offset, DataSink &sink) {
  11698. if (offset < 15) {
  11699. sink.write("chunk", 5);
  11700. return true;
  11701. }
  11702. sink.done();
  11703. return true;
  11704. });
  11705. });
  11706. svr_.Post("/echo", [](const Request &req, Response &res) {
  11707. res.set_content(req.body, req.get_header_value("Content-Type"));
  11708. });
  11709. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11710. std::string body = req.body;
  11711. res.set_chunked_content_provider(
  11712. "text/plain", [body](size_t offset, DataSink &sink) {
  11713. if (offset < body.size()) {
  11714. sink.write(body.data() + offset, body.size() - offset);
  11715. }
  11716. sink.done();
  11717. return true;
  11718. });
  11719. });
  11720. port_ = svr_.bind_to_any_port("127.0.0.1");
  11721. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11722. svr_.wait_until_ready();
  11723. }
  11724. void TearDown() override {
  11725. svr_.stop();
  11726. if (thread_.joinable()) thread_.join();
  11727. }
  11728. SSLServer svr_;
  11729. std::thread thread_;
  11730. int port_ = 0;
  11731. };
  11732. TEST_F(SSLOpenStreamTest, Basic) {
  11733. SSLClient cli("127.0.0.1", port_);
  11734. cli.enable_server_certificate_verification(false);
  11735. auto handle = cli.open_stream("GET", "/hello");
  11736. ASSERT_TRUE(handle.is_valid());
  11737. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11738. }
  11739. TEST_F(SSLOpenStreamTest, Chunked) {
  11740. SSLClient cli("127.0.0.1", port_);
  11741. cli.enable_server_certificate_verification(false);
  11742. auto handle = cli.open_stream("GET", "/chunked");
  11743. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11744. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11745. "Transfer-Encoding") == "chunked");
  11746. auto body = read_all(handle);
  11747. EXPECT_EQ("chunkchunkchunk", body);
  11748. }
  11749. TEST_F(SSLOpenStreamTest, Post) {
  11750. SSLClient cli("127.0.0.1", port_);
  11751. cli.enable_server_certificate_verification(false);
  11752. auto handle =
  11753. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11754. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11755. EXPECT_EQ(200, handle.response->status);
  11756. auto body = read_all(handle);
  11757. EXPECT_EQ("Hello SSL POST", body);
  11758. }
  11759. TEST_F(SSLOpenStreamTest, PostChunked) {
  11760. SSLClient cli("127.0.0.1", port_);
  11761. cli.enable_server_certificate_verification(false);
  11762. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11763. "Chunked SSL Data", "text/plain");
  11764. ASSERT_TRUE(handle.is_valid());
  11765. EXPECT_EQ(200, handle.response->status);
  11766. auto body = read_all(handle);
  11767. EXPECT_EQ("Chunked SSL Data", body);
  11768. }
  11769. #endif // CPPHTTPLIB_SSL_ENABLED
  11770. //==============================================================================
  11771. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11772. // results for various scenarios.
  11773. //==============================================================================
  11774. TEST(ParityTest, GetVsOpenStream) {
  11775. Server svr;
  11776. const std::string path = "/parity";
  11777. const std::string content = "Parity test content: hello world";
  11778. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11779. res.set_content(content, "text/plain");
  11780. });
  11781. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11782. auto se = detail::scope_exit([&] {
  11783. svr.stop();
  11784. t.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. });
  11787. svr.wait_until_ready();
  11788. Client cli(HOST, PORT);
  11789. // Non-stream path
  11790. auto r1 = cli.Get(path);
  11791. ASSERT_TRUE(r1);
  11792. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11793. // Stream path
  11794. auto h = cli.open_stream("GET", path);
  11795. ASSERT_TRUE(h.is_valid());
  11796. EXPECT_EQ(r1->body, read_all(h));
  11797. }
  11798. // Helper to compress data with provided compressor type T
  11799. template <typename Compressor>
  11800. static std::string compress_payload_for_parity(const std::string &in) {
  11801. std::string out;
  11802. Compressor compressor;
  11803. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11804. [&](const char *data, size_t n) {
  11805. out.append(data, n);
  11806. return true;
  11807. });
  11808. EXPECT_TRUE(ok);
  11809. return out;
  11810. }
  11811. // Helper function for compression parity tests
  11812. template <typename Compressor>
  11813. static void test_compression_parity(const std::string &original,
  11814. const std::string &path,
  11815. const std::string &encoding) {
  11816. const std::string compressed =
  11817. compress_payload_for_parity<Compressor>(original);
  11818. Server svr;
  11819. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11820. res.set_content(compressed, "application/octet-stream");
  11821. res.set_header("Content-Encoding", encoding);
  11822. });
  11823. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11824. auto se = detail::scope_exit([&] {
  11825. svr.stop();
  11826. t.join();
  11827. ASSERT_FALSE(svr.is_running());
  11828. });
  11829. svr.wait_until_ready();
  11830. Client cli(HOST, PORT);
  11831. // Non-streaming
  11832. {
  11833. auto res = cli.Get(path);
  11834. ASSERT_TRUE(res);
  11835. EXPECT_EQ(StatusCode::OK_200, res->status);
  11836. EXPECT_EQ(original, res->body);
  11837. }
  11838. // Streaming
  11839. {
  11840. auto h = cli.open_stream("GET", path);
  11841. ASSERT_TRUE(h.is_valid());
  11842. EXPECT_EQ(original, read_all(h));
  11843. }
  11844. }
  11845. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11846. TEST(ParityTest, Gzip) {
  11847. test_compression_parity<detail::gzip_compressor>(
  11848. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11849. }
  11850. #endif
  11851. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11852. TEST(ParityTest, Brotli) {
  11853. test_compression_parity<detail::brotli_compressor>(
  11854. "Hello, brotli parity test payload", "/parity-br", "br");
  11855. }
  11856. #endif
  11857. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11858. TEST(ParityTest, Zstd) {
  11859. test_compression_parity<detail::zstd_compressor>(
  11860. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11861. }
  11862. #endif
  11863. //==============================================================================
  11864. // New Stream API Tests
  11865. //==============================================================================
  11866. inline std::string read_body(httplib::stream::Result &result) {
  11867. std::string body;
  11868. while (result.next()) {
  11869. body.append(result.data(), result.size());
  11870. }
  11871. return body;
  11872. }
  11873. TEST(ClientConnectionTest, Basic) {
  11874. httplib::ClientConnection conn;
  11875. EXPECT_FALSE(conn.is_open());
  11876. conn.sock = 1;
  11877. EXPECT_TRUE(conn.is_open());
  11878. httplib::ClientConnection conn2(std::move(conn));
  11879. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11880. conn2.sock = INVALID_SOCKET;
  11881. }
  11882. // Unified test server for all stream::* tests
  11883. class StreamApiTest : public ::testing::Test {
  11884. protected:
  11885. void SetUp() override {
  11886. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11887. res.set_content("Hello World!", "text/plain");
  11888. });
  11889. svr_.Get("/echo-params",
  11890. [](const httplib::Request &req, httplib::Response &res) {
  11891. std::string r;
  11892. for (const auto &p : req.params) {
  11893. if (!r.empty()) r += "&";
  11894. r += p.first + "=" + p.second;
  11895. }
  11896. res.set_content(r, "text/plain");
  11897. });
  11898. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11899. res.set_content(req.body, req.get_header_value("Content-Type"));
  11900. });
  11901. svr_.Post("/echo-headers",
  11902. [](const httplib::Request &req, httplib::Response &res) {
  11903. std::string r;
  11904. for (const auto &h : req.headers)
  11905. r += h.first + ": " + h.second + "\n";
  11906. res.set_content(r, "text/plain");
  11907. });
  11908. svr_.Post("/echo-params",
  11909. [](const httplib::Request &req, httplib::Response &res) {
  11910. std::string r = "params:";
  11911. for (const auto &p : req.params)
  11912. r += p.first + "=" + p.second + ";";
  11913. res.set_content(r + " body:" + req.body, "text/plain");
  11914. });
  11915. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11916. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11917. });
  11918. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11919. res.set_content("PUT:" + req.body, "text/plain");
  11920. });
  11921. svr_.Patch("/echo",
  11922. [](const httplib::Request &req, httplib::Response &res) {
  11923. res.set_content("PATCH:" + req.body, "text/plain");
  11924. });
  11925. svr_.Delete(
  11926. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11927. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11928. "text/plain");
  11929. });
  11930. svr_.Get("/head-test",
  11931. [](const httplib::Request &, httplib::Response &res) {
  11932. res.set_content("body for HEAD", "text/plain");
  11933. });
  11934. svr_.Options("/options",
  11935. [](const httplib::Request &, httplib::Response &res) {
  11936. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11937. });
  11938. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11939. svr_.wait_until_ready();
  11940. }
  11941. void TearDown() override {
  11942. svr_.stop();
  11943. if (thread_.joinable()) thread_.join();
  11944. }
  11945. httplib::Server svr_;
  11946. std::thread thread_;
  11947. };
  11948. // stream::Get tests
  11949. TEST_F(StreamApiTest, GetBasic) {
  11950. httplib::Client cli(HOST, PORT);
  11951. auto result = httplib::stream::Get(cli, "/hello");
  11952. ASSERT_TRUE(result.is_valid());
  11953. EXPECT_EQ(200, result.status());
  11954. EXPECT_EQ("Hello World!", read_body(result));
  11955. }
  11956. TEST_F(StreamApiTest, GetWithParams) {
  11957. httplib::Client cli(HOST, PORT);
  11958. httplib::Params params{{"foo", "bar"}};
  11959. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11960. ASSERT_TRUE(result.is_valid());
  11961. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11962. }
  11963. TEST_F(StreamApiTest, GetConnectionError) {
  11964. httplib::Client cli(HOST, 9999);
  11965. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11966. }
  11967. TEST_F(StreamApiTest, Get404) {
  11968. httplib::Client cli(HOST, PORT);
  11969. auto result = httplib::stream::Get(cli, "/nonexistent");
  11970. EXPECT_TRUE(result.is_valid());
  11971. EXPECT_EQ(404, result.status());
  11972. }
  11973. // stream::Post tests
  11974. TEST_F(StreamApiTest, PostBasic) {
  11975. httplib::Client cli(HOST, PORT);
  11976. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11977. "application/json");
  11978. ASSERT_TRUE(result.is_valid());
  11979. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11980. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11981. }
  11982. TEST_F(StreamApiTest, PostWithHeaders) {
  11983. httplib::Client cli(HOST, PORT);
  11984. httplib::Headers headers{{"X-Custom", "value"}};
  11985. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11986. "text/plain");
  11987. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11988. }
  11989. TEST_F(StreamApiTest, PostWithParams) {
  11990. httplib::Client cli(HOST, PORT);
  11991. httplib::Params params{{"k", "v"}};
  11992. auto result =
  11993. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11994. auto body = read_body(result);
  11995. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11996. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11997. }
  11998. TEST_F(StreamApiTest, PostLarge) {
  11999. httplib::Client cli(HOST, PORT);
  12000. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12001. size_t total = 0;
  12002. while (result.next()) {
  12003. total += result.size();
  12004. }
  12005. EXPECT_EQ(100u * 1024u, total);
  12006. }
  12007. // stream::Put/Patch tests
  12008. TEST_F(StreamApiTest, PutAndPatch) {
  12009. httplib::Client cli(HOST, PORT);
  12010. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12011. EXPECT_EQ("PUT:test", read_body(put));
  12012. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12013. EXPECT_EQ("PATCH:test", read_body(patch));
  12014. }
  12015. // stream::Delete tests
  12016. TEST_F(StreamApiTest, Delete) {
  12017. httplib::Client cli(HOST, PORT);
  12018. auto del1 = httplib::stream::Delete(cli, "/resource");
  12019. EXPECT_EQ("Deleted", read_body(del1));
  12020. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12021. EXPECT_EQ("Deleted:data", read_body(del2));
  12022. }
  12023. // stream::Head/Options tests
  12024. TEST_F(StreamApiTest, HeadAndOptions) {
  12025. httplib::Client cli(HOST, PORT);
  12026. auto head = httplib::stream::Head(cli, "/head-test");
  12027. EXPECT_TRUE(head.is_valid());
  12028. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12029. auto opts = httplib::stream::Options(cli, "/options");
  12030. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12031. }
  12032. // SSL stream::* tests
  12033. #ifdef CPPHTTPLIB_SSL_ENABLED
  12034. class SSLStreamApiTest : public ::testing::Test {
  12035. protected:
  12036. void SetUp() override {
  12037. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12038. res.set_content("Hello SSL!", "text/plain");
  12039. });
  12040. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12041. res.set_content(req.body, "text/plain");
  12042. });
  12043. port_ = svr_.bind_to_any_port("127.0.0.1");
  12044. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12045. svr_.wait_until_ready();
  12046. }
  12047. void TearDown() override {
  12048. svr_.stop();
  12049. if (thread_.joinable()) thread_.join();
  12050. }
  12051. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12052. std::thread thread_;
  12053. int port_ = 0;
  12054. };
  12055. TEST_F(SSLStreamApiTest, GetAndPost) {
  12056. httplib::SSLClient cli("127.0.0.1", port_);
  12057. cli.enable_server_certificate_verification(false);
  12058. auto get = httplib::stream::Get(cli, "/hello");
  12059. EXPECT_EQ("Hello SSL!", read_body(get));
  12060. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12061. EXPECT_EQ("test", read_body(post));
  12062. }
  12063. #endif
  12064. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12065. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12066. // BodyReader
  12067. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12068. // Test that read timeout during streaming is detected
  12069. // Use a large content-length response where server delays mid-stream
  12070. Server svr;
  12071. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12072. // Send a large response with delay in the middle
  12073. res.set_content_provider(
  12074. 1000, // content_length
  12075. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12076. if (offset < 100) {
  12077. // Send first 100 bytes immediately
  12078. std::string data(100, 'A');
  12079. sink.write(data.c_str(), data.size());
  12080. return true;
  12081. }
  12082. // Then delay longer than client timeout
  12083. std::this_thread::sleep_for(std::chrono::seconds(3));
  12084. std::string data(900, 'B');
  12085. sink.write(data.c_str(), data.size());
  12086. return true;
  12087. });
  12088. });
  12089. auto port = 8091;
  12090. std::thread t([&]() { svr.listen("localhost", port); });
  12091. svr.wait_until_ready();
  12092. Client cli("localhost", port);
  12093. cli.set_read_timeout(1, 0); // 1 second timeout
  12094. auto handle = cli.open_stream("GET", "/slow-stream");
  12095. ASSERT_TRUE(handle.is_valid());
  12096. char buf[256];
  12097. ssize_t total = 0;
  12098. ssize_t n;
  12099. bool got_error = false;
  12100. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12101. total += n;
  12102. }
  12103. if (n < 0) {
  12104. got_error = true;
  12105. // Should be timeout or read error
  12106. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12107. handle.get_read_error() == Error::Read)
  12108. << "Actual error: " << to_string(handle.get_read_error());
  12109. }
  12110. // Either we got an error, or we got less data than expected
  12111. EXPECT_TRUE(got_error || total < 1000)
  12112. << "Expected timeout but got all " << total << " bytes";
  12113. svr.stop();
  12114. t.join();
  12115. }
  12116. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12117. // Test connection closed detection via BodyReader
  12118. Server svr;
  12119. std::atomic<bool> close_now{false};
  12120. svr.Get("/will-close", [&](const Request &, Response &res) {
  12121. res.set_content_provider(
  12122. 10000, // Large content_length that we won't fully send
  12123. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12124. if (offset < 100) {
  12125. std::string data(100, 'X');
  12126. sink.write(data.c_str(), data.size());
  12127. return true;
  12128. }
  12129. // Wait for signal then abort
  12130. while (!close_now) {
  12131. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12132. }
  12133. return false; // Abort - server will close connection
  12134. });
  12135. });
  12136. auto port = 8092;
  12137. std::thread t([&]() { svr.listen("localhost", port); });
  12138. svr.wait_until_ready();
  12139. Client cli("localhost", port);
  12140. auto handle = cli.open_stream("GET", "/will-close");
  12141. ASSERT_TRUE(handle.is_valid());
  12142. char buf[256];
  12143. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12144. EXPECT_GT(n, 0) << "First read should succeed";
  12145. // Signal server to close
  12146. close_now = true;
  12147. // Keep reading until error or EOF
  12148. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12149. // Keep reading
  12150. }
  12151. // Should get an error since content_length wasn't satisfied
  12152. if (n < 0) {
  12153. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12154. handle.get_read_error() == Error::Read)
  12155. << "Actual error: " << to_string(handle.get_read_error());
  12156. }
  12157. svr.stop();
  12158. t.join();
  12159. }
  12160. #ifdef CPPHTTPLIB_SSL_ENABLED
  12161. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12162. // Test that read timeout during SSL streaming is detected
  12163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12164. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12165. res.set_content_provider(
  12166. 1000, "text/plain",
  12167. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12168. if (offset < 100) {
  12169. std::string data(100, 'A');
  12170. sink.write(data.c_str(), data.size());
  12171. return true;
  12172. }
  12173. std::this_thread::sleep_for(std::chrono::seconds(3));
  12174. std::string data(900, 'B');
  12175. sink.write(data.c_str(), data.size());
  12176. return true;
  12177. });
  12178. });
  12179. auto port = 8093;
  12180. std::thread t([&]() { svr.listen("localhost", port); });
  12181. svr.wait_until_ready();
  12182. SSLClient cli("localhost", port);
  12183. cli.enable_server_certificate_verification(false);
  12184. cli.set_read_timeout(1, 0); // 1 second timeout
  12185. auto handle = cli.open_stream("GET", "/slow-stream");
  12186. ASSERT_TRUE(handle.is_valid());
  12187. char buf[256];
  12188. ssize_t total = 0;
  12189. ssize_t n;
  12190. bool got_error = false;
  12191. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12192. total += n;
  12193. }
  12194. if (n < 0) {
  12195. got_error = true;
  12196. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12197. handle.get_read_error() == Error::Read)
  12198. << "Actual error: " << to_string(handle.get_read_error());
  12199. }
  12200. EXPECT_TRUE(got_error || total < 1000)
  12201. << "Expected timeout but got all " << total << " bytes";
  12202. svr.stop();
  12203. t.join();
  12204. }
  12205. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12206. // Test SSL connection closed detection
  12207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12208. std::atomic<bool> close_now{false};
  12209. svr.Get("/will-close", [&](const Request &, Response &res) {
  12210. res.set_content_provider(
  12211. 10000, "text/plain",
  12212. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12213. if (offset < 100) {
  12214. std::string data(100, 'X');
  12215. sink.write(data.c_str(), data.size());
  12216. return true;
  12217. }
  12218. while (!close_now) {
  12219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12220. }
  12221. return false;
  12222. });
  12223. });
  12224. auto port = 8094;
  12225. std::thread t([&]() { svr.listen("localhost", port); });
  12226. svr.wait_until_ready();
  12227. SSLClient cli("localhost", port);
  12228. cli.enable_server_certificate_verification(false);
  12229. auto handle = cli.open_stream("GET", "/will-close");
  12230. ASSERT_TRUE(handle.is_valid());
  12231. char buf[256];
  12232. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12233. EXPECT_GT(n, 0);
  12234. // Signal server to close
  12235. close_now = true;
  12236. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12237. // Keep reading
  12238. }
  12239. if (n < 0) {
  12240. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12241. handle.get_read_error() == Error::Read)
  12242. << "Actual error: " << to_string(handle.get_read_error());
  12243. }
  12244. svr.stop();
  12245. t.join();
  12246. }
  12247. #endif
  12248. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12249. using namespace httplib;
  12250. // Create a test file
  12251. const char *fname = "etag_testfile.txt";
  12252. const char *content = "etag-content";
  12253. {
  12254. std::ofstream ofs(fname);
  12255. ofs << content;
  12256. ASSERT_TRUE(ofs.good());
  12257. }
  12258. Server svr;
  12259. svr.set_mount_point("/static", ".");
  12260. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12261. svr.wait_until_ready();
  12262. Client cli(HOST, PORT);
  12263. // First request: should get 200 with ETag header
  12264. auto res1 = cli.Get("/static/etag_testfile.txt");
  12265. ASSERT_TRUE(res1);
  12266. ASSERT_EQ(200, res1->status);
  12267. ASSERT_TRUE(res1->has_header("ETag"));
  12268. std::string etag = res1->get_header_value("ETag");
  12269. EXPECT_FALSE(etag.empty());
  12270. // Verify ETag format: W/"hex-hex"
  12271. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12272. EXPECT_EQ('W', etag[0]);
  12273. EXPECT_EQ('/', etag[1]);
  12274. EXPECT_EQ('"', etag[2]);
  12275. EXPECT_EQ('"', etag.back());
  12276. // Exact match: expect 304 Not Modified
  12277. Headers h2 = {{"If-None-Match", etag}};
  12278. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12279. ASSERT_TRUE(res2);
  12280. EXPECT_EQ(304, res2->status);
  12281. // Wildcard match: expect 304 Not Modified
  12282. Headers h3 = {{"If-None-Match", "*"}};
  12283. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12284. ASSERT_TRUE(res3);
  12285. EXPECT_EQ(304, res3->status);
  12286. // Non-matching ETag: expect 200
  12287. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12288. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12289. ASSERT_TRUE(res4);
  12290. EXPECT_EQ(200, res4->status);
  12291. // Multiple ETags with one matching: expect 304
  12292. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12293. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12294. ASSERT_TRUE(res5);
  12295. EXPECT_EQ(304, res5->status);
  12296. svr.stop();
  12297. t.join();
  12298. std::remove(fname);
  12299. }
  12300. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12301. using namespace httplib;
  12302. Server svr;
  12303. svr.set_mount_point("/static", ".");
  12304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12305. svr.wait_until_ready();
  12306. Client cli(HOST, PORT);
  12307. // Send If-None-Match: * to a non-existent file
  12308. Headers h = {{"If-None-Match", "*"}};
  12309. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12310. ASSERT_TRUE(res);
  12311. EXPECT_EQ(404, res->status);
  12312. svr.stop();
  12313. t.join();
  12314. }
  12315. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12316. using namespace httplib;
  12317. // Create a test file
  12318. const char *fname = "etag_boundary_testfile.txt";
  12319. const char *content = "boundary-test";
  12320. {
  12321. std::ofstream ofs(fname);
  12322. ofs << content;
  12323. ASSERT_TRUE(ofs.good());
  12324. }
  12325. Server svr;
  12326. svr.set_mount_point("/static", ".");
  12327. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12328. svr.wait_until_ready();
  12329. Client cli(HOST, PORT);
  12330. // Get the actual ETag
  12331. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12332. ASSERT_TRUE(res1);
  12333. ASSERT_EQ(200, res1->status);
  12334. ASSERT_TRUE(res1->has_header("ETag"));
  12335. std::string etag = res1->get_header_value("ETag");
  12336. // Test 1: Very long ETag value (longer than actual ETag)
  12337. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12338. Headers h1 = {{"If-None-Match", "W/"
  12339. "\"very-long-etag-value-that-is-much-longer-"
  12340. "than-the-actual-etag-value\""}};
  12341. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12342. ASSERT_TRUE(res2);
  12343. EXPECT_EQ(200, res2->status); // Should not match
  12344. // Test 2: Long string followed by wildcard
  12345. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12346. // string)
  12347. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12348. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12349. ASSERT_TRUE(res3);
  12350. EXPECT_EQ(304, res3->status); // Should match on "*"
  12351. // Test 3: Wildcard followed by long string
  12352. // Should match on "*" immediately and return 304
  12353. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12354. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12355. ASSERT_TRUE(res4);
  12356. EXPECT_EQ(304, res4->status); // Should match on "*"
  12357. // Test 4: Multiple long non-matching values
  12358. // Should NOT match and return 200 (test that all comparisons are safe)
  12359. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12360. "W/\"second-long-non-matching-value\", "
  12361. "W/\"third-long-non-matching-value\""}};
  12362. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12363. ASSERT_TRUE(res5);
  12364. EXPECT_EQ(200, res5->status); // Should not match
  12365. // Test 5: Single character that is not "*" (edge case)
  12366. Headers h5 = {{"If-None-Match", "X"}};
  12367. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12368. ASSERT_TRUE(res6);
  12369. EXPECT_EQ(200, res6->status); // Should not match
  12370. svr.stop();
  12371. t.join();
  12372. std::remove(fname);
  12373. }
  12374. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12375. using namespace httplib;
  12376. // Create a test file
  12377. const char *fname = "ims_testfile.txt";
  12378. const char *content = "if-modified-since-test";
  12379. {
  12380. std::ofstream ofs(fname);
  12381. ofs << content;
  12382. ASSERT_TRUE(ofs.good());
  12383. }
  12384. Server svr;
  12385. svr.set_mount_point("/static", ".");
  12386. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12387. svr.wait_until_ready();
  12388. Client cli(HOST, PORT);
  12389. // First request: should get 200 with Last-Modified header
  12390. auto res1 = cli.Get("/static/ims_testfile.txt");
  12391. ASSERT_TRUE(res1);
  12392. ASSERT_EQ(200, res1->status);
  12393. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12394. std::string last_modified = res1->get_header_value("Last-Modified");
  12395. EXPECT_FALSE(last_modified.empty());
  12396. // If-Modified-Since with same time: expect 304
  12397. Headers h2 = {{"If-Modified-Since", last_modified}};
  12398. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12399. ASSERT_TRUE(res2);
  12400. EXPECT_EQ(304, res2->status);
  12401. // If-Modified-Since with future time: expect 304
  12402. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12403. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12404. ASSERT_TRUE(res3);
  12405. EXPECT_EQ(304, res3->status);
  12406. // If-Modified-Since with past time: expect 200
  12407. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12408. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12409. ASSERT_TRUE(res4);
  12410. EXPECT_EQ(200, res4->status);
  12411. // If-None-Match takes precedence over If-Modified-Since
  12412. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12413. ASSERT_TRUE(res1->has_header("ETag"));
  12414. std::string etag = res1->get_header_value("ETag");
  12415. Headers h5 = {{"If-None-Match", etag},
  12416. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12417. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12418. ASSERT_TRUE(res5);
  12419. EXPECT_EQ(304, res5->status);
  12420. svr.stop();
  12421. t.join();
  12422. std::remove(fname);
  12423. }
  12424. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12425. using namespace httplib;
  12426. Server svr;
  12427. // Endpoint that returns compressible content
  12428. svr.Get("/compressible", [](const Request &, Response &res) {
  12429. // Return a large enough body to trigger compression
  12430. std::string body(1000, 'a');
  12431. res.set_content(body, "text/plain");
  12432. });
  12433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12434. svr.wait_until_ready();
  12435. Client cli(HOST, PORT);
  12436. // Request with gzip support: should get Vary header when compressed
  12437. cli.set_compress(true);
  12438. auto res1 = cli.Get("/compressible");
  12439. ASSERT_TRUE(res1);
  12440. EXPECT_EQ(200, res1->status);
  12441. // If Content-Encoding is set, Vary should also be set
  12442. if (res1->has_header("Content-Encoding")) {
  12443. EXPECT_TRUE(res1->has_header("Vary"));
  12444. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12445. }
  12446. // Request without Accept-Encoding header: should not have compression
  12447. Headers h_no_compress;
  12448. auto res2 = cli.Get("/compressible", h_no_compress);
  12449. ASSERT_TRUE(res2);
  12450. EXPECT_EQ(200, res2->status);
  12451. // Verify Vary header is present when compression is applied
  12452. // (the exact behavior depends on server configuration)
  12453. svr.stop();
  12454. t.join();
  12455. }
  12456. TEST(ETagTest, IfRangeWithETag) {
  12457. using namespace httplib;
  12458. // Create a test file with known content
  12459. const char *fname = "if_range_testfile.txt";
  12460. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12461. {
  12462. std::ofstream ofs(fname);
  12463. ofs << content;
  12464. ASSERT_TRUE(ofs.good());
  12465. }
  12466. Server svr;
  12467. svr.set_mount_point("/static", ".");
  12468. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12469. svr.wait_until_ready();
  12470. Client cli(HOST, PORT);
  12471. // First request: get ETag
  12472. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12473. ASSERT_TRUE(res1);
  12474. ASSERT_EQ(200, res1->status);
  12475. ASSERT_TRUE(res1->has_header("ETag"));
  12476. std::string etag = res1->get_header_value("ETag");
  12477. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12478. // Since our server generates weak ETags (W/"..."), If-Range with our
  12479. // ETag should NOT result in partial content - it should return full content.
  12480. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12481. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12482. ASSERT_TRUE(res2);
  12483. // Weak ETag in If-Range -> full content (200), not partial (206)
  12484. EXPECT_EQ(200, res2->status);
  12485. EXPECT_EQ(content, res2->body);
  12486. EXPECT_FALSE(res2->has_header("Content-Range"));
  12487. // Range request with non-matching If-Range (ETag): should get 200 (full
  12488. // content)
  12489. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12490. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12491. ASSERT_TRUE(res3);
  12492. EXPECT_EQ(200, res3->status);
  12493. EXPECT_EQ(content, res3->body);
  12494. EXPECT_FALSE(res3->has_header("Content-Range"));
  12495. // Range request with strong ETag (hypothetical - our server doesn't generate
  12496. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12497. // should return full content)
  12498. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12499. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12500. ASSERT_TRUE(res4);
  12501. EXPECT_EQ(200, res4->status);
  12502. EXPECT_EQ(content, res4->body);
  12503. EXPECT_FALSE(res4->has_header("Content-Range"));
  12504. svr.stop();
  12505. t.join();
  12506. std::remove(fname);
  12507. }
  12508. TEST(ETagTest, IfRangeWithDate) {
  12509. using namespace httplib;
  12510. // Create a test file
  12511. const char *fname = "if_range_date_testfile.txt";
  12512. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12513. {
  12514. std::ofstream ofs(fname);
  12515. ofs << content;
  12516. ASSERT_TRUE(ofs.good());
  12517. }
  12518. Server svr;
  12519. svr.set_mount_point("/static", ".");
  12520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12521. svr.wait_until_ready();
  12522. Client cli(HOST, PORT);
  12523. // First request: get Last-Modified
  12524. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12525. ASSERT_TRUE(res1);
  12526. ASSERT_EQ(200, res1->status);
  12527. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12528. std::string last_modified = res1->get_header_value("Last-Modified");
  12529. // Range request with matching If-Range (date): should get 206
  12530. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12531. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12532. ASSERT_TRUE(res2);
  12533. EXPECT_EQ(206, res2->status);
  12534. EXPECT_EQ("FGHIJ", res2->body);
  12535. // Range request with old If-Range date: should get 200 (full content)
  12536. Headers h3 = {{"Range", "bytes=5-9"},
  12537. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12538. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12539. ASSERT_TRUE(res3);
  12540. EXPECT_EQ(200, res3->status);
  12541. EXPECT_EQ(content, res3->body);
  12542. // Range request with future If-Range date: should get 206
  12543. Headers h4 = {{"Range", "bytes=0-4"},
  12544. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12545. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12546. ASSERT_TRUE(res4);
  12547. EXPECT_EQ(206, res4->status);
  12548. EXPECT_EQ("ABCDE", res4->body);
  12549. svr.stop();
  12550. t.join();
  12551. std::remove(fname);
  12552. }
  12553. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12554. using namespace httplib;
  12555. const char *fname = "etag_malformed.txt";
  12556. const char *content = "malformed-etag";
  12557. {
  12558. std::ofstream ofs(fname);
  12559. ofs << content;
  12560. ASSERT_TRUE(ofs.good());
  12561. }
  12562. Server svr;
  12563. svr.set_mount_point("/static", ".");
  12564. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12565. svr.wait_until_ready();
  12566. Client cli(HOST, PORT);
  12567. // baseline: should get 200 and an ETag
  12568. auto res1 = cli.Get("/static/etag_malformed.txt");
  12569. ASSERT_TRUE(res1);
  12570. ASSERT_EQ(200, res1->status);
  12571. ASSERT_TRUE(res1->has_header("ETag"));
  12572. // Malformed ETag value (missing quotes) should be treated as non-matching
  12573. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12574. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12575. ASSERT_TRUE(res_bad);
  12576. EXPECT_EQ(200, res_bad->status);
  12577. // Whitespace-only header value should be considered invalid / non-matching
  12578. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12579. "Host: localhost\r\n"
  12580. "If-None-Match: \r\n"
  12581. "Connection: close\r\n"
  12582. "\r\n";
  12583. std::string out;
  12584. ASSERT_TRUE(send_request(5, raw_req, &out));
  12585. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12586. svr.stop();
  12587. t.join();
  12588. std::remove(fname);
  12589. }
  12590. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12591. using namespace httplib;
  12592. const char *fname = "ims_invalid_format.txt";
  12593. const char *content = "ims-bad-format";
  12594. {
  12595. std::ofstream ofs(fname);
  12596. ofs << content;
  12597. ASSERT_TRUE(ofs.good());
  12598. }
  12599. Server svr;
  12600. svr.set_mount_point("/static", ".");
  12601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12602. svr.wait_until_ready();
  12603. Client cli(HOST, PORT);
  12604. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12605. ASSERT_TRUE(res1);
  12606. ASSERT_EQ(200, res1->status);
  12607. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12608. // If-Modified-Since with invalid format should not result in 304
  12609. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12610. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12611. ASSERT_TRUE(res_bad);
  12612. EXPECT_EQ(200, res_bad->status);
  12613. // If-Range with invalid date format should be treated as mismatch -> full
  12614. // content (200)
  12615. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12616. {"If-Range", "invalid-date"}};
  12617. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12618. ASSERT_TRUE(res_ifrange);
  12619. EXPECT_EQ(200, res_ifrange->status);
  12620. svr.stop();
  12621. t.join();
  12622. std::remove(fname);
  12623. }
  12624. TEST(ETagTest, IfRangeWithMalformedETag) {
  12625. using namespace httplib;
  12626. const char *fname = "ifrange_malformed.txt";
  12627. const std::string content = "0123456789";
  12628. {
  12629. std::ofstream ofs(fname);
  12630. ofs << content;
  12631. ASSERT_TRUE(ofs.good());
  12632. }
  12633. Server svr;
  12634. svr.set_mount_point("/static", ".");
  12635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12636. svr.wait_until_ready();
  12637. Client cli(HOST, PORT);
  12638. // First request: get ETag
  12639. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12640. ASSERT_TRUE(res1);
  12641. ASSERT_EQ(200, res1->status);
  12642. ASSERT_TRUE(res1->has_header("ETag"));
  12643. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12644. // full content (200)
  12645. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12646. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12647. ASSERT_TRUE(res2);
  12648. EXPECT_EQ(200, res2->status);
  12649. EXPECT_EQ(content, res2->body);
  12650. svr.stop();
  12651. t.join();
  12652. std::remove(fname);
  12653. }
  12654. TEST(ETagTest, ExtremeLargeDateValues) {
  12655. using namespace httplib;
  12656. const char *fname = "ims_extreme_date.txt";
  12657. const char *content = "ims-extreme-date";
  12658. {
  12659. std::ofstream ofs(fname);
  12660. ofs << content;
  12661. ASSERT_TRUE(ofs.good());
  12662. }
  12663. Server svr;
  12664. svr.set_mount_point("/static", ".");
  12665. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12666. svr.wait_until_ready();
  12667. Client cli(HOST, PORT);
  12668. auto res1 = cli.Get(std::string("/static/") + fname);
  12669. ASSERT_TRUE(res1);
  12670. ASSERT_EQ(200, res1->status);
  12671. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12672. // Extremely large year that may overflow date parsing routines.
  12673. Headers h_large_date = {
  12674. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12675. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12676. ASSERT_TRUE(res_bad);
  12677. // Expect server to treat this as invalid/mismatch and return full content
  12678. EXPECT_EQ(200, res_bad->status);
  12679. // If-Range with extremely large date should be treated as mismatch -> full
  12680. // content (200)
  12681. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12682. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12683. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12684. ASSERT_TRUE(res_ifrange);
  12685. EXPECT_EQ(200, res_ifrange->status);
  12686. svr.stop();
  12687. t.join();
  12688. std::remove(fname);
  12689. }
  12690. TEST(ETagTest, NegativeFileModificationTime) {
  12691. using namespace httplib;
  12692. const char *fname = "ims_negative_mtime.txt";
  12693. const std::string content = "negative-mtime";
  12694. {
  12695. std::ofstream ofs(fname);
  12696. ofs << content;
  12697. ASSERT_TRUE(ofs.good());
  12698. }
  12699. // Try to set file mtime to a negative value. This may fail on some
  12700. // platforms/filesystems; if it fails, the test will still verify server
  12701. // behaves safely by performing a regular conditional request.
  12702. #if defined(__APPLE__) || defined(__linux__)
  12703. bool set_negative = false;
  12704. do {
  12705. struct timeval times[2];
  12706. // access time: now
  12707. times[0].tv_sec = time(nullptr);
  12708. times[0].tv_usec = 0;
  12709. // modification time: negative (e.g., -1)
  12710. times[1].tv_sec = -1;
  12711. times[1].tv_usec = 0;
  12712. if (utimes(fname, times) == 0) { set_negative = true; }
  12713. } while (0);
  12714. #else
  12715. bool set_negative = false;
  12716. #endif
  12717. Server svr;
  12718. svr.set_mount_point("/static", ".");
  12719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12720. svr.wait_until_ready();
  12721. Client cli(HOST, PORT);
  12722. auto res1 = cli.Get(std::string("/static/") + fname);
  12723. ASSERT_TRUE(res1);
  12724. ASSERT_EQ(200, res1->status);
  12725. bool has_last_modified = res1->has_header("Last-Modified");
  12726. std::string last_modified;
  12727. if (has_last_modified) {
  12728. last_modified = res1->get_header_value("Last-Modified");
  12729. }
  12730. if (set_negative) {
  12731. // If we successfully set a negative mtime, ensure server returns a
  12732. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12733. // with an old date and ensure server handles it without crash.
  12734. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12735. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12736. ASSERT_TRUE(res2);
  12737. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12738. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12739. } else {
  12740. // Could not set negative mtime on this platform; fall back to verifying
  12741. // that normal invalid/malformed dates are treated safely (non-304).
  12742. Headers h_bad_date = {
  12743. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12744. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12745. ASSERT_TRUE(res_bad);
  12746. EXPECT_EQ(200, res_bad->status);
  12747. }
  12748. svr.stop();
  12749. t.join();
  12750. std::remove(fname);
  12751. }
  12752. //==============================================================================
  12753. // SSE Parsing Tests
  12754. //==============================================================================
  12755. class SSEParsingTest : public ::testing::Test {
  12756. protected:
  12757. // Test helper that mimics SSE parsing behavior
  12758. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12759. int &retry_ms) {
  12760. // Blank line signals end of event
  12761. if (line.empty() || line == "\r") { return true; }
  12762. // Lines starting with ':' are comments (ignored)
  12763. if (!line.empty() && line[0] == ':') { return false; }
  12764. // Find the colon separator
  12765. auto colon_pos = line.find(':');
  12766. if (colon_pos == std::string::npos) {
  12767. // Line with no colon is treated as field name with empty value
  12768. return false;
  12769. }
  12770. std::string field = line.substr(0, colon_pos);
  12771. std::string value;
  12772. // Value starts after colon, skip optional single space
  12773. if (colon_pos + 1 < line.size()) {
  12774. size_t value_start = colon_pos + 1;
  12775. if (line[value_start] == ' ') { value_start++; }
  12776. value = line.substr(value_start);
  12777. // Remove trailing \r if present
  12778. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12779. }
  12780. // Handle known fields
  12781. if (field == "event") {
  12782. msg.event = value;
  12783. } else if (field == "data") {
  12784. // Multiple data lines are concatenated with newlines
  12785. if (!msg.data.empty()) { msg.data += "\n"; }
  12786. msg.data += value;
  12787. } else if (field == "id") {
  12788. // Empty id is valid (clears the last event ID)
  12789. msg.id = value;
  12790. } else if (field == "retry") {
  12791. // Parse retry interval in milliseconds
  12792. {
  12793. int v = 0;
  12794. auto res =
  12795. detail::from_chars(value.data(), value.data() + value.size(), v);
  12796. if (res.ec == std::errc{}) { retry_ms = v; }
  12797. }
  12798. }
  12799. // Unknown fields are ignored per SSE spec
  12800. return false;
  12801. }
  12802. };
  12803. // Test: Single-line data
  12804. TEST_F(SSEParsingTest, SingleLineData) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12808. EXPECT_EQ(msg.data, "hello");
  12809. EXPECT_EQ(msg.event, "message");
  12810. // Blank line ends event
  12811. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12812. }
  12813. // Test: Multi-line data
  12814. TEST_F(SSEParsingTest, MultiLineData) {
  12815. sse::SSEMessage msg;
  12816. int retry_ms = 3000;
  12817. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12818. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12819. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12820. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12821. }
  12822. // Test: Custom event types
  12823. TEST_F(SSEParsingTest, CustomEventType) {
  12824. sse::SSEMessage msg;
  12825. int retry_ms = 3000;
  12826. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12827. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12828. EXPECT_EQ(msg.event, "update");
  12829. EXPECT_EQ(msg.data, "payload");
  12830. }
  12831. // Test: Event ID handling
  12832. TEST_F(SSEParsingTest, EventIdHandling) {
  12833. sse::SSEMessage msg;
  12834. int retry_ms = 3000;
  12835. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12836. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12837. EXPECT_EQ(msg.id, "12345");
  12838. }
  12839. // Test: Empty event ID (clears last event ID)
  12840. TEST_F(SSEParsingTest, EmptyEventId) {
  12841. sse::SSEMessage msg;
  12842. msg.id = "previous";
  12843. int retry_ms = 3000;
  12844. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12845. EXPECT_EQ(msg.id, "");
  12846. }
  12847. // Test: Retry field parsing
  12848. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12849. sse::SSEMessage msg;
  12850. int retry_ms = 3000;
  12851. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12852. EXPECT_EQ(retry_ms, 5000);
  12853. }
  12854. // Test: Invalid retry value
  12855. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12856. sse::SSEMessage msg;
  12857. int retry_ms = 3000;
  12858. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12859. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12860. }
  12861. // Test: Comments (lines starting with :)
  12862. TEST_F(SSEParsingTest, CommentsIgnored) {
  12863. sse::SSEMessage msg;
  12864. int retry_ms = 3000;
  12865. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12866. EXPECT_EQ(msg.data, "");
  12867. EXPECT_EQ(msg.event, "message");
  12868. }
  12869. // Test: Colon in value
  12870. TEST_F(SSEParsingTest, ColonInValue) {
  12871. sse::SSEMessage msg;
  12872. int retry_ms = 3000;
  12873. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12874. EXPECT_EQ(msg.data, "hello:world:test");
  12875. }
  12876. // Test: Line with no colon (field name only)
  12877. TEST_F(SSEParsingTest, FieldNameOnly) {
  12878. sse::SSEMessage msg;
  12879. int retry_ms = 3000;
  12880. // According to SSE spec, this is treated as field name with empty value
  12881. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12882. // Since we don't recognize "data" without colon, data should be empty
  12883. EXPECT_EQ(msg.data, "");
  12884. }
  12885. // Test: Trailing \r handling
  12886. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12887. sse::SSEMessage msg;
  12888. int retry_ms = 3000;
  12889. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12890. EXPECT_EQ(msg.data, "hello");
  12891. }
  12892. // Test: Unknown fields ignored
  12893. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12894. sse::SSEMessage msg;
  12895. int retry_ms = 3000;
  12896. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12897. EXPECT_EQ(msg.data, "");
  12898. EXPECT_EQ(msg.event, "message");
  12899. }
  12900. // Test: Space after colon is optional
  12901. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12902. sse::SSEMessage msg1, msg2;
  12903. int retry_ms = 3000;
  12904. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12905. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12906. EXPECT_EQ(msg1.data, "hello");
  12907. EXPECT_EQ(msg2.data, "hello");
  12908. }
  12909. // Test: SSEMessage clear
  12910. TEST_F(SSEParsingTest, MessageClear) {
  12911. sse::SSEMessage msg;
  12912. msg.event = "custom";
  12913. msg.data = "some data";
  12914. msg.id = "123";
  12915. msg.clear();
  12916. EXPECT_EQ(msg.event, "message");
  12917. EXPECT_EQ(msg.data, "");
  12918. EXPECT_EQ(msg.id, "");
  12919. }
  12920. // Test: Complete event parsing
  12921. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12922. sse::SSEMessage msg;
  12923. int retry_ms = 3000;
  12924. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12925. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12926. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12927. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12928. // Blank line ends event
  12929. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12930. EXPECT_EQ(msg.event, "notification");
  12931. EXPECT_EQ(msg.id, "evt-42");
  12932. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12933. EXPECT_EQ(retry_ms, 1000);
  12934. }
  12935. //==============================================================================
  12936. // Integration Tests with Server
  12937. //==============================================================================
  12938. class SSEIntegrationTest : public ::testing::Test {
  12939. protected:
  12940. void SetUp() override {
  12941. stop_server_.store(false);
  12942. events_.clear();
  12943. server_ = httplib::detail::make_unique<Server>();
  12944. setup_server();
  12945. start_server();
  12946. }
  12947. void TearDown() override {
  12948. stop_server_.store(true);
  12949. event_cv_.notify_all();
  12950. server_->stop();
  12951. if (server_thread_.joinable()) { server_thread_.join(); }
  12952. }
  12953. void setup_server() {
  12954. // Simple SSE endpoint
  12955. server_->Get("/events", [this](const Request &req, Response &res) {
  12956. auto last_id = req.get_header_value("Last-Event-ID");
  12957. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12958. res.set_chunked_content_provider(
  12959. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12960. std::unique_lock<std::mutex> lock(event_mutex_);
  12961. if (event_cv_.wait_for(
  12962. lock, std::chrono::milliseconds(200), [this] {
  12963. return !events_.empty() || stop_server_.load();
  12964. })) {
  12965. if (stop_server_.load()) { return false; }
  12966. if (!events_.empty()) {
  12967. std::string event = events_.front();
  12968. events_.erase(events_.begin());
  12969. sink.write(event.data(), event.size());
  12970. return true;
  12971. }
  12972. }
  12973. return !stop_server_.load();
  12974. });
  12975. });
  12976. // Endpoint that returns error
  12977. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12978. res.status = 500;
  12979. res.set_content("Internal Server Error", "text/plain");
  12980. });
  12981. // Endpoint for custom event types
  12982. server_->Get("/custom-events", [](const Request &, Response &res) {
  12983. res.set_chunked_content_provider(
  12984. "text/event-stream", [](size_t offset, DataSink &sink) {
  12985. if (offset == 0) {
  12986. std::string event = "event: update\ndata: updated\n\n"
  12987. "event: delete\ndata: deleted\n\n";
  12988. sink.write(event.data(), event.size());
  12989. }
  12990. return false; // End stream after sending
  12991. });
  12992. });
  12993. }
  12994. void start_server() {
  12995. port_ = server_->bind_to_any_port(HOST);
  12996. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12997. // Wait for server to start
  12998. while (!server_->is_running()) {
  12999. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13000. }
  13001. }
  13002. int get_port() const { return port_; }
  13003. void send_event(const std::string &event) {
  13004. std::lock_guard<std::mutex> lock(event_mutex_);
  13005. events_.push_back(event);
  13006. event_cv_.notify_all();
  13007. }
  13008. std::unique_ptr<Server> server_;
  13009. std::thread server_thread_;
  13010. std::mutex event_mutex_;
  13011. std::condition_variable event_cv_;
  13012. std::vector<std::string> events_;
  13013. std::atomic<bool> stop_server_{false};
  13014. std::string last_received_event_id_;
  13015. int port_ = 0;
  13016. };
  13017. // Test: Successful connection and on_open callback
  13018. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13019. // Add a simple endpoint that sends one event and closes
  13020. server_->Get("/simple-event", [](const Request &, Response &res) {
  13021. res.set_chunked_content_provider(
  13022. "text/event-stream", [](size_t offset, DataSink &sink) {
  13023. if (offset == 0) {
  13024. std::string event = "data: hello\n\n";
  13025. sink.write(event.data(), event.size());
  13026. }
  13027. return false; // Close stream after sending
  13028. });
  13029. });
  13030. Client client("localhost", get_port());
  13031. sse::SSEClient sse(client, "/simple-event");
  13032. std::atomic<bool> open_called{false};
  13033. std::atomic<bool> message_received{false};
  13034. sse.on_open([&open_called]() { open_called.store(true); });
  13035. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13036. if (msg.data == "hello") { message_received.store(true); }
  13037. });
  13038. sse.set_reconnect_interval(100);
  13039. sse.set_max_reconnect_attempts(1);
  13040. // Start async
  13041. sse.start_async();
  13042. // Wait for message to be processed
  13043. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13044. sse.stop();
  13045. EXPECT_TRUE(open_called.load());
  13046. EXPECT_TRUE(message_received.load());
  13047. }
  13048. // Test: on_message callback
  13049. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13050. // Endpoint that sends multiple events then closes
  13051. server_->Get("/multi-event", [](const Request &, Response &res) {
  13052. res.set_chunked_content_provider(
  13053. "text/event-stream", [](size_t offset, DataSink &sink) {
  13054. if (offset == 0) {
  13055. std::string events = "data: message1\n\ndata: message2\n\n";
  13056. sink.write(events.data(), events.size());
  13057. }
  13058. return false;
  13059. });
  13060. });
  13061. Client client("localhost", get_port());
  13062. sse::SSEClient sse(client, "/multi-event");
  13063. std::vector<std::string> received_messages;
  13064. std::mutex messages_mutex;
  13065. sse.on_message([&](const sse::SSEMessage &msg) {
  13066. std::lock_guard<std::mutex> lock(messages_mutex);
  13067. received_messages.push_back(msg.data);
  13068. });
  13069. sse.set_reconnect_interval(100);
  13070. sse.set_max_reconnect_attempts(1);
  13071. sse.start_async();
  13072. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13073. sse.stop();
  13074. std::lock_guard<std::mutex> lock(messages_mutex);
  13075. EXPECT_GE(received_messages.size(), 2u);
  13076. if (received_messages.size() >= 2) {
  13077. EXPECT_EQ(received_messages[0], "message1");
  13078. EXPECT_EQ(received_messages[1], "message2");
  13079. }
  13080. }
  13081. // Test: on_event for specific types
  13082. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13083. Client client("localhost", get_port());
  13084. sse::SSEClient sse(client, "/custom-events");
  13085. std::atomic<bool> update_received{false};
  13086. std::atomic<bool> delete_received{false};
  13087. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13088. if (msg.data == "updated") { update_received.store(true); }
  13089. });
  13090. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13091. if (msg.data == "deleted") { delete_received.store(true); }
  13092. });
  13093. sse.set_max_reconnect_attempts(1);
  13094. sse.start_async();
  13095. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13096. sse.stop();
  13097. EXPECT_TRUE(update_received.load());
  13098. EXPECT_TRUE(delete_received.load());
  13099. }
  13100. // Test: on_error callback on connection failure
  13101. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13102. // Connect to a non-existent port
  13103. Client client("localhost", 59999);
  13104. sse::SSEClient sse(client, "/events");
  13105. std::atomic<bool> error_called{false};
  13106. Error received_error = Error::Success;
  13107. sse.on_error([&](Error err) {
  13108. error_called.store(true);
  13109. received_error = err;
  13110. });
  13111. sse.set_reconnect_interval(50);
  13112. sse.set_max_reconnect_attempts(1);
  13113. sse.start_async();
  13114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13115. sse.stop();
  13116. EXPECT_TRUE(error_called.load());
  13117. EXPECT_NE(received_error, Error::Success);
  13118. }
  13119. // Test: Last-Event-ID header sent on reconnect
  13120. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13121. // Endpoint that sends event with ID
  13122. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13123. res.set_chunked_content_provider(
  13124. "text/event-stream", [](size_t offset, DataSink &sink) {
  13125. if (offset == 0) {
  13126. std::string event = "id: evt-123\ndata: test\n\n";
  13127. sink.write(event.data(), event.size());
  13128. }
  13129. return false;
  13130. });
  13131. });
  13132. Client client("localhost", get_port());
  13133. sse::SSEClient sse(client, "/event-with-id");
  13134. std::atomic<bool> id_received{false};
  13135. sse.on_message([&](const sse::SSEMessage &msg) {
  13136. if (!msg.id.empty()) { id_received.store(true); }
  13137. });
  13138. sse.set_reconnect_interval(100);
  13139. sse.set_max_reconnect_attempts(1);
  13140. sse.start_async();
  13141. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13142. sse.stop();
  13143. EXPECT_TRUE(id_received.load());
  13144. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13145. }
  13146. // Test: Manual stop
  13147. TEST_F(SSEIntegrationTest, ManualStop) {
  13148. // Endpoint that sends one event and stays open briefly
  13149. std::atomic<bool> handler_running{true};
  13150. server_->Get("/stay-open", [&handler_running](const Request &,
  13151. Response &res) {
  13152. res.set_chunked_content_provider(
  13153. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13154. if (offset == 0) {
  13155. std::string event = "data: connected\n\n";
  13156. sink.write(event.data(), event.size());
  13157. }
  13158. // Keep connection open while handler_running is true
  13159. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13160. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13161. }
  13162. return false;
  13163. });
  13164. });
  13165. Client client("localhost", get_port());
  13166. sse::SSEClient sse(client, "/stay-open");
  13167. std::atomic<bool> connected{false};
  13168. sse.on_open([&connected]() { connected.store(true); });
  13169. sse.set_reconnect_interval(100);
  13170. sse.set_max_reconnect_attempts(1);
  13171. sse.start_async();
  13172. // Wait for connection to establish
  13173. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13174. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13175. }
  13176. EXPECT_TRUE(connected.load());
  13177. EXPECT_TRUE(sse.is_connected());
  13178. // Signal handler to stop
  13179. handler_running.store(false);
  13180. // Stop SSE client
  13181. sse.stop();
  13182. EXPECT_FALSE(sse.is_connected());
  13183. }
  13184. // Test: SSEClient with custom headers
  13185. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13186. // Setup a server endpoint that checks for custom header
  13187. std::atomic<bool> header_received{false};
  13188. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13189. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13190. header_received.store(true);
  13191. }
  13192. res.set_chunked_content_provider("text/event-stream",
  13193. [](size_t, DataSink &) { return false; });
  13194. });
  13195. Client client("localhost", get_port());
  13196. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13197. sse::SSEClient sse(client, "/header-check", headers);
  13198. sse.set_max_reconnect_attempts(1);
  13199. sse.start_async();
  13200. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13201. sse.stop();
  13202. EXPECT_TRUE(header_received.load());
  13203. }
  13204. // Test: Reconnect interval configuration
  13205. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13206. Client client("localhost", get_port());
  13207. sse::SSEClient sse(client, "/events");
  13208. auto &result = sse.set_reconnect_interval(500);
  13209. // Builder pattern should return reference to self
  13210. EXPECT_EQ(&result, &sse);
  13211. }
  13212. // Test: Max reconnect attempts
  13213. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13214. // Connect to non-existent port to force reconnects
  13215. Client client("localhost", 59998);
  13216. sse::SSEClient sse(client, "/events");
  13217. std::atomic<int> error_count{0};
  13218. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13219. sse.set_reconnect_interval(50);
  13220. sse.set_max_reconnect_attempts(2);
  13221. auto start = std::chrono::steady_clock::now();
  13222. sse.start(); // Blocking call
  13223. auto end = std::chrono::steady_clock::now();
  13224. // Should have stopped after 2 failed attempts
  13225. EXPECT_GE(error_count.load(), 2);
  13226. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13227. auto duration =
  13228. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13229. #ifdef _WIN32
  13230. // Windows is much slower for socket connection failures
  13231. EXPECT_LT(duration.count(), 7000);
  13232. #else
  13233. EXPECT_LT(duration.count(), 1000);
  13234. #endif
  13235. }
  13236. // Test: Multi-line data in integration
  13237. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13238. // Endpoint with multi-line data
  13239. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13240. res.set_chunked_content_provider(
  13241. "text/event-stream", [](size_t offset, DataSink &sink) {
  13242. if (offset == 0) {
  13243. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13244. sink.write(event.data(), event.size());
  13245. }
  13246. return false;
  13247. });
  13248. });
  13249. Client client("localhost", get_port());
  13250. sse::SSEClient sse(client, "/multiline-data");
  13251. std::string received_data;
  13252. std::mutex data_mutex;
  13253. sse.on_message([&](const sse::SSEMessage &msg) {
  13254. std::lock_guard<std::mutex> lock(data_mutex);
  13255. received_data = msg.data;
  13256. });
  13257. sse.set_reconnect_interval(100);
  13258. sse.set_max_reconnect_attempts(1);
  13259. sse.start_async();
  13260. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13261. sse.stop();
  13262. std::lock_guard<std::mutex> lock(data_mutex);
  13263. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13264. }
  13265. // Test: Auto-reconnect after server disconnection
  13266. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13267. std::atomic<int> connection_count{0};
  13268. std::atomic<int> message_count{0};
  13269. // Endpoint that sends one event and closes, forcing reconnect
  13270. server_->Get("/reconnect-test",
  13271. [&connection_count](const Request &, Response &res) {
  13272. connection_count.fetch_add(1);
  13273. res.set_chunked_content_provider(
  13274. "text/event-stream", [](size_t offset, DataSink &sink) {
  13275. if (offset == 0) {
  13276. std::string event = "data: hello\n\n";
  13277. sink.write(event.data(), event.size());
  13278. }
  13279. return false; // Close connection after sending
  13280. });
  13281. });
  13282. Client client("localhost", get_port());
  13283. sse::SSEClient sse(client, "/reconnect-test");
  13284. sse.on_message([&message_count](const sse::SSEMessage &) {
  13285. message_count.fetch_add(1);
  13286. });
  13287. sse.set_reconnect_interval(100);
  13288. sse.set_max_reconnect_attempts(3);
  13289. sse.start_async();
  13290. // Wait long enough for multiple reconnects
  13291. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13292. sse.stop();
  13293. // Should have connected multiple times (initial + reconnects)
  13294. EXPECT_GE(connection_count.load(), 2);
  13295. // Should have received messages from multiple connections
  13296. EXPECT_GE(message_count.load(), 2);
  13297. }
  13298. // Test: Last-Event-ID sent on reconnect
  13299. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13300. std::atomic<int> connection_count{0};
  13301. std::vector<std::string> received_last_event_ids;
  13302. std::mutex id_mutex;
  13303. // Endpoint that checks Last-Event-ID header and sends event with ID
  13304. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13305. int conn = connection_count.fetch_add(1);
  13306. // Capture the Last-Event-ID header from each connection
  13307. {
  13308. std::lock_guard<std::mutex> lock(id_mutex);
  13309. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13310. }
  13311. res.set_chunked_content_provider(
  13312. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13313. if (offset == 0) {
  13314. std::string event =
  13315. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13316. sink.write(event.data(), event.size());
  13317. }
  13318. return false;
  13319. });
  13320. });
  13321. Client client("localhost", get_port());
  13322. sse::SSEClient sse(client, "/reconnect-with-id");
  13323. sse.set_reconnect_interval(100);
  13324. sse.set_max_reconnect_attempts(3);
  13325. sse.start_async();
  13326. // Wait for at least 2 connections
  13327. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13328. sse.stop();
  13329. // Verify behavior
  13330. std::lock_guard<std::mutex> lock(id_mutex);
  13331. EXPECT_GE(received_last_event_ids.size(), 2u);
  13332. // First connection should have no Last-Event-ID
  13333. if (!received_last_event_ids.empty()) {
  13334. EXPECT_EQ(received_last_event_ids[0], "");
  13335. }
  13336. // Second connection should have Last-Event-ID from first connection
  13337. if (received_last_event_ids.size() >= 2) {
  13338. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13339. }
  13340. }
  13341. // Test: set_headers updates headers used on reconnect
  13342. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13343. std::vector<std::string> received_tokens;
  13344. std::mutex token_mutex;
  13345. // Endpoint that captures Authorization header
  13346. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13347. {
  13348. std::lock_guard<std::mutex> lock(token_mutex);
  13349. received_tokens.push_back(req.get_header_value("Authorization"));
  13350. }
  13351. res.set_chunked_content_provider(
  13352. "text/event-stream", [](size_t offset, DataSink &sink) {
  13353. if (offset == 0) {
  13354. std::string event = "data: hello\n\n";
  13355. sink.write(event.data(), event.size());
  13356. }
  13357. return false; // Close connection to trigger reconnect
  13358. });
  13359. });
  13360. Client client("localhost", get_port());
  13361. Headers headers = {{"Authorization", "Bearer old-token"}};
  13362. sse::SSEClient sse(client, "/auth-check", headers);
  13363. // Update headers on each successful connection
  13364. sse.on_open(
  13365. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13366. sse.set_reconnect_interval(100);
  13367. sse.set_max_reconnect_attempts(3);
  13368. sse.start_async();
  13369. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13370. sse.stop();
  13371. std::lock_guard<std::mutex> lock(token_mutex);
  13372. ASSERT_GE(received_tokens.size(), 2u);
  13373. // First connection uses original header
  13374. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13375. // Second connection uses updated header from set_headers
  13376. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13377. }
  13378. // Test: 401 allows reconnection (so on_error can refresh headers)
  13379. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13380. std::atomic<int> connection_count{0};
  13381. // Endpoint: returns 401 on first attempt, 200 on second
  13382. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13383. int conn = connection_count.fetch_add(1);
  13384. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13385. res.status = StatusCode::Unauthorized_401;
  13386. res.set_content("Unauthorized", "text/plain");
  13387. return;
  13388. }
  13389. res.set_chunked_content_provider(
  13390. "text/event-stream", [](size_t offset, DataSink &sink) {
  13391. if (offset == 0) {
  13392. std::string event = "data: authenticated\n\n";
  13393. sink.write(event.data(), event.size());
  13394. }
  13395. return false;
  13396. });
  13397. });
  13398. Client client("localhost", get_port());
  13399. Headers headers = {{"Authorization", "Bearer expired"}};
  13400. sse::SSEClient sse(client, "/auth-retry", headers);
  13401. std::atomic<bool> message_received{false};
  13402. // Refresh token on error
  13403. sse.on_error(
  13404. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13405. sse.on_message([&](const sse::SSEMessage &msg) {
  13406. if (msg.data == "authenticated") { message_received.store(true); }
  13407. });
  13408. sse.set_reconnect_interval(100);
  13409. sse.set_max_reconnect_attempts(3);
  13410. sse.start_async();
  13411. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13412. sse.stop();
  13413. // Should have reconnected after 401 and succeeded with new token
  13414. EXPECT_GE(connection_count.load(), 2);
  13415. EXPECT_TRUE(message_received.load());
  13416. }
  13417. TEST(Issue2318Test, EmptyHostString) {
  13418. {
  13419. httplib::Client cli_empty("", PORT);
  13420. auto res = cli_empty.Get("/");
  13421. ASSERT_FALSE(res);
  13422. EXPECT_EQ(httplib::Error::Connection, res.error());
  13423. }
  13424. {
  13425. httplib::Client cli(" ", PORT);
  13426. auto res = cli.Get("/");
  13427. ASSERT_FALSE(res);
  13428. EXPECT_EQ(httplib::Error::Connection, res.error());
  13429. }
  13430. }
  13431. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13432. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13433. Server svr;
  13434. // Set a small payload limit (1KB)
  13435. svr.set_payload_max_length(1024);
  13436. svr.Post("/test", [&](const Request &req, Response &res) {
  13437. res.set_content("Body size: " + std::to_string(req.body.size()),
  13438. "text/plain");
  13439. });
  13440. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13441. auto se = detail::scope_exit([&] {
  13442. svr.stop();
  13443. listen_thread.join();
  13444. });
  13445. svr.wait_until_ready();
  13446. // Create data that compresses well but exceeds limit when decompressed
  13447. // 8KB of repeated null bytes compresses to a very small size
  13448. std::string original_data(8 * 1024, '\0');
  13449. // Compress the data using gzip
  13450. std::string compressed_data;
  13451. detail::gzip_compressor compressor;
  13452. compressor.compress(original_data.data(), original_data.size(), true,
  13453. [&](const char *data, size_t size) {
  13454. compressed_data.append(data, size);
  13455. return true;
  13456. });
  13457. // Verify compression worked (compressed should be much smaller)
  13458. ASSERT_LT(compressed_data.size(), original_data.size());
  13459. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13460. // Send compressed data with Content-Encoding: gzip
  13461. Client cli(HOST, PORT);
  13462. Headers headers = {{"Content-Encoding", "gzip"}};
  13463. auto res =
  13464. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13465. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13466. ASSERT_TRUE(res);
  13467. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13468. }
  13469. #endif
  13470. // ============================================================================
  13471. // OpenSSL-Specific Tests
  13472. // ============================================================================
  13473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13474. X509 *readCertificate(const std::string &strFileName) {
  13475. std::ifstream inStream(strFileName);
  13476. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13477. std::istreambuf_iterator<char>());
  13478. if (strCertPEM.empty()) return (nullptr);
  13479. BIO *pbCert = BIO_new(BIO_s_mem());
  13480. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13481. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13482. BIO_free(pbCert);
  13483. return (pCert);
  13484. }
  13485. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13486. std::ifstream inStream(strFileName);
  13487. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13488. std::istreambuf_iterator<char>());
  13489. if (strPrivateKeyPEM.empty()) return (nullptr);
  13490. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13491. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13492. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13493. BIO_free(pbPrivKey);
  13494. return (pPrivateKey);
  13495. }
  13496. TEST(BindServerTest, UpdateCerts) {
  13497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13498. int port = svr.bind_to_any_port("0.0.0.0");
  13499. ASSERT_TRUE(svr.is_valid());
  13500. ASSERT_TRUE(port > 0);
  13501. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13502. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13503. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13504. ASSERT_TRUE(cert != nullptr);
  13505. ASSERT_TRUE(ca_cert != nullptr);
  13506. ASSERT_TRUE(key != nullptr);
  13507. X509_STORE *cert_store = X509_STORE_new();
  13508. X509_STORE_add_cert(cert_store, ca_cert);
  13509. // svr.update_certs(cert, key, cert_store); // deprecated
  13510. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13511. CLIENT_CA_CERT_FILE);
  13512. ASSERT_TRUE(svr.is_valid());
  13513. svr.stop();
  13514. X509_STORE_free(cert_store);
  13515. X509_free(cert);
  13516. X509_free(ca_cert);
  13517. EVP_PKEY_free(key);
  13518. }
  13519. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13520. // client CA list correctly for TLS handshake
  13521. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13522. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13523. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13524. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13525. ASSERT_TRUE(cert != nullptr);
  13526. ASSERT_TRUE(ca_cert != nullptr);
  13527. ASSERT_TRUE(key != nullptr);
  13528. X509_STORE *cert_store = X509_STORE_new();
  13529. X509_STORE_add_cert(cert_store, ca_cert);
  13530. // Use X509-based constructor (deprecated but should still work correctly)
  13531. #pragma GCC diagnostic push
  13532. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13533. SSLServer svr(cert, key, cert_store);
  13534. #pragma GCC diagnostic pop
  13535. ASSERT_TRUE(svr.is_valid());
  13536. // Verify that client CA list is set in SSL_CTX
  13537. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13538. ASSERT_TRUE(ssl_ctx != nullptr);
  13539. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13540. ASSERT_TRUE(ca_list != nullptr);
  13541. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13542. X509_free(cert);
  13543. X509_free(ca_cert);
  13544. EVP_PKEY_free(key);
  13545. }
  13546. // Test that update_certs() updates client CA list correctly
  13547. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13548. // Start with file-based constructor
  13549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13550. ASSERT_TRUE(svr.is_valid());
  13551. // Initially no client CA list should be set
  13552. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13553. ASSERT_TRUE(ssl_ctx != nullptr);
  13554. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13555. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13556. EXPECT_EQ(0, count_before);
  13557. // Now update with client CA (PEM string)
  13558. std::string cert_pem, key_pem, ca_pem;
  13559. read_file(SERVER_CERT_FILE, cert_pem);
  13560. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13561. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13562. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13563. ASSERT_TRUE(svr.is_valid());
  13564. // Now client CA list should be set
  13565. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13566. ASSERT_TRUE(ca_list_after != nullptr);
  13567. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13568. }
  13569. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13570. // Test that the file-path SSLServer constructor properly sets the client CA
  13571. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13573. ASSERT_TRUE(svr.is_valid());
  13574. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13575. ASSERT_TRUE(ssl_ctx != nullptr);
  13576. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13577. ASSERT_TRUE(ca_list != nullptr);
  13578. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13579. }
  13580. #endif
  13581. // ============================================================================
  13582. // MbedTLS-Specific Tests
  13583. // ============================================================================
  13584. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13585. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13586. using namespace httplib::tls;
  13587. // Track if callback was invoked
  13588. bool callback_invoked = false;
  13589. // The callback receives void* ctx which is actually MbedTlsContext*
  13590. // We can access the mbedtls_ssl_config via the context
  13591. auto setup_callback = [&callback_invoked](void *ctx) {
  13592. callback_invoked = true;
  13593. // Cast to MbedTlsContext* to access the ssl config
  13594. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13595. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13596. // Use static variables to hold certificate data (simplified for test)
  13597. static mbedtls_x509_crt own_cert;
  13598. static mbedtls_pk_context own_key;
  13599. static mbedtls_x509_crt ca_chain;
  13600. static bool initialized = false;
  13601. if (!initialized) {
  13602. mbedtls_x509_crt_init(&own_cert);
  13603. mbedtls_pk_init(&own_key);
  13604. mbedtls_x509_crt_init(&ca_chain);
  13605. // Load server certificate
  13606. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13607. return false;
  13608. }
  13609. // Load server private key
  13610. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13611. #if MBEDTLS_VERSION_MAJOR >= 3
  13612. ,
  13613. mbedtls_ctr_drbg_random, nullptr
  13614. #endif
  13615. ) != 0) {
  13616. return false;
  13617. }
  13618. // Load CA chain for client verification
  13619. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13620. return false;
  13621. }
  13622. initialized = true;
  13623. }
  13624. // Configure the SSL config
  13625. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13626. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13627. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13628. // Set minimum TLS version using mbedTLS native API
  13629. #if MBEDTLS_VERSION_MAJOR >= 3
  13630. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13631. #else
  13632. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13633. MBEDTLS_SSL_MINOR_VERSION_3);
  13634. #endif
  13635. return true;
  13636. };
  13637. SSLServer svr(setup_callback);
  13638. ASSERT_TRUE(svr.is_valid());
  13639. ASSERT_TRUE(callback_invoked);
  13640. svr.Get("/test", [&](const Request &req, Response &res) {
  13641. res.set_content("test", "text/plain");
  13642. auto cert = req.peer_cert();
  13643. ASSERT_TRUE(static_cast<bool>(cert));
  13644. auto common_name = cert.subject_cn();
  13645. EXPECT_EQ("Common Name", common_name);
  13646. });
  13647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13648. auto se = detail::scope_exit([&] {
  13649. svr.stop();
  13650. t.join();
  13651. ASSERT_FALSE(svr.is_running());
  13652. });
  13653. svr.wait_until_ready();
  13654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13655. cli.enable_server_certificate_verification(false);
  13656. cli.set_connection_timeout(30);
  13657. auto res = cli.Get("/test");
  13658. ASSERT_TRUE(res);
  13659. ASSERT_EQ(StatusCode::OK_200, res->status);
  13660. }
  13661. #endif
  13662. // WebSocket Tests
  13663. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13664. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13665. // defining the meaning of these bits has been negotiated.
  13666. auto make_frame = [](uint8_t first_byte) {
  13667. std::string frame;
  13668. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13669. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13670. frame += "Hello";
  13671. return frame;
  13672. };
  13673. // RSV1 set (0x40)
  13674. {
  13675. detail::BufferStream strm;
  13676. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13677. ws::Opcode opcode;
  13678. std::string payload;
  13679. bool fin;
  13680. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13681. false, 1024));
  13682. }
  13683. // RSV2 set (0x20)
  13684. {
  13685. detail::BufferStream strm;
  13686. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13687. ws::Opcode opcode;
  13688. std::string payload;
  13689. bool fin;
  13690. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13691. false, 1024));
  13692. }
  13693. // RSV3 set (0x10)
  13694. {
  13695. detail::BufferStream strm;
  13696. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13697. ws::Opcode opcode;
  13698. std::string payload;
  13699. bool fin;
  13700. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13701. false, 1024));
  13702. }
  13703. // No RSV bits set - should succeed
  13704. {
  13705. detail::BufferStream strm;
  13706. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13707. ws::Opcode opcode;
  13708. std::string payload;
  13709. bool fin;
  13710. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13711. false, 1024));
  13712. EXPECT_EQ(ws::Opcode::Text, opcode);
  13713. EXPECT_EQ("Hello", payload);
  13714. EXPECT_TRUE(fin);
  13715. }
  13716. }
  13717. TEST(WebSocketTest, ControlFrameValidation) {
  13718. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13719. // payload length <= 125.
  13720. // Ping with FIN=0 - must be rejected
  13721. {
  13722. detail::BufferStream strm;
  13723. std::string frame;
  13724. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13725. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13726. strm.write(frame.data(), frame.size());
  13727. ws::Opcode opcode;
  13728. std::string payload;
  13729. bool fin;
  13730. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13731. false, 1024));
  13732. }
  13733. // Close with FIN=0 - must be rejected
  13734. {
  13735. detail::BufferStream strm;
  13736. std::string frame;
  13737. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13738. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13739. strm.write(frame.data(), frame.size());
  13740. ws::Opcode opcode;
  13741. std::string payload;
  13742. bool fin;
  13743. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13744. false, 1024));
  13745. }
  13746. // Ping with payload_len=126 (extended length) - must be rejected
  13747. {
  13748. detail::BufferStream strm;
  13749. std::string frame;
  13750. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13751. frame += static_cast<char>(126); // payload_len=126 (>125)
  13752. frame += static_cast<char>(0x00); // extended length high byte
  13753. frame += static_cast<char>(126); // extended length low byte
  13754. frame += std::string(126, 'x');
  13755. strm.write(frame.data(), frame.size());
  13756. ws::Opcode opcode;
  13757. std::string payload;
  13758. bool fin;
  13759. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13760. false, 1024));
  13761. }
  13762. // Ping with FIN=1 and payload_len=125 - should succeed
  13763. {
  13764. detail::BufferStream strm;
  13765. std::string frame;
  13766. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13767. frame += static_cast<char>(125); // payload_len=125
  13768. frame += std::string(125, 'x');
  13769. strm.write(frame.data(), frame.size());
  13770. ws::Opcode opcode;
  13771. std::string payload;
  13772. bool fin;
  13773. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13774. false, 1024));
  13775. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13776. EXPECT_EQ(125u, payload.size());
  13777. EXPECT_TRUE(fin);
  13778. }
  13779. }
  13780. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13781. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13782. // length MUST be 0.
  13783. // MSB set - must be rejected
  13784. {
  13785. detail::BufferStream strm;
  13786. std::string frame;
  13787. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13788. frame += static_cast<char>(127); // 64-bit extended length
  13789. frame += static_cast<char>(0x80); // MSB set (invalid)
  13790. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13791. strm.write(frame.data(), frame.size());
  13792. ws::Opcode opcode;
  13793. std::string payload;
  13794. bool fin;
  13795. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13796. false, 1024));
  13797. }
  13798. // MSB clear - should pass length parsing (will be rejected by max_len,
  13799. // but that's a different check; use a small length to verify)
  13800. {
  13801. detail::BufferStream strm;
  13802. std::string frame;
  13803. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13804. frame += static_cast<char>(127); // 64-bit extended length
  13805. frame += std::string(7, '\0'); // high bytes = 0
  13806. frame += static_cast<char>(0x03); // length = 3
  13807. frame += "abc";
  13808. strm.write(frame.data(), frame.size());
  13809. ws::Opcode opcode;
  13810. std::string payload;
  13811. bool fin;
  13812. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13813. false, 1024));
  13814. EXPECT_EQ(ws::Opcode::Text, opcode);
  13815. EXPECT_EQ("abc", payload);
  13816. }
  13817. }
  13818. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13819. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13820. // Valid UTF-8
  13821. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13822. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13823. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13824. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13825. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13826. // Invalid UTF-8
  13827. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13828. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13829. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13830. EXPECT_FALSE(
  13831. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13832. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13833. }
  13834. TEST(WebSocketTest, ConnectAndDisconnect) {
  13835. Server svr;
  13836. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13837. std::string msg;
  13838. while (ws.read(msg)) {}
  13839. });
  13840. auto port = svr.bind_to_any_port(HOST);
  13841. std::thread t([&]() { svr.listen_after_bind(); });
  13842. svr.wait_until_ready();
  13843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13844. ASSERT_TRUE(client.connect());
  13845. EXPECT_TRUE(client.is_open());
  13846. client.close();
  13847. EXPECT_FALSE(client.is_open());
  13848. svr.stop();
  13849. t.join();
  13850. }
  13851. TEST(WebSocketTest, ValidURL) {
  13852. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13853. EXPECT_TRUE(ws1.is_valid());
  13854. ws::WebSocketClient ws2("ws://example.com/path");
  13855. EXPECT_TRUE(ws2.is_valid());
  13856. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13857. EXPECT_TRUE(ws3.is_valid());
  13858. #ifdef CPPHTTPLIB_SSL_ENABLED
  13859. ws::WebSocketClient wss1("wss://example.com/path");
  13860. EXPECT_TRUE(wss1.is_valid());
  13861. ws::WebSocketClient wss2("wss://example.com:443/path");
  13862. EXPECT_TRUE(wss2.is_valid());
  13863. #endif
  13864. }
  13865. TEST(WebSocketTest, InvalidURL) {
  13866. // No scheme
  13867. ws::WebSocketClient ws1("localhost:8080/path");
  13868. EXPECT_FALSE(ws1.is_valid());
  13869. // No path
  13870. ws::WebSocketClient ws2("ws://localhost:8080");
  13871. EXPECT_FALSE(ws2.is_valid());
  13872. // Empty string
  13873. ws::WebSocketClient ws3("");
  13874. EXPECT_FALSE(ws3.is_valid());
  13875. // Missing host
  13876. ws::WebSocketClient ws4("ws://:8080/path");
  13877. EXPECT_FALSE(ws4.is_valid());
  13878. // Port number overflow — should not crash
  13879. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13880. EXPECT_FALSE(ws5.is_valid());
  13881. // Port out of range
  13882. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13883. EXPECT_FALSE(ws6.is_valid());
  13884. }
  13885. TEST(WebSocketTest, UnsupportedScheme) {
  13886. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13887. ws::WebSocketClient ws1("http://localhost:8080/path");
  13888. EXPECT_FALSE(ws1.is_valid());
  13889. ws::WebSocketClient ws2("https://localhost:8080/path");
  13890. EXPECT_FALSE(ws2.is_valid());
  13891. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13892. EXPECT_FALSE(ws3.is_valid());
  13893. #else
  13894. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13895. std::invalid_argument);
  13896. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13897. std::invalid_argument);
  13898. #endif
  13899. }
  13900. TEST(WebSocketTest, ConnectWhenInvalid) {
  13901. ws::WebSocketClient ws("not a valid url");
  13902. EXPECT_FALSE(ws.is_valid());
  13903. EXPECT_FALSE(ws.connect());
  13904. }
  13905. TEST(WebSocketTest, DefaultPort) {
  13906. ws::WebSocketClient ws1("ws://example.com/path");
  13907. EXPECT_TRUE(ws1.is_valid());
  13908. // ws:// defaults to port 80 (verified by successful parse)
  13909. #ifdef CPPHTTPLIB_SSL_ENABLED
  13910. ws::WebSocketClient ws2("wss://example.com/path");
  13911. EXPECT_TRUE(ws2.is_valid());
  13912. // wss:// defaults to port 443 (verified by successful parse)
  13913. #endif
  13914. }
  13915. TEST(WebSocketTest, IPv6LiteralAddress) {
  13916. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13917. EXPECT_TRUE(ws1.is_valid());
  13918. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13919. EXPECT_TRUE(ws2.is_valid());
  13920. }
  13921. TEST(WebSocketTest, ComplexPath) {
  13922. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13923. EXPECT_TRUE(ws1.is_valid());
  13924. ws::WebSocketClient ws2("ws://localhost:8080/");
  13925. EXPECT_TRUE(ws2.is_valid());
  13926. }
  13927. class WebSocketIntegrationTest : public ::testing::Test {
  13928. protected:
  13929. void SetUp() override {
  13930. server_ = httplib::detail::make_unique<Server>();
  13931. setup_server();
  13932. start_server();
  13933. }
  13934. void TearDown() override {
  13935. server_->stop();
  13936. if (server_thread_.joinable()) { server_thread_.join(); }
  13937. }
  13938. void setup_server() {
  13939. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13940. std::string msg;
  13941. ws::ReadResult ret;
  13942. while ((ret = ws.read(msg))) {
  13943. if (ret == ws::Binary) {
  13944. ws.send(msg.data(), msg.size());
  13945. } else {
  13946. ws.send(msg);
  13947. }
  13948. }
  13949. });
  13950. server_->WebSocket("/ws-echo-string",
  13951. [](const Request &, ws::WebSocket &ws) {
  13952. std::string msg;
  13953. while (ws.read(msg)) {
  13954. ws.send("echo: " + msg);
  13955. }
  13956. });
  13957. server_->WebSocket(
  13958. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13959. // Echo back request metadata
  13960. ws.send("path:" + req.path);
  13961. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13962. std::string msg;
  13963. while (ws.read(msg)) {}
  13964. });
  13965. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13966. std::string msg;
  13967. ws.read(msg); // wait for a message
  13968. ws.close();
  13969. });
  13970. server_->WebSocket("/ws-close-status",
  13971. [](const Request &, ws::WebSocket &ws) {
  13972. std::string msg;
  13973. ws.read(msg); // wait for a message
  13974. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13975. });
  13976. server_->WebSocket(
  13977. "/ws-subprotocol",
  13978. [](const Request &, ws::WebSocket &ws) {
  13979. std::string msg;
  13980. while (ws.read(msg)) {
  13981. ws.send(msg);
  13982. }
  13983. },
  13984. [](const std::vector<std::string> &protocols) -> std::string {
  13985. for (const auto &p : protocols) {
  13986. if (p == "graphql-ws") { return p; }
  13987. }
  13988. return "";
  13989. });
  13990. }
  13991. void start_server() {
  13992. port_ = server_->bind_to_any_port(HOST);
  13993. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13994. server_->wait_until_ready();
  13995. }
  13996. std::unique_ptr<Server> server_;
  13997. std::thread server_thread_;
  13998. int port_ = 0;
  13999. };
  14000. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14002. "/ws-echo");
  14003. ASSERT_TRUE(client.connect());
  14004. ASSERT_TRUE(client.is_open());
  14005. ASSERT_TRUE(client.send("Hello WebSocket"));
  14006. std::string msg;
  14007. EXPECT_EQ(ws::Text, client.read(msg));
  14008. EXPECT_EQ("Hello WebSocket", msg);
  14009. client.close();
  14010. }
  14011. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14013. "/ws-echo");
  14014. ASSERT_TRUE(client.connect());
  14015. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14016. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14017. std::string msg;
  14018. EXPECT_EQ(ws::Binary, client.read(msg));
  14019. EXPECT_EQ(binary_data, msg);
  14020. client.close();
  14021. }
  14022. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14024. "/ws-echo");
  14025. ASSERT_TRUE(client.connect());
  14026. for (int i = 0; i < 10; i++) {
  14027. auto text = "message " + std::to_string(i);
  14028. ASSERT_TRUE(client.send(text));
  14029. std::string msg;
  14030. ASSERT_TRUE(client.read(msg));
  14031. EXPECT_EQ(text, msg);
  14032. }
  14033. client.close();
  14034. }
  14035. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14037. "/ws-close");
  14038. ASSERT_TRUE(client.connect());
  14039. // Send a message to trigger the server to close
  14040. ASSERT_TRUE(client.send("trigger close"));
  14041. // The server will close, so read should return false
  14042. std::string msg;
  14043. EXPECT_FALSE(client.read(msg));
  14044. EXPECT_FALSE(client.is_open());
  14045. }
  14046. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14048. "/ws-echo");
  14049. ASSERT_TRUE(client.connect());
  14050. // 128KB message
  14051. std::string large_data(128 * 1024, 'X');
  14052. ASSERT_TRUE(client.send(large_data));
  14053. std::string msg;
  14054. ASSERT_TRUE(client.read(msg));
  14055. EXPECT_EQ(large_data, msg);
  14056. client.close();
  14057. }
  14058. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14060. "/ws-echo");
  14061. ASSERT_TRUE(client.connect());
  14062. const int num_threads = 4;
  14063. std::vector<std::thread> threads;
  14064. std::atomic<int> send_count{0};
  14065. for (int t = 0; t < num_threads; t++) {
  14066. threads.emplace_back([&client, &send_count, t]() {
  14067. for (int i = 0; i < 5; i++) {
  14068. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14069. if (client.send(text)) { send_count++; }
  14070. }
  14071. });
  14072. }
  14073. for (auto &th : threads) {
  14074. th.join();
  14075. }
  14076. int received = 0;
  14077. std::string msg;
  14078. while (received < send_count.load()) {
  14079. if (!client.read(msg)) { break; }
  14080. received++;
  14081. }
  14082. EXPECT_EQ(send_count.load(), received);
  14083. client.close();
  14084. }
  14085. TEST_F(WebSocketIntegrationTest, ReadString) {
  14086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14087. "/ws-echo-string");
  14088. ASSERT_TRUE(client.connect());
  14089. ASSERT_TRUE(client.send("hello"));
  14090. std::string msg;
  14091. ASSERT_TRUE(client.read(msg));
  14092. EXPECT_EQ("echo: hello", msg);
  14093. ASSERT_TRUE(client.send("world"));
  14094. ASSERT_TRUE(client.read(msg));
  14095. EXPECT_EQ("echo: world", msg);
  14096. client.close();
  14097. }
  14098. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14099. Headers headers = {{"X-Test-Header", "test-value"}};
  14100. ws::WebSocketClient client(
  14101. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14102. ASSERT_TRUE(client.connect());
  14103. std::string msg;
  14104. ASSERT_TRUE(client.read(msg));
  14105. EXPECT_EQ("path:/ws-request-info", msg);
  14106. ASSERT_TRUE(client.read(msg));
  14107. EXPECT_EQ("header:test-value", msg);
  14108. client.close();
  14109. }
  14110. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14112. "/ws-echo");
  14113. client.set_read_timeout(1, 0); // 1 second
  14114. ASSERT_TRUE(client.connect());
  14115. // Don't send anything — server echo handler waits for a message,
  14116. // so read() should time out and return false.
  14117. std::string msg;
  14118. EXPECT_FALSE(client.read(msg));
  14119. }
  14120. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14121. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14122. "/ws-echo");
  14123. client.set_read_timeout(5, 0);
  14124. ASSERT_TRUE(client.connect());
  14125. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14126. // The server should reject it and close the connection.
  14127. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14128. client.send(oversized);
  14129. // The server's read() should have failed due to payload limit,
  14130. // so our read() should return false (connection closed).
  14131. std::string msg;
  14132. EXPECT_FALSE(client.read(msg));
  14133. }
  14134. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14136. "/ws-echo");
  14137. client.set_read_timeout(10, 0);
  14138. ASSERT_TRUE(client.connect());
  14139. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14140. // This should succeed.
  14141. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14142. ASSERT_TRUE(client.send(at_limit));
  14143. std::string msg;
  14144. ASSERT_TRUE(client.read(msg));
  14145. EXPECT_EQ(at_limit.size(), msg.size());
  14146. client.close();
  14147. }
  14148. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14150. "/nonexistent");
  14151. EXPECT_FALSE(client.connect());
  14152. EXPECT_FALSE(client.is_open());
  14153. }
  14154. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14156. "/ws-echo");
  14157. ASSERT_TRUE(client.connect());
  14158. ASSERT_TRUE(client.send(""));
  14159. std::string msg;
  14160. EXPECT_EQ(ws::Text, client.read(msg));
  14161. EXPECT_EQ("", msg);
  14162. client.close();
  14163. }
  14164. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14166. "/ws-echo");
  14167. // First connection
  14168. ASSERT_TRUE(client.connect());
  14169. ASSERT_TRUE(client.send("first"));
  14170. std::string msg;
  14171. ASSERT_TRUE(client.read(msg));
  14172. EXPECT_EQ("first", msg);
  14173. client.close();
  14174. EXPECT_FALSE(client.is_open());
  14175. // Reconnect using the same client object
  14176. ASSERT_TRUE(client.connect());
  14177. ASSERT_TRUE(client.is_open());
  14178. ASSERT_TRUE(client.send("second"));
  14179. ASSERT_TRUE(client.read(msg));
  14180. EXPECT_EQ("second", msg);
  14181. client.close();
  14182. }
  14183. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14184. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14185. "/ws-close-status");
  14186. ASSERT_TRUE(client.connect());
  14187. // Trigger the server to close with GoingAway status
  14188. ASSERT_TRUE(client.send("trigger"));
  14189. // read() should return false after receiving the close frame
  14190. std::string msg;
  14191. EXPECT_FALSE(client.read(msg));
  14192. EXPECT_FALSE(client.is_open());
  14193. }
  14194. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14196. "/ws-echo");
  14197. ASSERT_TRUE(client.connect());
  14198. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14199. EXPECT_FALSE(client.is_open());
  14200. }
  14201. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14202. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14203. ws::WebSocketClient client(
  14204. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14205. ASSERT_TRUE(client.connect());
  14206. // Server should have selected graphql-ws
  14207. EXPECT_EQ("graphql-ws", client.subprotocol());
  14208. client.close();
  14209. }
  14210. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14211. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14212. ws::WebSocketClient client(
  14213. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14214. ASSERT_TRUE(client.connect());
  14215. // Server should not have selected any subprotocol
  14216. EXPECT_TRUE(client.subprotocol().empty());
  14217. client.close();
  14218. }
  14219. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14220. // Connect without requesting any subprotocol
  14221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14222. "/ws-subprotocol");
  14223. ASSERT_TRUE(client.connect());
  14224. EXPECT_TRUE(client.subprotocol().empty());
  14225. client.close();
  14226. }
  14227. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14229. "/ws-echo");
  14230. client.set_tcp_nodelay(true);
  14231. client.set_address_family(AF_INET);
  14232. client.set_connection_timeout(3, 0);
  14233. bool socket_options_called = false;
  14234. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14235. ASSERT_TRUE(client.connect());
  14236. ASSERT_TRUE(client.is_open());
  14237. EXPECT_TRUE(socket_options_called);
  14238. ASSERT_TRUE(client.send("hello"));
  14239. std::string msg;
  14240. auto result = client.read(msg);
  14241. EXPECT_EQ(result, ws::ReadResult::Text);
  14242. EXPECT_EQ(msg, "hello");
  14243. client.close();
  14244. }
  14245. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14246. Server svr;
  14247. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14248. if (!req.has_header("Authorization")) {
  14249. res.status = StatusCode::Unauthorized_401;
  14250. res.set_content("Unauthorized", "text/plain");
  14251. return Server::HandlerResponse::Handled;
  14252. }
  14253. return Server::HandlerResponse::Unhandled;
  14254. });
  14255. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14256. std::string msg;
  14257. while (ws.read(msg)) {
  14258. ws.send(msg);
  14259. }
  14260. });
  14261. auto port = svr.bind_to_any_port("localhost");
  14262. std::thread t([&]() { svr.listen_after_bind(); });
  14263. svr.wait_until_ready();
  14264. // Without Authorization header - should be rejected before upgrade
  14265. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14266. EXPECT_FALSE(client1.connect());
  14267. // With Authorization header - should succeed
  14268. Headers headers = {{"Authorization", "Bearer token123"}};
  14269. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14270. headers);
  14271. ASSERT_TRUE(client2.connect());
  14272. ASSERT_TRUE(client2.send("hello"));
  14273. std::string msg;
  14274. ASSERT_TRUE(client2.read(msg));
  14275. EXPECT_EQ("hello", msg);
  14276. client2.close();
  14277. svr.stop();
  14278. t.join();
  14279. }
  14280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14281. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14282. protected:
  14283. void SetUp() override {
  14284. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14285. SERVER_PRIVATE_KEY_FILE);
  14286. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14287. std::string msg;
  14288. ws::ReadResult ret;
  14289. while ((ret = ws.read(msg))) {
  14290. if (ret == ws::Binary) {
  14291. ws.send(msg.data(), msg.size());
  14292. } else {
  14293. ws.send(msg);
  14294. }
  14295. }
  14296. });
  14297. port_ = server_->bind_to_any_port(HOST);
  14298. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14299. server_->wait_until_ready();
  14300. }
  14301. void TearDown() override {
  14302. server_->stop();
  14303. if (server_thread_.joinable()) { server_thread_.join(); }
  14304. }
  14305. std::unique_ptr<SSLServer> server_;
  14306. std::thread server_thread_;
  14307. int port_ = 0;
  14308. };
  14309. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14310. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14311. "/ws-echo");
  14312. client.enable_server_certificate_verification(false);
  14313. ASSERT_TRUE(client.connect());
  14314. ASSERT_TRUE(client.is_open());
  14315. ASSERT_TRUE(client.send("Hello WSS"));
  14316. std::string msg;
  14317. EXPECT_EQ(ws::Text, client.read(msg));
  14318. EXPECT_EQ("Hello WSS", msg);
  14319. client.close();
  14320. }
  14321. #endif
  14322. #if !defined(_WIN32)
  14323. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14324. auto secret_dir = std::string("./symlink_test_secret");
  14325. auto served_dir = std::string("./symlink_test_served");
  14326. auto secret_file = secret_dir + "/secret.txt";
  14327. auto symlink_path = served_dir + "/escape";
  14328. // Setup: create directories and files
  14329. mkdir(secret_dir.c_str(), 0755);
  14330. mkdir(served_dir.c_str(), 0755);
  14331. {
  14332. std::ofstream ofs(secret_file);
  14333. ofs << "SECRET_DATA";
  14334. }
  14335. // Create symlink using absolute path so it resolves correctly
  14336. char abs_secret[PATH_MAX];
  14337. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14338. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14339. auto se = detail::scope_exit([&] {
  14340. unlink(symlink_path.c_str());
  14341. unlink(secret_file.c_str());
  14342. rmdir(served_dir.c_str());
  14343. rmdir(secret_dir.c_str());
  14344. });
  14345. Server svr;
  14346. svr.set_mount_point("/", served_dir);
  14347. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14348. auto se2 = detail::scope_exit([&] {
  14349. svr.stop();
  14350. listen_thread.join();
  14351. });
  14352. svr.wait_until_ready();
  14353. Client cli("localhost", PORT);
  14354. // Symlink pointing outside base dir should be blocked
  14355. auto res = cli.Get("/escape/secret.txt");
  14356. ASSERT_TRUE(res);
  14357. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14358. }
  14359. #endif
  14360. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14361. // A GET request with Content-Length to a static file handler must have its
  14362. // body drained before the keep-alive connection is reused. Otherwise the
  14363. // unread body bytes are interpreted as the next HTTP request.
  14364. //
  14365. // The body is sent AFTER receiving the first response (as in the original
  14366. // PoC) so that the stream_line_reader cannot buffer it together with the
  14367. // headers of the first request.
  14368. Server svr;
  14369. svr.set_mount_point("/", "./www");
  14370. std::atomic<int> smuggled_count(0);
  14371. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14372. smuggled_count++;
  14373. res.set_content("oops", "text/plain");
  14374. });
  14375. auto port = svr.bind_to_any_port("localhost");
  14376. thread t = thread([&] { svr.listen_after_bind(); });
  14377. auto se = detail::scope_exit([&] {
  14378. svr.stop();
  14379. t.join();
  14380. });
  14381. svr.wait_until_ready();
  14382. auto error = Error::Success;
  14383. auto sock = detail::create_client_socket(
  14384. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14385. /*connection_timeout_sec=*/2, 0,
  14386. /*read_timeout_sec=*/2, 0,
  14387. /*write_timeout_sec=*/2, 0, std::string(), error);
  14388. ASSERT_NE(INVALID_SOCKET, sock);
  14389. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14390. // The "smuggled" request will be sent as the body of the outer GET
  14391. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14392. "Host: localhost\r\n"
  14393. "Connection: close\r\n"
  14394. "\r\n";
  14395. // Step 1: Send only the outer request headers (no body yet)
  14396. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14397. "Host: localhost\r\n"
  14398. "Content-Length: " +
  14399. std::to_string(smuggled.size()) +
  14400. "\r\n"
  14401. "\r\n";
  14402. auto sent =
  14403. send(sock, outer_headers.data(), outer_headers.size(), MSG_NOSIGNAL);
  14404. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14405. // Step 2: Read the first response (server serves file without reading body)
  14406. std::string first_response;
  14407. char buf[4096];
  14408. for (;;) {
  14409. auto n = recv(sock, buf, sizeof(buf), 0);
  14410. if (n <= 0) break;
  14411. first_response.append(buf, static_cast<size_t>(n));
  14412. // Stop once we have a complete response (headers + body)
  14413. auto hdr_end = first_response.find("\r\n\r\n");
  14414. if (hdr_end != std::string::npos) {
  14415. // Check for Content-Length to know when the body is complete
  14416. auto cl_pos = first_response.find("Content-Length:");
  14417. if (cl_pos != std::string::npos) {
  14418. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14419. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14420. auto cl = std::stoul(
  14421. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14422. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14423. } else {
  14424. break; // No Content-Length, assume headers-only response
  14425. }
  14426. }
  14427. }
  14428. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14429. // Step 3: Now send the body, which looks like a new HTTP request.
  14430. // On a vulnerable server the keep-alive loop reads this as a second request.
  14431. sent = send(sock, smuggled.data(), smuggled.size(), MSG_NOSIGNAL);
  14432. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14433. // Step 4: Try to read a second response (should NOT exist after fix)
  14434. std::string second_response;
  14435. for (;;) {
  14436. auto n = recv(sock, buf, sizeof(buf), 0);
  14437. if (n <= 0) break;
  14438. second_response.append(buf, static_cast<size_t>(n));
  14439. }
  14440. // The smuggled request must NOT have been processed
  14441. EXPECT_EQ(0, smuggled_count.load());
  14442. }
  14443. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14444. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14445. // must be rejected with 400 Bad Request.
  14446. Server svr;
  14447. svr.Post("/test", [&](const Request &, Response &res) {
  14448. res.set_content("ok", "text/plain");
  14449. });
  14450. thread t = thread([&] { svr.listen(HOST, PORT); });
  14451. auto se = detail::scope_exit([&] {
  14452. svr.stop();
  14453. t.join();
  14454. ASSERT_FALSE(svr.is_running());
  14455. });
  14456. svr.wait_until_ready();
  14457. // Exact "chunked"
  14458. {
  14459. auto req = "POST /test HTTP/1.1\r\n"
  14460. "Host: localhost\r\n"
  14461. "Content-Length: 5\r\n"
  14462. "Transfer-Encoding: chunked\r\n"
  14463. "Connection: close\r\n"
  14464. "\r\n"
  14465. "hello";
  14466. std::string response;
  14467. ASSERT_TRUE(send_request(1, req, &response));
  14468. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14469. response.substr(0, response.find("\r\n")));
  14470. }
  14471. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14472. {
  14473. auto req = "POST /test HTTP/1.1\r\n"
  14474. "Host: localhost\r\n"
  14475. "Content-Length: 5\r\n"
  14476. "Transfer-Encoding: gzip, chunked\r\n"
  14477. "Connection: close\r\n"
  14478. "\r\n"
  14479. "hello";
  14480. std::string response;
  14481. ASSERT_TRUE(send_request(1, req, &response));
  14482. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14483. response.substr(0, response.find("\r\n")));
  14484. }
  14485. }