test.cc 529 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308
  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(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. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1187. auto host = "httpcan.org";
  1188. auto path = std::string{"/range/32"};
  1189. #else
  1190. auto host = "nghttp2.org";
  1191. auto path = std::string{"/httpbin/range/32"};
  1192. #endif
  1193. #ifdef CPPHTTPLIB_SSL_ENABLED
  1194. auto port = 443;
  1195. SSLClient cli(host, port);
  1196. #else
  1197. auto port = 80;
  1198. Client cli(host, port);
  1199. #endif
  1200. cli.set_connection_timeout(5);
  1201. {
  1202. auto res = cli.Get(path);
  1203. ASSERT_TRUE(res);
  1204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1205. EXPECT_EQ(StatusCode::OK_200, res->status);
  1206. }
  1207. {
  1208. Headers headers = {make_range_header({{1, -1}})};
  1209. auto res = cli.Get(path, headers);
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1213. }
  1214. {
  1215. Headers headers = {make_range_header({{1, 10}})};
  1216. auto res = cli.Get(path, headers);
  1217. ASSERT_TRUE(res);
  1218. EXPECT_EQ("bcdefghijk", res->body);
  1219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1220. }
  1221. {
  1222. Headers headers = {make_range_header({{0, 31}})};
  1223. auto res = cli.Get(path, headers);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1226. EXPECT_EQ(StatusCode::OK_200, res->status);
  1227. }
  1228. {
  1229. Headers headers = {make_range_header({{0, -1}})};
  1230. auto res = cli.Get(path, headers);
  1231. ASSERT_TRUE(res);
  1232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1233. EXPECT_EQ(StatusCode::OK_200, res->status);
  1234. }
  1235. {
  1236. Headers headers = {make_range_header({{0, 32}})};
  1237. auto res = cli.Get(path, headers);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1240. }
  1241. }
  1242. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1243. auto host = "unresolvableaddress.local";
  1244. auto path = std::string{"/"};
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(1);
  1253. {
  1254. auto res = cli.Get(path);
  1255. ASSERT_FALSE(res);
  1256. }
  1257. std::this_thread::sleep_for(std::chrono::seconds(8));
  1258. }
  1259. TEST(ConnectionErrorTest, InvalidHost) {
  1260. auto host = "-abcde.com";
  1261. #ifdef CPPHTTPLIB_SSL_ENABLED
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. cli.set_connection_timeout(std::chrono::seconds(2));
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Connection, res.error());
  1272. }
  1273. TEST(ConnectionErrorTest, InvalidHost2) {
  1274. auto host = "httpcan.org/";
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_connection_timeout(std::chrono::seconds(2));
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::Connection, res.error());
  1284. }
  1285. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1286. auto host = "httpcan.org/";
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. SSLClient cli(host);
  1289. #else
  1290. Client cli(host);
  1291. #endif
  1292. cli.set_connection_timeout(std::chrono::seconds(2));
  1293. auto res = cli.Get("/");
  1294. ASSERT_TRUE(!res);
  1295. stringstream s;
  1296. s << "error code: " << res.error();
  1297. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1298. }
  1299. TEST(ConnectionErrorTest, InvalidPort) {
  1300. auto host = "localhost";
  1301. auto port = 44380;
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. SSLClient cli(host, port);
  1304. #else
  1305. Client cli(host, port);
  1306. #endif
  1307. cli.set_connection_timeout(std::chrono::seconds(2));
  1308. auto res = cli.Get("/");
  1309. ASSERT_TRUE(!res);
  1310. EXPECT_TRUE(Error::Connection == res.error() ||
  1311. Error::ConnectionTimeout == res.error());
  1312. }
  1313. TEST(ConnectionErrorTest, Timeout_Online) {
  1314. auto host = "google.com";
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. auto port = 44380;
  1317. SSLClient cli(host, port);
  1318. #else
  1319. auto port = 8080;
  1320. Client cli(host, port);
  1321. #endif
  1322. cli.set_connection_timeout(std::chrono::seconds(2));
  1323. // only probe one address type so that the error reason
  1324. // correlates to the timed-out IPv4, not the unsupported
  1325. // IPv6 connection attempt
  1326. cli.set_address_family(AF_INET);
  1327. auto res = cli.Get("/");
  1328. ASSERT_TRUE(!res);
  1329. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1330. }
  1331. TEST(CancelTest, NoCancel_Online) {
  1332. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1333. auto host = "httpcan.org";
  1334. auto path = std::string{"/range/32"};
  1335. #else
  1336. auto host = "nghttp2.org";
  1337. auto path = std::string{"/httpbin/range/32"};
  1338. #endif
  1339. #ifdef CPPHTTPLIB_SSL_ENABLED
  1340. auto port = 443;
  1341. SSLClient cli(host, port);
  1342. #else
  1343. auto port = 80;
  1344. Client cli(host, port);
  1345. #endif
  1346. cli.set_connection_timeout(std::chrono::seconds(5));
  1347. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. }
  1352. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1353. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1354. auto host = "httpcan.org";
  1355. auto path = std::string{"/range/32"};
  1356. #else
  1357. auto host = "nghttp2.org";
  1358. auto path = std::string{"/httpbin/range/32"};
  1359. #endif
  1360. #ifdef CPPHTTPLIB_SSL_ENABLED
  1361. auto port = 443;
  1362. SSLClient cli(host, port);
  1363. #else
  1364. auto port = 80;
  1365. Client cli(host, port);
  1366. #endif
  1367. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1368. cli.set_connection_timeout(std::chrono::seconds(5));
  1369. ASSERT_TRUE(!res);
  1370. EXPECT_EQ(Error::Canceled, res.error());
  1371. }
  1372. TEST(CancelTest, WithCancelLargePayload_Online) {
  1373. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1374. auto host = "httpcan.org";
  1375. auto path = std::string{"/range/65536"};
  1376. #else
  1377. auto host = "nghttp2.org";
  1378. auto path = std::string{"/httpbin/range/65536"};
  1379. #endif
  1380. #ifdef CPPHTTPLIB_SSL_ENABLED
  1381. auto port = 443;
  1382. SSLClient cli(host, port);
  1383. #else
  1384. auto port = 80;
  1385. Client cli(host, port);
  1386. #endif
  1387. cli.set_connection_timeout(std::chrono::seconds(5));
  1388. uint32_t count = 0;
  1389. auto res =
  1390. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1391. ASSERT_TRUE(!res);
  1392. EXPECT_EQ(Error::Canceled, res.error());
  1393. }
  1394. TEST(CancelTest, NoCancelPost) {
  1395. Server svr;
  1396. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1397. res.set_content("Hello World!", "text/plain");
  1398. });
  1399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. thread.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. Client cli(HOST, PORT);
  1407. cli.set_connection_timeout(std::chrono::seconds(5));
  1408. auto res =
  1409. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1410. "application/json", [](uint64_t, uint64_t) { return true; });
  1411. ASSERT_TRUE(res);
  1412. EXPECT_EQ("Hello World!", res->body);
  1413. EXPECT_EQ(StatusCode::OK_200, res->status);
  1414. }
  1415. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1416. Server svr;
  1417. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1418. res.set_content("Hello World!", "text/plain");
  1419. });
  1420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. thread.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. Client cli(HOST, PORT);
  1428. cli.set_connection_timeout(std::chrono::seconds(5));
  1429. auto res =
  1430. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1431. "application/json", [](uint64_t, uint64_t) { return false; });
  1432. ASSERT_TRUE(!res);
  1433. EXPECT_EQ(Error::Canceled, res.error());
  1434. }
  1435. TEST(CancelTest, WithCancelLargePayloadPost) {
  1436. Server svr;
  1437. svr.set_payload_max_length(200 * 1024 * 1024);
  1438. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1439. res.set_content(LARGE_DATA, "text/plain");
  1440. });
  1441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. thread.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. Client cli(HOST, PORT);
  1449. cli.set_payload_max_length(200 * 1024 * 1024);
  1450. cli.set_connection_timeout(std::chrono::seconds(5));
  1451. auto res =
  1452. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1453. "application/json", [](uint64_t, uint64_t) { return false; });
  1454. ASSERT_TRUE(!res);
  1455. EXPECT_EQ(Error::Canceled, res.error());
  1456. }
  1457. TEST(CancelTest, NoCancelPut) {
  1458. Server svr;
  1459. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1460. res.set_content("Hello World!", "text/plain");
  1461. });
  1462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1463. auto se = detail::scope_exit([&] {
  1464. svr.stop();
  1465. thread.join();
  1466. ASSERT_FALSE(svr.is_running());
  1467. });
  1468. svr.wait_until_ready();
  1469. Client cli(HOST, PORT);
  1470. cli.set_connection_timeout(std::chrono::seconds(5));
  1471. auto res =
  1472. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1473. "application/json", [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("Hello World!", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1479. Server svr;
  1480. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return false; });
  1495. ASSERT_TRUE(!res);
  1496. EXPECT_EQ(Error::Canceled, res.error());
  1497. }
  1498. TEST(CancelTest, WithCancelLargePayloadPut) {
  1499. Server svr;
  1500. svr.set_payload_max_length(200 * 1024 * 1024);
  1501. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_payload_max_length(200 * 1024 * 1024);
  1513. cli.set_connection_timeout(std::chrono::seconds(5));
  1514. auto res =
  1515. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1516. "application/json", [](uint64_t, uint64_t) { return false; });
  1517. ASSERT_TRUE(!res);
  1518. EXPECT_EQ(Error::Canceled, res.error());
  1519. }
  1520. TEST(CancelTest, NoCancelPatch) {
  1521. Server svr;
  1522. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1523. res.set_content("Hello World!", "text/plain");
  1524. });
  1525. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1526. auto se = detail::scope_exit([&] {
  1527. svr.stop();
  1528. thread.join();
  1529. ASSERT_FALSE(svr.is_running());
  1530. });
  1531. svr.wait_until_ready();
  1532. Client cli(HOST, PORT);
  1533. cli.set_connection_timeout(std::chrono::seconds(5));
  1534. auto res =
  1535. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1536. "application/json", [](uint64_t, uint64_t) { return true; });
  1537. ASSERT_TRUE(res);
  1538. EXPECT_EQ("Hello World!", res->body);
  1539. EXPECT_EQ(StatusCode::OK_200, res->status);
  1540. }
  1541. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1542. Server svr;
  1543. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1544. res.set_content("Hello World!", "text/plain");
  1545. });
  1546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1547. auto se = detail::scope_exit([&] {
  1548. svr.stop();
  1549. thread.join();
  1550. ASSERT_FALSE(svr.is_running());
  1551. });
  1552. svr.wait_until_ready();
  1553. Client cli(HOST, PORT);
  1554. cli.set_connection_timeout(std::chrono::seconds(5));
  1555. auto res =
  1556. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1557. "application/json", [](uint64_t, uint64_t) { return false; });
  1558. ASSERT_TRUE(!res);
  1559. EXPECT_EQ(Error::Canceled, res.error());
  1560. }
  1561. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1562. Server svr;
  1563. svr.set_payload_max_length(200 * 1024 * 1024);
  1564. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1565. res.set_content(LARGE_DATA, "text/plain");
  1566. });
  1567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1568. auto se = detail::scope_exit([&] {
  1569. svr.stop();
  1570. thread.join();
  1571. ASSERT_FALSE(svr.is_running());
  1572. });
  1573. svr.wait_until_ready();
  1574. Client cli(HOST, PORT);
  1575. cli.set_payload_max_length(200 * 1024 * 1024);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, NoCancelDelete) {
  1584. Server svr;
  1585. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1586. res.set_content("Hello World!", "text/plain");
  1587. });
  1588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1589. auto se = detail::scope_exit([&] {
  1590. svr.stop();
  1591. thread.join();
  1592. ASSERT_FALSE(svr.is_running());
  1593. });
  1594. svr.wait_until_ready();
  1595. Client cli(HOST, PORT);
  1596. cli.set_connection_timeout(std::chrono::seconds(5));
  1597. auto res =
  1598. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1599. "application/json", [](uint64_t, uint64_t) { return true; });
  1600. ASSERT_TRUE(res);
  1601. EXPECT_EQ("Hello World!", res->body);
  1602. EXPECT_EQ(StatusCode::OK_200, res->status);
  1603. }
  1604. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1605. Server svr;
  1606. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1607. res.set_content("Hello World!", "text/plain");
  1608. });
  1609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1610. auto se = detail::scope_exit([&] {
  1611. svr.stop();
  1612. thread.join();
  1613. ASSERT_FALSE(svr.is_running());
  1614. });
  1615. svr.wait_until_ready();
  1616. Client cli(HOST, PORT);
  1617. cli.set_connection_timeout(std::chrono::seconds(5));
  1618. auto res =
  1619. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1620. "application/json", [](uint64_t, uint64_t) { return false; });
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Canceled, res.error());
  1623. }
  1624. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1625. Server svr;
  1626. svr.set_payload_max_length(200 * 1024 * 1024);
  1627. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1628. res.set_content(LARGE_DATA, "text/plain");
  1629. });
  1630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1631. auto se = detail::scope_exit([&] {
  1632. svr.stop();
  1633. thread.join();
  1634. ASSERT_FALSE(svr.is_running());
  1635. });
  1636. svr.wait_until_ready();
  1637. Client cli(HOST, PORT);
  1638. cli.set_payload_max_length(200 * 1024 * 1024);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. static std::string remove_whitespace(const std::string &input) {
  1647. std::string output;
  1648. output.reserve(input.size());
  1649. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1650. [](unsigned char c) { return !std::isspace(c); });
  1651. return output;
  1652. }
  1653. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. auto host = "httpcan.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #else
  1658. auto host = "nghttp2.org";
  1659. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1660. #endif
  1661. #ifdef CPPHTTPLIB_SSL_ENABLED
  1662. auto port = 443;
  1663. SSLClient cli(host, port);
  1664. #else
  1665. auto port = 80;
  1666. Client cli(host, port);
  1667. #endif
  1668. {
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. {
  1674. auto res =
  1675. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1678. remove_whitespace(res->body));
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. }
  1681. {
  1682. cli.set_basic_auth("hello", "world");
  1683. auto res = cli.Get(path);
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1686. remove_whitespace(res->body));
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. {
  1690. cli.set_basic_auth("hello", "bad");
  1691. auto res = cli.Get(path);
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1694. }
  1695. {
  1696. cli.set_basic_auth("bad", "world");
  1697. auto res = cli.Get(path);
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1700. }
  1701. }
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1704. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1705. auto host = "httpcan.org";
  1706. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1707. auto paths = std::vector<std::string>{
  1708. "/digest-auth/auth/hello/world/MD5",
  1709. "/digest-auth/auth/hello/world/SHA-256",
  1710. "/digest-auth/auth/hello/world/SHA-512",
  1711. };
  1712. #else
  1713. auto host = "nghttp2.org";
  1714. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1715. auto paths = std::vector<std::string>{
  1716. "/httpbin/digest-auth/auth/hello/world/MD5",
  1717. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1718. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1719. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1720. };
  1721. #endif
  1722. auto port = 443;
  1723. SSLClient cli(host, port);
  1724. {
  1725. auto res = cli.Get(unauth_path);
  1726. ASSERT_TRUE(res);
  1727. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1728. }
  1729. {
  1730. cli.set_digest_auth("hello", "world");
  1731. for (const auto &path : paths) {
  1732. auto res = cli.Get(path.c_str());
  1733. ASSERT_TRUE(res);
  1734. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1735. std::string algo(path.substr(path.rfind('/') + 1));
  1736. EXPECT_EQ(
  1737. remove_whitespace("{\"algorithm\":\"" + algo +
  1738. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1739. remove_whitespace(res->body));
  1740. #else
  1741. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1742. remove_whitespace(res->body));
  1743. #endif
  1744. EXPECT_EQ(StatusCode::OK_200, res->status);
  1745. }
  1746. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1747. cli.set_digest_auth("hello", "bad");
  1748. for (const auto &path : paths) {
  1749. auto res = cli.Get(path.c_str());
  1750. ASSERT_TRUE(res);
  1751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1752. }
  1753. #endif
  1754. }
  1755. }
  1756. #endif
  1757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1758. auto host = "google.com";
  1759. auto another_host = "example.com";
  1760. auto wrong_ip = "0.0.0.0";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1767. auto res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1770. }
  1771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1772. auto host = "google.com";
  1773. auto wrong_ip = "0.0.0.0";
  1774. #ifdef CPPHTTPLIB_SSL_ENABLED
  1775. SSLClient cli(host);
  1776. #else
  1777. Client cli(host);
  1778. #endif
  1779. cli.set_hostname_addr_map({{host, wrong_ip}});
  1780. auto res = cli.Get("/");
  1781. ASSERT_TRUE(!res);
  1782. EXPECT_EQ(Error::Connection, res.error());
  1783. }
  1784. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1785. auto host = "nghttp2.org";
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. SSLClient cli(host);
  1788. #else
  1789. Client cli(host);
  1790. #endif
  1791. cli.set_follow_location(true);
  1792. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1793. ASSERT_TRUE(res);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. TEST(RedirectTest, Redirect_Online) {
  1797. auto host = "nghttp2.org";
  1798. #ifdef CPPHTTPLIB_SSL_ENABLED
  1799. SSLClient cli(host);
  1800. #else
  1801. Client cli(host);
  1802. #endif
  1803. cli.set_follow_location(true);
  1804. auto res = cli.Get("/httpbin/redirect/3");
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(RelativeRedirectTest, Redirect_Online) {
  1809. auto host = "nghttp2.org";
  1810. #ifdef CPPHTTPLIB_SSL_ENABLED
  1811. SSLClient cli(host);
  1812. #else
  1813. Client cli(host);
  1814. #endif
  1815. cli.set_follow_location(true);
  1816. auto res = cli.Get("/httpbin/relative-redirect/3");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. }
  1820. TEST(TooManyRedirectTest, Redirect_Online) {
  1821. auto host = "nghttp2.org";
  1822. #ifdef CPPHTTPLIB_SSL_ENABLED
  1823. SSLClient cli(host);
  1824. #else
  1825. Client cli(host);
  1826. #endif
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/httpbin/redirect/21");
  1829. ASSERT_TRUE(!res);
  1830. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1831. }
  1832. #ifdef CPPHTTPLIB_SSL_ENABLED
  1833. TEST(YahooRedirectTest, Redirect_Online) {
  1834. Client cli("yahoo.com");
  1835. auto res = cli.Get("/");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1838. cli.set_follow_location(true);
  1839. res = cli.Get("/");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1843. }
  1844. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1845. #define REDIR_HOST "httpbingo.org"
  1846. #define REDIR_PATH "/redirect-to"
  1847. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1848. SSLClient cli(REDIR_HOST);
  1849. cli.set_follow_location(true);
  1850. auto res =
  1851. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1856. SSLClient cli(REDIR_HOST);
  1857. cli.set_follow_location(true);
  1858. Params params;
  1859. params.emplace("url", "http://example.com");
  1860. params.emplace("status_code", "302");
  1861. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1866. SSLClient cli(REDIR_HOST);
  1867. cli.set_follow_location(true);
  1868. Params params;
  1869. params.emplace("url", "http://example.com");
  1870. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(StatusCode::OK_200, res->status);
  1873. }
  1874. TEST(UrlWithSpace, Redirect_Online) {
  1875. SSLClient cli("edge.forgecdn.net");
  1876. cli.set_follow_location(true);
  1877. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1878. ASSERT_TRUE(res);
  1879. EXPECT_EQ(StatusCode::OK_200, res->status);
  1880. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1881. }
  1882. #endif
  1883. #if !defined(_WIN32) && !defined(_WIN64)
  1884. TEST(ReceiveSignals, Signal) {
  1885. auto setupSignalHandlers = []() {
  1886. struct sigaction act;
  1887. sigemptyset(&act.sa_mask);
  1888. act.sa_flags = SA_SIGINFO;
  1889. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1890. switch (sig) {
  1891. case SIGINT:
  1892. default: break;
  1893. }
  1894. };
  1895. ::sigaction(SIGINT, &act, nullptr);
  1896. };
  1897. Server svr;
  1898. int port = 0;
  1899. auto thread = std::thread([&]() {
  1900. setupSignalHandlers();
  1901. port = svr.bind_to_any_port(HOST);
  1902. svr.listen_after_bind();
  1903. });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. ASSERT_TRUE(svr.is_running());
  1911. pthread_kill(thread.native_handle(), SIGINT);
  1912. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1913. ASSERT_TRUE(svr.is_running());
  1914. }
  1915. #endif
  1916. TEST(RedirectToDifferentPort, Redirect) {
  1917. Server svr1;
  1918. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("Hello World!", "text/plain");
  1920. });
  1921. int svr1_port = 0;
  1922. auto thread1 = std::thread([&]() {
  1923. svr1_port = svr1.bind_to_any_port(HOST);
  1924. svr1.listen_after_bind();
  1925. });
  1926. Server svr2;
  1927. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1928. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1929. });
  1930. int svr2_port = 0;
  1931. auto thread2 = std::thread([&]() {
  1932. svr2_port = svr2.bind_to_any_port(HOST);
  1933. svr2.listen_after_bind();
  1934. });
  1935. auto se = detail::scope_exit([&] {
  1936. svr2.stop();
  1937. thread2.join();
  1938. svr1.stop();
  1939. thread1.join();
  1940. ASSERT_FALSE(svr2.is_running());
  1941. ASSERT_FALSE(svr1.is_running());
  1942. });
  1943. svr1.wait_until_ready();
  1944. svr2.wait_until_ready();
  1945. Client cli("localhost", svr2_port);
  1946. cli.set_follow_location(true);
  1947. auto res = cli.Get("/2");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(StatusCode::OK_200, res->status);
  1950. EXPECT_EQ("Hello World!", res->body);
  1951. }
  1952. static void
  1953. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1954. Server svr1;
  1955. std::string captured_authorization;
  1956. svr1.Get("/target", [&](const Request &req, Response &res) {
  1957. captured_authorization = req.get_header_value("Authorization");
  1958. res.set_content("OK", "text/plain");
  1959. });
  1960. int svr1_port = 0;
  1961. auto thread1 = std::thread([&]() {
  1962. svr1_port = svr1.bind_to_any_port(HOST);
  1963. svr1.listen_after_bind();
  1964. });
  1965. Server svr2;
  1966. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1967. res.set_redirect(
  1968. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1969. });
  1970. int svr2_port = 0;
  1971. auto thread2 = std::thread([&]() {
  1972. svr2_port = svr2.bind_to_any_port(HOST);
  1973. svr2.listen_after_bind();
  1974. });
  1975. auto se = detail::scope_exit([&] {
  1976. svr2.stop();
  1977. thread2.join();
  1978. svr1.stop();
  1979. thread1.join();
  1980. ASSERT_FALSE(svr2.is_running());
  1981. ASSERT_FALSE(svr1.is_running());
  1982. });
  1983. svr1.wait_until_ready();
  1984. svr2.wait_until_ready();
  1985. Client cli("localhost", svr2_port);
  1986. cli.set_follow_location(true);
  1987. set_auth(cli);
  1988. auto res = cli.Get("/redir");
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1992. EXPECT_TRUE(captured_authorization.empty());
  1993. }
  1994. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1995. TestDoNotForwardCredentialsOnRedirect(
  1996. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1997. }
  1998. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1999. TestDoNotForwardCredentialsOnRedirect(
  2000. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2001. }
  2002. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2003. Server svr;
  2004. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2005. // Port number that overflows int — should not crash
  2006. res.set_redirect("http://localhost:99999999999999999999/target");
  2007. });
  2008. auto port = svr.bind_to_any_port(HOST);
  2009. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2010. auto se = detail::scope_exit([&] {
  2011. svr.stop();
  2012. thread.join();
  2013. ASSERT_FALSE(svr.is_running());
  2014. });
  2015. svr.wait_until_ready();
  2016. Client cli(HOST, port);
  2017. cli.set_follow_location(true);
  2018. auto res = cli.Get("/redir");
  2019. // Should fail gracefully, not crash (no valid response due to bad port)
  2020. EXPECT_FALSE(res);
  2021. }
  2022. TEST(RedirectFromPageWithContent, Redirect) {
  2023. Server svr;
  2024. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2025. res.set_content("___", "text/plain");
  2026. res.set_redirect("/2");
  2027. });
  2028. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2029. res.set_content("Hello World!", "text/plain");
  2030. });
  2031. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2032. auto se = detail::scope_exit([&] {
  2033. svr.stop();
  2034. th.join();
  2035. ASSERT_FALSE(svr.is_running());
  2036. });
  2037. svr.wait_until_ready();
  2038. {
  2039. Client cli("localhost", PORT);
  2040. cli.set_follow_location(true);
  2041. std::string body;
  2042. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2043. body.append(data, data_length);
  2044. return true;
  2045. });
  2046. ASSERT_TRUE(res);
  2047. EXPECT_EQ(StatusCode::OK_200, res->status);
  2048. EXPECT_EQ("Hello World!", body);
  2049. }
  2050. {
  2051. Client cli("localhost", PORT);
  2052. std::string body;
  2053. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2054. body.append(data, data_length);
  2055. return true;
  2056. });
  2057. ASSERT_TRUE(res);
  2058. EXPECT_EQ(StatusCode::Found_302, res->status);
  2059. EXPECT_EQ("___", body);
  2060. }
  2061. }
  2062. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2063. Server svr;
  2064. auto port_str = std::to_string(PORT);
  2065. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2066. auto expected_host = "[::1]:" + port_str;
  2067. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2068. res.set_content("___", "text/plain");
  2069. // res.set_redirect("/2");
  2070. res.set_redirect(redirect_url);
  2071. });
  2072. svr.Get("/2", [&](const Request &req, Response &res) {
  2073. auto host_header = req.headers.find("Host");
  2074. ASSERT_TRUE(host_header != req.headers.end());
  2075. EXPECT_EQ(expected_host, host_header->second);
  2076. res.set_content("Hello World!", "text/plain");
  2077. });
  2078. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2079. auto se = detail::scope_exit([&] {
  2080. svr.stop();
  2081. th.join();
  2082. ASSERT_FALSE(svr.is_running());
  2083. });
  2084. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2085. // actually starts anything, so the condition !svr.is_running() will
  2086. // always remain true, and the loop never stops.
  2087. // This basically counts how many milliseconds have passed since the
  2088. // call to svr.listen(), and if after 5 seconds nothing started yet
  2089. // aborts the test.
  2090. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2091. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2092. ASSERT_LT(milliseconds, 5000U);
  2093. }
  2094. {
  2095. Client cli("::1", PORT);
  2096. cli.set_follow_location(true);
  2097. std::string body;
  2098. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2099. body.append(data, data_length);
  2100. return true;
  2101. });
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. EXPECT_EQ("Hello World!", body);
  2105. }
  2106. {
  2107. Client cli("::1", PORT);
  2108. std::string body;
  2109. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2110. body.append(data, data_length);
  2111. return true;
  2112. });
  2113. ASSERT_TRUE(res);
  2114. EXPECT_EQ(StatusCode::Found_302, res->status);
  2115. EXPECT_EQ("___", body);
  2116. }
  2117. }
  2118. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2119. Server svr;
  2120. svr.Get("/foo", [](const Request &req, Response &res) {
  2121. auto a = req.params.find("a");
  2122. if (a != req.params.end()) {
  2123. res.set_content((*a).second, "text/plain");
  2124. res.status = StatusCode::OK_200;
  2125. } else {
  2126. res.status = StatusCode::BadRequest_400;
  2127. }
  2128. });
  2129. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2130. auto se = detail::scope_exit([&] {
  2131. svr.stop();
  2132. thread.join();
  2133. ASSERT_FALSE(svr.is_running());
  2134. });
  2135. svr.wait_until_ready();
  2136. {
  2137. Client cli(HOST, PORT);
  2138. cli.set_path_encode(false);
  2139. auto res = cli.Get("/foo?a=explicitly+encoded");
  2140. ASSERT_TRUE(res);
  2141. EXPECT_EQ(StatusCode::OK_200, res->status);
  2142. // This expects it back with a space, as the `+` won't have been
  2143. // url-encoded, and server-side the params get decoded turning `+`
  2144. // into spaces.
  2145. EXPECT_EQ("explicitly encoded", res->body);
  2146. }
  2147. }
  2148. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2149. Server svr;
  2150. svr.Get("/", [](const Request &req, Response &) {
  2151. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2152. });
  2153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2154. auto se = detail::scope_exit([&] {
  2155. svr.stop();
  2156. thread.join();
  2157. ASSERT_FALSE(svr.is_running());
  2158. });
  2159. svr.wait_until_ready();
  2160. {
  2161. Client cli(HOST, PORT);
  2162. cli.set_path_encode(false);
  2163. auto res = cli.Get("/?something=%0A");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. }
  2167. }
  2168. TEST(BindServerTest, BindDualStack) {
  2169. Server svr;
  2170. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2171. res.set_content("Hello World!", "text/plain");
  2172. });
  2173. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2174. auto se = detail::scope_exit([&] {
  2175. svr.stop();
  2176. thread.join();
  2177. ASSERT_FALSE(svr.is_running());
  2178. });
  2179. svr.wait_until_ready();
  2180. {
  2181. Client cli("127.0.0.1", PORT);
  2182. auto res = cli.Get("/1");
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::OK_200, res->status);
  2185. EXPECT_EQ("Hello World!", res->body);
  2186. }
  2187. {
  2188. Client cli("::1", PORT);
  2189. auto res = cli.Get("/1");
  2190. ASSERT_TRUE(res);
  2191. EXPECT_EQ(StatusCode::OK_200, res->status);
  2192. EXPECT_EQ("Hello World!", res->body);
  2193. }
  2194. }
  2195. TEST(BindServerTest, BindAndListenSeparately) {
  2196. Server svr;
  2197. int port = svr.bind_to_any_port("0.0.0.0");
  2198. ASSERT_TRUE(svr.is_valid());
  2199. ASSERT_TRUE(port > 0);
  2200. svr.stop();
  2201. }
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2205. CLIENT_CA_CERT_DIR);
  2206. int port = svr.bind_to_any_port("0.0.0.0");
  2207. ASSERT_TRUE(svr.is_valid());
  2208. ASSERT_TRUE(port > 0);
  2209. svr.stop();
  2210. }
  2211. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2212. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2213. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2214. int port = svr.bind_to_any_port("0.0.0.0");
  2215. ASSERT_TRUE(svr.is_valid());
  2216. ASSERT_TRUE(port > 0);
  2217. svr.stop();
  2218. }
  2219. TEST(BindServerTest, UpdateCertsPem) {
  2220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2221. int port = svr.bind_to_any_port("0.0.0.0");
  2222. ASSERT_TRUE(svr.is_valid());
  2223. ASSERT_TRUE(port > 0);
  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 using PEM API
  2230. ASSERT_TRUE(
  2231. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2232. ASSERT_TRUE(svr.is_valid());
  2233. svr.stop();
  2234. }
  2235. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2236. // Start server with client CA (enables client auth)
  2237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2238. ASSERT_TRUE(svr.is_valid());
  2239. bool handler_called = false;
  2240. svr.Get("/test", [&](const Request &req, Response &res) {
  2241. handler_called = true;
  2242. // Verify client certificate is present
  2243. auto cert = req.peer_cert();
  2244. EXPECT_TRUE(static_cast<bool>(cert));
  2245. res.set_content("ok", "text/plain");
  2246. });
  2247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2248. auto se = detail::scope_exit([&] {
  2249. svr.stop();
  2250. t.join();
  2251. ASSERT_FALSE(svr.is_running());
  2252. });
  2253. svr.wait_until_ready();
  2254. // Read PEM files
  2255. std::string cert_pem, key_pem, ca_pem;
  2256. read_file(SERVER_CERT_FILE, cert_pem);
  2257. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2258. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2259. // Update server certificates and client CA using PEM API while server running
  2260. ASSERT_TRUE(
  2261. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2262. // Connect with client certificate
  2263. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2264. cli.enable_server_certificate_verification(false);
  2265. cli.set_connection_timeout(30);
  2266. auto res = cli.Get("/test");
  2267. ASSERT_TRUE(res);
  2268. ASSERT_EQ(StatusCode::OK_200, res->status);
  2269. ASSERT_TRUE(handler_called);
  2270. EXPECT_EQ("ok", res->body);
  2271. }
  2272. #endif
  2273. TEST(ErrorHandlerTest, ContentLength) {
  2274. Server svr;
  2275. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2276. res.status = StatusCode::OK_200;
  2277. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2278. "text/html"); // <= Content-Length still 13
  2279. });
  2280. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2281. res.set_content("Hello World!\n", "text/plain");
  2282. res.status = 524;
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. {
  2292. Client cli(HOST, PORT);
  2293. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2294. ASSERT_TRUE(res);
  2295. EXPECT_EQ(StatusCode::OK_200, res->status);
  2296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2298. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2299. }
  2300. }
  2301. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2302. TEST(ExceptionTest, WithoutExceptionHandler) {
  2303. Server svr;
  2304. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2305. throw std::runtime_error("exception...");
  2306. });
  2307. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2308. throw std::runtime_error("exception\r\n...");
  2309. });
  2310. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2311. auto se = detail::scope_exit([&] {
  2312. svr.stop();
  2313. listen_thread.join();
  2314. ASSERT_FALSE(svr.is_running());
  2315. });
  2316. svr.wait_until_ready();
  2317. Client cli("localhost", PORT);
  2318. {
  2319. auto res = cli.Get("/exception");
  2320. ASSERT_TRUE(res);
  2321. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2322. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2323. }
  2324. {
  2325. auto res = cli.Get("/unknown");
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2328. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2329. }
  2330. }
  2331. TEST(ExceptionTest, WithExceptionHandler) {
  2332. Server svr;
  2333. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2334. std::exception_ptr ep) {
  2335. EXPECT_FALSE(ep == nullptr);
  2336. try {
  2337. std::rethrow_exception(ep);
  2338. } catch (std::exception &e) {
  2339. EXPECT_EQ("abc", std::string(e.what()));
  2340. } catch (...) {}
  2341. res.status = StatusCode::InternalServerError_500;
  2342. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2343. "text/html"); // <= Content-Length still 13 at this point
  2344. });
  2345. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2346. res.set_content("Hello World!\n", "text/plain");
  2347. throw std::runtime_error("abc");
  2348. });
  2349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2350. auto se = detail::scope_exit([&] {
  2351. svr.stop();
  2352. thread.join();
  2353. ASSERT_FALSE(svr.is_running());
  2354. });
  2355. svr.wait_until_ready();
  2356. for (size_t i = 0; i < 10; i++) {
  2357. Client cli(HOST, PORT);
  2358. for (size_t j = 0; j < 100; j++) {
  2359. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2363. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2364. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2365. }
  2366. cli.set_keep_alive(true);
  2367. for (size_t j = 0; j < 100; j++) {
  2368. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2371. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2372. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2373. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2374. }
  2375. }
  2376. }
  2377. TEST(ExceptionTest, AndErrorHandler) {
  2378. Server svr;
  2379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2380. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2381. });
  2382. svr.set_exception_handler(
  2383. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2384. EXPECT_FALSE(ep == nullptr);
  2385. try {
  2386. std::rethrow_exception(ep);
  2387. } catch (std::exception &e) {
  2388. res.set_content(e.what(), "text/html");
  2389. } catch (...) {}
  2390. res.status = StatusCode::InternalServerError_500;
  2391. });
  2392. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2393. throw std::runtime_error("EXCEPTION");
  2394. });
  2395. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2396. res.set_content("ERROR", "text/html");
  2397. res.status = StatusCode::InternalServerError_500;
  2398. });
  2399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2400. auto se = detail::scope_exit([&] {
  2401. svr.stop();
  2402. thread.join();
  2403. ASSERT_FALSE(svr.is_running());
  2404. });
  2405. svr.wait_until_ready();
  2406. Client cli(HOST, PORT);
  2407. {
  2408. auto res = cli.Get("/exception");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2411. EXPECT_EQ("EXCEPTION", res->body);
  2412. }
  2413. {
  2414. auto res = cli.Get("/error");
  2415. ASSERT_TRUE(res);
  2416. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2417. EXPECT_EQ("ERROR", res->body);
  2418. }
  2419. {
  2420. auto res = cli.Get("/invalid");
  2421. ASSERT_TRUE(res);
  2422. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2423. EXPECT_EQ("NOT_FOUND", res->body);
  2424. }
  2425. }
  2426. #endif
  2427. TEST(NoContentTest, ContentLength) {
  2428. Server svr;
  2429. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2430. res.status = StatusCode::NoContent_204;
  2431. });
  2432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2433. auto se = detail::scope_exit([&] {
  2434. svr.stop();
  2435. thread.join();
  2436. ASSERT_FALSE(svr.is_running());
  2437. });
  2438. svr.wait_until_ready();
  2439. {
  2440. Client cli(HOST, PORT);
  2441. auto res = cli.Get("/hi");
  2442. ASSERT_TRUE(res);
  2443. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2444. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2445. }
  2446. }
  2447. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2448. #ifdef CPPHTTPLIB_SSL_ENABLED
  2449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2450. ASSERT_TRUE(svr.is_valid());
  2451. #else
  2452. Server svr;
  2453. #endif
  2454. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2455. if (req.path == "/routing_handler") {
  2456. res.set_header("PRE_ROUTING", "on");
  2457. res.set_content("Routing Handler", "text/plain");
  2458. return httplib::Server::HandlerResponse::Handled;
  2459. }
  2460. return httplib::Server::HandlerResponse::Unhandled;
  2461. });
  2462. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2463. res.set_content("Error", "text/html");
  2464. });
  2465. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2466. if (req.path == "/routing_handler") {
  2467. res.set_header("POST_ROUTING", "on");
  2468. }
  2469. });
  2470. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!\n", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  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("/routing_handler");
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(StatusCode::OK_200, res->status);
  2490. EXPECT_EQ("Routing Handler", res->body);
  2491. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2492. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2493. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2494. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2495. }
  2496. {
  2497. #ifdef CPPHTTPLIB_SSL_ENABLED
  2498. SSLClient cli(HOST, PORT);
  2499. cli.enable_server_certificate_verification(false);
  2500. #else
  2501. Client cli(HOST, PORT);
  2502. #endif
  2503. auto res = cli.Get("/hi");
  2504. ASSERT_TRUE(res);
  2505. EXPECT_EQ(StatusCode::OK_200, res->status);
  2506. EXPECT_EQ("Hello World!\n", res->body);
  2507. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2508. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2509. }
  2510. {
  2511. #ifdef CPPHTTPLIB_SSL_ENABLED
  2512. SSLClient cli(HOST, PORT);
  2513. cli.enable_server_certificate_verification(false);
  2514. #else
  2515. Client cli(HOST, PORT);
  2516. #endif
  2517. auto res = cli.Get("/aaa");
  2518. ASSERT_TRUE(res);
  2519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2520. EXPECT_EQ("Error", res->body);
  2521. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2522. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2523. }
  2524. }
  2525. TEST(RequestHandlerTest, PreRequestHandler) {
  2526. auto route_path = "/user/:user";
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request &, Response &res) {
  2529. res.set_content("hi", "text/plain");
  2530. });
  2531. svr.Get(route_path, [](const Request &req, Response &res) {
  2532. res.set_content(req.path_params.at("user"), "text/plain");
  2533. });
  2534. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2535. if (req.matched_route == route_path) {
  2536. auto user = req.path_params.at("user");
  2537. if (user != "john") {
  2538. res.status = StatusCode::Forbidden_403;
  2539. res.set_content("error", "text/html");
  2540. return Server::HandlerResponse::Handled;
  2541. }
  2542. }
  2543. return Server::HandlerResponse::Unhandled;
  2544. });
  2545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2546. auto se = detail::scope_exit([&] {
  2547. svr.stop();
  2548. thread.join();
  2549. ASSERT_FALSE(svr.is_running());
  2550. });
  2551. svr.wait_until_ready();
  2552. Client cli(HOST, PORT);
  2553. {
  2554. auto res = cli.Get("/hi");
  2555. ASSERT_TRUE(res);
  2556. EXPECT_EQ(StatusCode::OK_200, res->status);
  2557. EXPECT_EQ("hi", res->body);
  2558. }
  2559. {
  2560. auto res = cli.Get("/user/john");
  2561. ASSERT_TRUE(res);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. EXPECT_EQ("john", res->body);
  2564. }
  2565. {
  2566. auto res = cli.Get("/user/invalid-user");
  2567. ASSERT_TRUE(res);
  2568. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2569. EXPECT_EQ("error", res->body);
  2570. }
  2571. }
  2572. TEST(AnyTest, BasicOperations) {
  2573. // Default construction
  2574. httplib::any a;
  2575. EXPECT_FALSE(a.has_value());
  2576. // Value construction and any_cast (pointer form, noexcept)
  2577. httplib::any b(42);
  2578. EXPECT_TRUE(b.has_value());
  2579. auto *p = httplib::any_cast<int>(&b);
  2580. ASSERT_NE(nullptr, p);
  2581. EXPECT_EQ(42, *p);
  2582. // Type mismatch → nullptr
  2583. auto *q = httplib::any_cast<std::string>(&b);
  2584. EXPECT_EQ(nullptr, q);
  2585. // any_cast (value form) succeeds
  2586. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2587. // any_cast (value form) throws on type mismatch
  2588. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2589. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2590. #endif
  2591. // Copy
  2592. httplib::any c = b;
  2593. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2594. // Move
  2595. httplib::any d = std::move(c);
  2596. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2597. // Assignment with different type
  2598. b = std::string("hello");
  2599. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2600. // Reset
  2601. b.reset();
  2602. EXPECT_FALSE(b.has_value());
  2603. }
  2604. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2605. struct AuthCtx {
  2606. std::string user_id;
  2607. };
  2608. Server svr;
  2609. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2610. res.user_data["auth"] = AuthCtx{"alice"};
  2611. return Server::HandlerResponse::Unhandled;
  2612. });
  2613. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2614. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2615. ASSERT_NE(nullptr, ctx);
  2616. res.set_content("Hello " + ctx->user_id, "text/plain");
  2617. });
  2618. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2619. auto se = detail::scope_exit([&] {
  2620. svr.stop();
  2621. thread.join();
  2622. ASSERT_FALSE(svr.is_running());
  2623. });
  2624. svr.wait_until_ready();
  2625. Client cli(HOST, PORT);
  2626. auto res = cli.Get("/me");
  2627. ASSERT_TRUE(res);
  2628. EXPECT_EQ(StatusCode::OK_200, res->status);
  2629. EXPECT_EQ("Hello alice", res->body);
  2630. }
  2631. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2632. struct RoleCtx {
  2633. std::string role;
  2634. };
  2635. Server svr;
  2636. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2637. res.user_data["role"] = RoleCtx{"admin"};
  2638. return Server::HandlerResponse::Unhandled;
  2639. });
  2640. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2641. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2642. ASSERT_NE(nullptr, ctx);
  2643. res.set_content(ctx->role, "text/plain");
  2644. });
  2645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2646. auto se = detail::scope_exit([&] {
  2647. svr.stop();
  2648. thread.join();
  2649. ASSERT_FALSE(svr.is_running());
  2650. });
  2651. svr.wait_until_ready();
  2652. Client cli(HOST, PORT);
  2653. auto res = cli.Get("/role");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("admin", res->body);
  2657. }
  2658. TEST(InvalidFormatTest, StatusCode) {
  2659. Server svr;
  2660. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2661. res.set_content("Hello World!\n", "text/plain");
  2662. res.status = 9999; // Status should be a three-digit code...
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. {
  2672. Client cli(HOST, PORT);
  2673. auto res = cli.Get("/hi");
  2674. ASSERT_FALSE(res);
  2675. }
  2676. }
  2677. TEST(URLFragmentTest, WithFragment) {
  2678. Server svr;
  2679. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2680. EXPECT_TRUE(req.target == "/hi");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. {
  2690. Client cli(HOST, PORT);
  2691. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2692. EXPECT_TRUE(res);
  2693. EXPECT_EQ(StatusCode::OK_200, res->status);
  2694. res = cli.Get("/hi%23key1=val1=key2=val2");
  2695. EXPECT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2697. }
  2698. }
  2699. TEST(HeaderWriter, SetHeaderWriter) {
  2700. Server svr;
  2701. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2702. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2703. return detail::write_headers(strm, hdrs);
  2704. });
  2705. svr.Get("/hi", [](const Request &req, Response &res) {
  2706. auto it = req.headers.find("CustomClientHeader");
  2707. EXPECT_TRUE(it != req.headers.end());
  2708. EXPECT_EQ(it->second, "CustomClientValue");
  2709. res.set_content("Hello World!\n", "text/plain");
  2710. });
  2711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2712. auto se = detail::scope_exit([&] {
  2713. svr.stop();
  2714. thread.join();
  2715. ASSERT_FALSE(svr.is_running());
  2716. });
  2717. svr.wait_until_ready();
  2718. {
  2719. Client cli(HOST, PORT);
  2720. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2721. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2722. return detail::write_headers(strm, hdrs);
  2723. });
  2724. auto res = cli.Get("/hi");
  2725. EXPECT_TRUE(res);
  2726. EXPECT_EQ(StatusCode::OK_200, res->status);
  2727. auto it = res->headers.find("CustomServerHeader");
  2728. EXPECT_TRUE(it != res->headers.end());
  2729. EXPECT_EQ(it->second, "CustomServerValue");
  2730. }
  2731. }
  2732. class ServerTest : public ::testing::Test {
  2733. protected:
  2734. ServerTest()
  2735. : cli_(HOST, PORT)
  2736. #ifdef CPPHTTPLIB_SSL_ENABLED
  2737. ,
  2738. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2739. #endif
  2740. {
  2741. #ifdef CPPHTTPLIB_SSL_ENABLED
  2742. cli_.enable_server_certificate_verification(false);
  2743. #endif
  2744. // Allow LARGE_DATA (100MB) responses
  2745. cli_.set_payload_max_length(200 * 1024 * 1024);
  2746. }
  2747. virtual void SetUp() {
  2748. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2749. svr_.set_payload_max_length(200 * 1024 * 1024);
  2750. svr_.set_mount_point("/", "./www");
  2751. svr_.set_mount_point("/mount", "./www2");
  2752. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2753. svr_.Get("/hi",
  2754. [&](const Request & /*req*/, Response &res) {
  2755. res.set_content("Hello World!", "text/plain");
  2756. })
  2757. .Get("/file_content",
  2758. [&](const Request & /*req*/, Response &res) {
  2759. res.set_file_content("./www/dir/test.html");
  2760. })
  2761. .Get("/file_content_with_content_type",
  2762. [&](const Request & /*req*/, Response &res) {
  2763. res.set_file_content("./www/file", "text/plain");
  2764. })
  2765. .Get("/invalid_file_content",
  2766. [&](const Request & /*req*/, Response &res) {
  2767. res.set_file_content("./www/dir/invalid_file_path");
  2768. })
  2769. .Get("/http_response_splitting",
  2770. [&](const Request & /*req*/, Response &res) {
  2771. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2772. EXPECT_EQ(0U, res.headers.size());
  2773. EXPECT_FALSE(res.has_header("a"));
  2774. res.set_header("a", "1\nSet-Cookie: a=1");
  2775. EXPECT_EQ(0U, res.headers.size());
  2776. EXPECT_FALSE(res.has_header("a"));
  2777. res.set_header("a", "1\rSet-Cookie: a=1");
  2778. EXPECT_EQ(0U, res.headers.size());
  2779. EXPECT_FALSE(res.has_header("a"));
  2780. res.set_header("a\r\nb", "0");
  2781. EXPECT_EQ(0U, res.headers.size());
  2782. EXPECT_FALSE(res.has_header("a"));
  2783. res.set_header("a\rb", "0");
  2784. EXPECT_EQ(0U, res.headers.size());
  2785. EXPECT_FALSE(res.has_header("a"));
  2786. res.set_header("a\nb", "0");
  2787. EXPECT_EQ(0U, res.headers.size());
  2788. EXPECT_FALSE(res.has_header("a"));
  2789. res.set_redirect("1\r\nSet-Cookie: a=1");
  2790. EXPECT_EQ(0U, res.headers.size());
  2791. EXPECT_FALSE(res.has_header("Location"));
  2792. })
  2793. .Get("/slow",
  2794. [&](const Request & /*req*/, Response &res) {
  2795. std::this_thread::sleep_for(std::chrono::seconds(2));
  2796. res.set_content("slow", "text/plain");
  2797. })
  2798. #if 0
  2799. .Post("/slowpost",
  2800. [&](const Request & /*req*/, Response &res) {
  2801. std::this_thread::sleep_for(std::chrono::seconds(2));
  2802. res.set_content("slow", "text/plain");
  2803. })
  2804. #endif
  2805. .Get("/remote_addr",
  2806. [&](const Request &req, Response &res) {
  2807. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2808. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2809. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2810. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2811. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2812. #endif
  2813. res.set_content(req.remote_addr, "text/plain");
  2814. })
  2815. .Get("/local_addr",
  2816. [&](const Request &req, Response &res) {
  2817. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2818. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2819. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2820. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2821. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2822. #endif
  2823. auto local_addr = req.local_addr;
  2824. auto local_port = std::to_string(req.local_port);
  2825. res.set_content(local_addr.append(":").append(local_port),
  2826. "text/plain");
  2827. })
  2828. .Get("/endwith%",
  2829. [&](const Request & /*req*/, Response &res) {
  2830. res.set_content("Hello World!", "text/plain");
  2831. })
  2832. .Get("/a\\+\\+b",
  2833. [&](const Request &req, Response &res) {
  2834. ASSERT_TRUE(req.has_param("a +b"));
  2835. auto val = req.get_param_value("a +b");
  2836. res.set_content(val, "text/plain");
  2837. })
  2838. .Get("/", [&](const Request & /*req*/,
  2839. Response &res) { res.set_redirect("/hi"); })
  2840. .Post("/1",
  2841. [](const Request & /*req*/, Response &res) {
  2842. res.set_redirect("/2", StatusCode::SeeOther_303);
  2843. })
  2844. .Get("/2",
  2845. [](const Request & /*req*/, Response &res) {
  2846. res.set_content("redirected.", "text/plain");
  2847. res.status = StatusCode::OK_200;
  2848. })
  2849. .Post("/person",
  2850. [&](const Request &req, Response &res) {
  2851. if (req.has_param("name") && req.has_param("note")) {
  2852. persons_[req.get_param_value("name")] =
  2853. req.get_param_value("note");
  2854. } else {
  2855. res.status = StatusCode::BadRequest_400;
  2856. }
  2857. })
  2858. .Put("/person",
  2859. [&](const Request &req, Response &res) {
  2860. if (req.has_param("name") && req.has_param("note")) {
  2861. persons_[req.get_param_value("name")] =
  2862. req.get_param_value("note");
  2863. } else {
  2864. res.status = StatusCode::BadRequest_400;
  2865. }
  2866. })
  2867. .Get("/person/(.*)",
  2868. [&](const Request &req, Response &res) {
  2869. string name = req.matches[1];
  2870. if (persons_.find(name) != persons_.end()) {
  2871. auto note = persons_[name];
  2872. res.set_content(note, "text/plain");
  2873. } else {
  2874. res.status = StatusCode::NotFound_404;
  2875. }
  2876. })
  2877. .Delete("/person",
  2878. [&](const Request &req, Response &res) {
  2879. if (req.has_param("name")) {
  2880. string name = req.get_param_value("name");
  2881. if (persons_.find(name) != persons_.end()) {
  2882. persons_.erase(name);
  2883. res.set_content("DELETED", "text/plain");
  2884. } else {
  2885. res.status = StatusCode::NotFound_404;
  2886. }
  2887. } else {
  2888. res.status = StatusCode::BadRequest_400;
  2889. }
  2890. })
  2891. .Post("/x-www-form-urlencoded-json",
  2892. [&](const Request &req, Response &res) {
  2893. auto json = req.get_param_value("json");
  2894. ASSERT_EQ(JSON_DATA, json);
  2895. res.set_content(json, "appliation/json");
  2896. res.status = StatusCode::OK_200;
  2897. })
  2898. .Get("/streamed-chunked",
  2899. [&](const Request & /*req*/, Response &res) {
  2900. res.set_chunked_content_provider(
  2901. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2902. sink.os << "123";
  2903. sink.os << "456";
  2904. sink.os << "789";
  2905. sink.done();
  2906. return true;
  2907. });
  2908. })
  2909. .Get("/streamed-chunked-with-prohibited-trailer",
  2910. [&](const Request & /*req*/, Response &res) {
  2911. auto i = new int(0);
  2912. // Declare both a prohibited trailer (Content-Length) and an
  2913. // allowed one
  2914. res.set_header("Trailer", "Content-Length, X-Allowed");
  2915. res.set_chunked_content_provider(
  2916. "text/plain",
  2917. [i](size_t /*offset*/, DataSink &sink) {
  2918. switch (*i) {
  2919. case 0: sink.os << "123"; break;
  2920. case 1: sink.os << "456"; break;
  2921. case 2: sink.os << "789"; break;
  2922. case 3: {
  2923. sink.done_with_trailer(
  2924. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2925. } break;
  2926. }
  2927. (*i)++;
  2928. return true;
  2929. },
  2930. [i](bool success) {
  2931. EXPECT_TRUE(success);
  2932. delete i;
  2933. });
  2934. })
  2935. .Get("/streamed-chunked2",
  2936. [&](const Request & /*req*/, Response &res) {
  2937. auto i = new int(0);
  2938. res.set_chunked_content_provider(
  2939. "text/plain",
  2940. [i](size_t /*offset*/, DataSink &sink) {
  2941. switch (*i) {
  2942. case 0: sink.os << "123"; break;
  2943. case 1: sink.os << "456"; break;
  2944. case 2: sink.os << "789"; break;
  2945. case 3: sink.done(); break;
  2946. }
  2947. (*i)++;
  2948. return true;
  2949. },
  2950. [i](bool success) {
  2951. EXPECT_TRUE(success);
  2952. delete i;
  2953. });
  2954. })
  2955. .Get("/streamed-chunked-with-trailer",
  2956. [&](const Request & /*req*/, Response &res) {
  2957. auto i = new int(0);
  2958. res.set_header("Trailer", "Dummy1, Dummy2");
  2959. res.set_chunked_content_provider(
  2960. "text/plain",
  2961. [i](size_t /*offset*/, DataSink &sink) {
  2962. switch (*i) {
  2963. case 0: sink.os << "123"; break;
  2964. case 1: sink.os << "456"; break;
  2965. case 2: sink.os << "789"; break;
  2966. case 3: {
  2967. sink.done_with_trailer(
  2968. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2969. } break;
  2970. }
  2971. (*i)++;
  2972. return true;
  2973. },
  2974. [i](bool success) {
  2975. EXPECT_TRUE(success);
  2976. delete i;
  2977. });
  2978. })
  2979. .Get("/streamed",
  2980. [&](const Request & /*req*/, Response &res) {
  2981. res.set_content_provider(
  2982. 6, "text/plain",
  2983. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2984. sink.os << (offset < 3 ? "a" : "b");
  2985. return true;
  2986. });
  2987. })
  2988. .Get("/streamed-with-range",
  2989. [&](const Request &req, Response &res) {
  2990. auto data = new std::string("abcdefg");
  2991. res.set_content_provider(
  2992. data->size(), "text/plain",
  2993. [data](size_t offset, size_t length, DataSink &sink) {
  2994. size_t DATA_CHUNK_SIZE = 4;
  2995. const auto &d = *data;
  2996. auto out_len =
  2997. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2998. auto ret =
  2999. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3000. EXPECT_TRUE(ret);
  3001. return true;
  3002. },
  3003. [data, &req](bool success) {
  3004. EXPECT_EQ(success, !req.has_param("error"));
  3005. delete data;
  3006. });
  3007. })
  3008. .Get("/streamed-cancel",
  3009. [&](const Request & /*req*/, Response &res) {
  3010. res.set_content_provider(
  3011. size_t(-1), "text/plain",
  3012. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3013. sink.os << "data_chunk";
  3014. return true;
  3015. });
  3016. })
  3017. .Get("/regex-with-delimiter",
  3018. [&](const Request &req, Response & /*res*/) {
  3019. ASSERT_TRUE(req.has_param("key"));
  3020. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3021. })
  3022. .Get("/with-range",
  3023. [&](const Request & /*req*/, Response &res) {
  3024. res.set_content("abcdefg", "text/plain");
  3025. })
  3026. .Get("/test-start-time",
  3027. [&](const Request &req, Response & /*res*/) {
  3028. EXPECT_NE(req.start_time_,
  3029. std::chrono::steady_clock::time_point::min());
  3030. })
  3031. .Get("/with-range-customized-response",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. res.status = StatusCode::BadRequest_400;
  3034. res.set_content(JSON_DATA, "application/json");
  3035. })
  3036. .Post("/chunked",
  3037. [&](const Request &req, Response & /*res*/) {
  3038. EXPECT_EQ(req.body, "dechunked post body");
  3039. })
  3040. .Post("/large-chunked",
  3041. [&](const Request &req, Response & /*res*/) {
  3042. std::string expected(6 * 30 * 1024u, 'a');
  3043. EXPECT_EQ(req.body, expected);
  3044. })
  3045. .Post("/multipart",
  3046. [&](const Request &req, Response & /*res*/) {
  3047. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3048. req.form.get_field_count("text2") +
  3049. req.form.get_field_count("file3") +
  3050. req.form.get_field_count("file4"));
  3051. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3052. req.form.get_file_count("file2"));
  3053. ASSERT_TRUE(!req.form.has_file("???"));
  3054. ASSERT_TRUE(!req.form.has_field("???"));
  3055. ASSERT_TRUE(req.body.empty());
  3056. {
  3057. const auto &text = req.form.get_field("text1");
  3058. EXPECT_EQ("text default", text);
  3059. }
  3060. {
  3061. const auto &text = req.form.get_field("text2");
  3062. EXPECT_EQ("aωb", text);
  3063. }
  3064. {
  3065. const auto &file = req.form.get_file("file1");
  3066. EXPECT_EQ("hello.txt", file.filename);
  3067. EXPECT_EQ("text/plain", file.content_type);
  3068. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3069. }
  3070. {
  3071. const auto &file = req.form.get_file("file2");
  3072. EXPECT_EQ("world.json", file.filename);
  3073. EXPECT_EQ("application/json", file.content_type);
  3074. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3075. }
  3076. {
  3077. const auto &text = req.form.get_field("file3");
  3078. EXPECT_EQ(0u, text.size());
  3079. }
  3080. {
  3081. const auto &text = req.form.get_field("file4");
  3082. EXPECT_EQ(0u, text.size());
  3083. }
  3084. })
  3085. .Post("/multipart/multi_file_values",
  3086. [&](const Request &req, Response & /*res*/) {
  3087. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3088. req.form.get_field_count("multi_text1"));
  3089. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3090. ASSERT_TRUE(!req.form.has_file("???"));
  3091. ASSERT_TRUE(!req.form.has_field("???"));
  3092. ASSERT_TRUE(req.body.empty());
  3093. {
  3094. const auto &text = req.form.get_field("text");
  3095. EXPECT_EQ("default text", text);
  3096. }
  3097. {
  3098. const auto &text1_values = req.form.get_fields("multi_text1");
  3099. EXPECT_EQ(2u, text1_values.size());
  3100. EXPECT_EQ("aaaaa", text1_values[0]);
  3101. EXPECT_EQ("bbbbb", text1_values[1]);
  3102. }
  3103. {
  3104. const auto &file1_values = req.form.get_files("multi_file1");
  3105. EXPECT_EQ(2u, file1_values.size());
  3106. auto file1 = file1_values[0];
  3107. EXPECT_EQ(file1.filename, "hello.txt");
  3108. EXPECT_EQ(file1.content_type, "text/plain");
  3109. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3110. auto file2 = file1_values[1];
  3111. EXPECT_EQ(file2.filename, "world.json");
  3112. EXPECT_EQ(file2.content_type, "application/json");
  3113. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3114. }
  3115. })
  3116. .Post("/empty",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(req.body, "");
  3119. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3120. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3121. res.set_content("empty", "text/plain");
  3122. })
  3123. .Post("/empty-no-content-type",
  3124. [&](const Request &req, Response &res) {
  3125. EXPECT_EQ(req.body, "");
  3126. EXPECT_FALSE(req.has_header("Content-Type"));
  3127. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3128. res.set_content("empty-no-content-type", "text/plain");
  3129. })
  3130. .Post("/path-only",
  3131. [&](const Request &req, Response &res) {
  3132. EXPECT_EQ(req.body, "");
  3133. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3134. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3135. res.set_content("path-only", "text/plain");
  3136. })
  3137. .Post("/path-headers-only",
  3138. [&](const Request &req, Response &res) {
  3139. EXPECT_EQ(req.body, "");
  3140. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3141. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3142. EXPECT_EQ("world", req.get_header_value("hello"));
  3143. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3144. res.set_content("path-headers-only", "text/plain");
  3145. })
  3146. .Post("/post-large",
  3147. [&](const Request &req, Response &res) {
  3148. EXPECT_EQ(req.body, LARGE_DATA);
  3149. res.set_content(req.body, "text/plain");
  3150. })
  3151. .Post("/post-loopback",
  3152. [&](const Request &, Response &res,
  3153. ContentReader const &content_reader) {
  3154. std::string body;
  3155. content_reader([&](const char *data, size_t data_length) {
  3156. body.append(data, data_length);
  3157. return true;
  3158. });
  3159. res.set_content(body, "text/plain");
  3160. })
  3161. .Put("/put-loopback",
  3162. [&](const Request &, Response &res,
  3163. ContentReader const &content_reader) {
  3164. std::string body;
  3165. content_reader([&](const char *data, size_t data_length) {
  3166. body.append(data, data_length);
  3167. return true;
  3168. });
  3169. res.set_content(body, "text/plain");
  3170. })
  3171. .Patch("/patch-loopback",
  3172. [&](const Request &, Response &res,
  3173. ContentReader const &content_reader) {
  3174. std::string body;
  3175. content_reader([&](const char *data, size_t data_length) {
  3176. body.append(data, data_length);
  3177. return true;
  3178. });
  3179. res.set_content(body, "text/plain");
  3180. })
  3181. .Put("/empty-no-content-type",
  3182. [&](const Request &req, Response &res) {
  3183. EXPECT_EQ(req.body, "");
  3184. EXPECT_FALSE(req.has_header("Content-Type"));
  3185. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3186. res.set_content("empty-no-content-type", "text/plain");
  3187. })
  3188. .Put("/put",
  3189. [&](const Request &req, Response &res) {
  3190. EXPECT_EQ(req.body, "PUT");
  3191. res.set_content(req.body, "text/plain");
  3192. })
  3193. .Put("/put-large",
  3194. [&](const Request &req, Response &res) {
  3195. EXPECT_EQ(req.body, LARGE_DATA);
  3196. res.set_content(req.body, "text/plain");
  3197. })
  3198. .Patch("/patch",
  3199. [&](const Request &req, Response &res) {
  3200. EXPECT_EQ(req.body, "PATCH");
  3201. res.set_content(req.body, "text/plain");
  3202. })
  3203. .Delete("/delete",
  3204. [&](const Request & /*req*/, Response &res) {
  3205. res.set_content("DELETE", "text/plain");
  3206. })
  3207. .Delete("/delete-body",
  3208. [&](const Request &req, Response &res) {
  3209. EXPECT_EQ(req.body, "content");
  3210. res.set_content(req.body, "text/plain");
  3211. })
  3212. .Options(R"(\*)",
  3213. [&](const Request & /*req*/, Response &res) {
  3214. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3215. })
  3216. .Get("/request-target",
  3217. [&](const Request &req, Response & /*res*/) {
  3218. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3219. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3220. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3221. })
  3222. .Get("/long-query-value",
  3223. [&](const Request &req, Response & /*res*/) {
  3224. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3225. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3226. })
  3227. .Get("/too-long-query-value",
  3228. [&](const Request &req, Response & /*res*/) {
  3229. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3230. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3231. })
  3232. .Get("/array-param",
  3233. [&](const Request &req, Response & /*res*/) {
  3234. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3235. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3236. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3237. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3238. })
  3239. .Post("/validate-no-multiple-headers",
  3240. [&](const Request &req, Response & /*res*/) {
  3241. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3242. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3243. })
  3244. .Post("/content_receiver",
  3245. [&](const Request &req, Response &res,
  3246. const ContentReader &content_reader) {
  3247. if (req.is_multipart_form_data()) {
  3248. std::vector<FormData> items;
  3249. content_reader(
  3250. [&](const FormData &file) {
  3251. items.push_back(file);
  3252. return true;
  3253. },
  3254. [&](const char *data, size_t data_length) {
  3255. items.back().content.append(data, data_length);
  3256. return true;
  3257. });
  3258. EXPECT_EQ(5u, items.size());
  3259. {
  3260. const auto &file = get_file_value(items, "text1");
  3261. EXPECT_TRUE(file.filename.empty());
  3262. EXPECT_EQ("text default", file.content);
  3263. }
  3264. {
  3265. const auto &file = get_file_value(items, "text2");
  3266. EXPECT_TRUE(file.filename.empty());
  3267. EXPECT_EQ("aωb", file.content);
  3268. }
  3269. {
  3270. const auto &file = get_file_value(items, "file1");
  3271. EXPECT_EQ("hello.txt", file.filename);
  3272. EXPECT_EQ("text/plain", file.content_type);
  3273. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3274. }
  3275. {
  3276. const auto &file = get_file_value(items, "file2");
  3277. EXPECT_EQ("world.json", file.filename);
  3278. EXPECT_EQ("application/json", file.content_type);
  3279. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3280. }
  3281. {
  3282. const auto &file = get_file_value(items, "file3");
  3283. EXPECT_TRUE(file.filename.empty());
  3284. EXPECT_EQ("application/octet-stream", file.content_type);
  3285. EXPECT_EQ(0u, file.content.size());
  3286. }
  3287. } else {
  3288. std::string body;
  3289. content_reader([&](const char *data, size_t data_length) {
  3290. EXPECT_EQ(7U, data_length);
  3291. body.append(data, data_length);
  3292. return true;
  3293. });
  3294. EXPECT_EQ(body, "content");
  3295. res.set_content(body, "text/plain");
  3296. }
  3297. })
  3298. .Put("/content_receiver",
  3299. [&](const Request & /*req*/, Response &res,
  3300. const ContentReader &content_reader) {
  3301. std::string body;
  3302. content_reader([&](const char *data, size_t data_length) {
  3303. body.append(data, data_length);
  3304. return true;
  3305. });
  3306. EXPECT_EQ(body, "content");
  3307. res.set_content(body, "text/plain");
  3308. })
  3309. .Patch("/content_receiver",
  3310. [&](const Request & /*req*/, Response &res,
  3311. const ContentReader &content_reader) {
  3312. std::string body;
  3313. content_reader([&](const char *data, size_t data_length) {
  3314. body.append(data, data_length);
  3315. return true;
  3316. });
  3317. EXPECT_EQ(body, "content");
  3318. res.set_content(body, "text/plain");
  3319. })
  3320. .Post("/query-string-and-body",
  3321. [&](const Request &req, Response & /*res*/) {
  3322. ASSERT_TRUE(req.has_param("key"));
  3323. EXPECT_EQ(req.get_param_value("key"), "value");
  3324. EXPECT_EQ(req.body, "content");
  3325. })
  3326. .Get("/last-request",
  3327. [&](const Request &req, Response & /*res*/) {
  3328. EXPECT_EQ("close", req.get_header_value("Connection"));
  3329. })
  3330. .Get(R"(/redirect/(\d+))",
  3331. [&](const Request &req, Response &res) {
  3332. auto num = std::stoi(req.matches[1]) + 1;
  3333. std::string url = "/redirect/" + std::to_string(num);
  3334. res.set_redirect(url);
  3335. })
  3336. .Post("/binary",
  3337. [&](const Request &req, Response &res) {
  3338. EXPECT_EQ(4U, req.body.size());
  3339. EXPECT_EQ("application/octet-stream",
  3340. req.get_header_value("Content-Type"));
  3341. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3342. res.set_content(req.body, "application/octet-stream");
  3343. })
  3344. .Put("/binary",
  3345. [&](const Request &req, Response &res) {
  3346. EXPECT_EQ(4U, req.body.size());
  3347. EXPECT_EQ("application/octet-stream",
  3348. req.get_header_value("Content-Type"));
  3349. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3350. res.set_content(req.body, "application/octet-stream");
  3351. })
  3352. .Patch("/binary",
  3353. [&](const Request &req, Response &res) {
  3354. EXPECT_EQ(4U, req.body.size());
  3355. EXPECT_EQ("application/octet-stream",
  3356. req.get_header_value("Content-Type"));
  3357. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3358. res.set_content(req.body, "application/octet-stream");
  3359. })
  3360. .Delete("/binary",
  3361. [&](const Request &req, Response &res) {
  3362. EXPECT_EQ(4U, req.body.size());
  3363. EXPECT_EQ("application/octet-stream",
  3364. req.get_header_value("Content-Type"));
  3365. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3366. res.set_content(req.body, "application/octet-stream");
  3367. })
  3368. .Get("/issue1772",
  3369. [&](const Request & /*req*/, Response &res) {
  3370. res.status = 401;
  3371. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3372. })
  3373. .Delete("/issue609",
  3374. [](const httplib::Request &, httplib::Response &res,
  3375. const httplib::ContentReader &) {
  3376. res.set_content("ok", "text/plain");
  3377. })
  3378. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3379. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3380. .Get("/compress",
  3381. [&](const Request & /*req*/, Response &res) {
  3382. res.set_content(
  3383. "12345678901234567890123456789012345678901234567890123456789"
  3384. "01234567890123456789012345678901234567890",
  3385. "text/plain");
  3386. })
  3387. .Get("/compress-with-charset",
  3388. [&](const Request & /*req*/, Response &res) {
  3389. res.set_content(
  3390. "12345678901234567890123456789012345678901234567890123456789"
  3391. "01234567890123456789012345678901234567890",
  3392. "application/json; charset=utf-8");
  3393. })
  3394. .Get("/nocompress",
  3395. [&](const Request & /*req*/, Response &res) {
  3396. res.set_content(
  3397. "12345678901234567890123456789012345678901234567890123456789"
  3398. "01234567890123456789012345678901234567890",
  3399. "application/octet-stream");
  3400. })
  3401. .Post("/compress-multipart",
  3402. [&](const Request &req, Response & /*res*/) {
  3403. EXPECT_EQ(2u, req.form.fields.size());
  3404. ASSERT_TRUE(!req.form.has_field("???"));
  3405. {
  3406. const auto &text = req.form.get_field("key1");
  3407. EXPECT_EQ("test", text);
  3408. }
  3409. {
  3410. const auto &text = req.form.get_field("key2");
  3411. EXPECT_EQ("--abcdefg123", text);
  3412. }
  3413. })
  3414. #endif
  3415. ;
  3416. persons_["john"] = "programmer";
  3417. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3418. svr_.wait_until_ready();
  3419. }
  3420. virtual void TearDown() {
  3421. svr_.stop();
  3422. if (!request_threads_.empty()) {
  3423. std::this_thread::sleep_for(std::chrono::seconds(1));
  3424. for (auto &t : request_threads_) {
  3425. t.join();
  3426. }
  3427. }
  3428. t_.join();
  3429. }
  3430. map<string, string> persons_;
  3431. #ifdef CPPHTTPLIB_SSL_ENABLED
  3432. SSLClient cli_;
  3433. SSLServer svr_;
  3434. #else
  3435. Client cli_;
  3436. Server svr_;
  3437. #endif
  3438. thread t_;
  3439. std::vector<thread> request_threads_;
  3440. };
  3441. TEST_F(ServerTest, GetMethod200) {
  3442. auto res = cli_.Get("/hi");
  3443. ASSERT_TRUE(res);
  3444. EXPECT_EQ("HTTP/1.1", res->version);
  3445. EXPECT_EQ(StatusCode::OK_200, res->status);
  3446. EXPECT_EQ("OK", res->reason);
  3447. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3448. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3449. EXPECT_EQ("Hello World!", res->body);
  3450. }
  3451. TEST_F(ServerTest, GetEmptyFile) {
  3452. auto res = cli_.Get("/empty_file");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3456. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3457. EXPECT_EQ("", res->body);
  3458. }
  3459. TEST_F(ServerTest, GetFileContent) {
  3460. auto res = cli_.Get("/file_content");
  3461. ASSERT_TRUE(res);
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3464. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3465. EXPECT_EQ("test.html", res->body);
  3466. }
  3467. TEST_F(ServerTest, GetFileContentWithRange) {
  3468. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3473. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3474. EXPECT_EQ("est", res->body);
  3475. }
  3476. TEST_F(ServerTest, GetFileContentWithContentType) {
  3477. auto res = cli_.Get("/file_content_with_content_type");
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::OK_200, res->status);
  3480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3481. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3482. EXPECT_EQ("file\n", res->body);
  3483. }
  3484. TEST_F(ServerTest, GetInvalidFileContent) {
  3485. auto res = cli_.Get("/invalid_file_content");
  3486. ASSERT_TRUE(res);
  3487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3488. }
  3489. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3490. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3491. ASSERT_TRUE(res);
  3492. EXPECT_EQ("HTTP/1.1", res->version);
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3495. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3496. EXPECT_EQ("Hello World!", res->body);
  3497. }
  3498. TEST_F(ServerTest, GetMethod302) {
  3499. auto res = cli_.Get("/");
  3500. ASSERT_TRUE(res);
  3501. EXPECT_EQ(StatusCode::Found_302, res->status);
  3502. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3503. }
  3504. TEST_F(ServerTest, GetMethod302Redirect) {
  3505. cli_.set_follow_location(true);
  3506. auto res = cli_.Get("/");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("Hello World!", res->body);
  3510. EXPECT_EQ("/hi", res->location);
  3511. }
  3512. TEST_F(ServerTest, GetMethod404) {
  3513. auto res = cli_.Get("/invalid");
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3516. }
  3517. TEST_F(ServerTest, HeadMethod200) {
  3518. auto res = cli_.Head("/hi");
  3519. ASSERT_TRUE(res);
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3522. EXPECT_TRUE(res->body.empty());
  3523. }
  3524. TEST_F(ServerTest, HeadMethod200Static) {
  3525. auto res = cli_.Head("/mount/dir/index.html");
  3526. ASSERT_TRUE(res);
  3527. EXPECT_EQ(StatusCode::OK_200, res->status);
  3528. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3529. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3530. EXPECT_TRUE(res->body.empty());
  3531. }
  3532. TEST_F(ServerTest, HeadMethod404) {
  3533. auto res = cli_.Head("/invalid");
  3534. ASSERT_TRUE(res);
  3535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3536. EXPECT_TRUE(res->body.empty());
  3537. }
  3538. TEST_F(ServerTest, GetMethodPersonJohn) {
  3539. auto res = cli_.Get("/person/john");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. EXPECT_EQ("programmer", res->body);
  3544. }
  3545. TEST_F(ServerTest, PostMethod1) {
  3546. auto res = cli_.Get("/person/john1");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3549. res = cli_.Post("/person", "name=john1&note=coder",
  3550. "application/x-www-form-urlencoded");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::OK_200, res->status);
  3553. res = cli_.Get("/person/john1");
  3554. ASSERT_TRUE(res);
  3555. ASSERT_EQ(StatusCode::OK_200, res->status);
  3556. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3557. ASSERT_EQ("coder", res->body);
  3558. }
  3559. TEST_F(ServerTest, PostMethod2) {
  3560. auto res = cli_.Get("/person/john2");
  3561. ASSERT_TRUE(res);
  3562. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3563. Params params;
  3564. params.emplace("name", "john2");
  3565. params.emplace("note", "coder");
  3566. res = cli_.Post("/person", params);
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::OK_200, res->status);
  3569. res = cli_.Get("/person/john2");
  3570. ASSERT_TRUE(res);
  3571. ASSERT_EQ(StatusCode::OK_200, res->status);
  3572. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3573. ASSERT_EQ("coder", res->body);
  3574. }
  3575. TEST_F(ServerTest, PutMethod3) {
  3576. auto res = cli_.Get("/person/john3");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3579. Params params;
  3580. params.emplace("name", "john3");
  3581. params.emplace("note", "coder");
  3582. res = cli_.Put("/person", params);
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. res = cli_.Get("/person/john3");
  3586. ASSERT_TRUE(res);
  3587. ASSERT_EQ(StatusCode::OK_200, res->status);
  3588. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3589. ASSERT_EQ("coder", res->body);
  3590. }
  3591. TEST_F(ServerTest, DeleteMethod1) {
  3592. auto res = cli_.Get("/person/john4");
  3593. ASSERT_TRUE(res);
  3594. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3595. Params params;
  3596. params.emplace("name", "john4");
  3597. params.emplace("note", "coder");
  3598. res = cli_.Post("/person", params);
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::OK_200, res->status);
  3601. res = cli_.Get("/person/john4");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3605. ASSERT_EQ("coder", res->body);
  3606. Params delete_params;
  3607. delete_params.emplace("name", "john4");
  3608. res = cli_.Delete("/person", delete_params);
  3609. ASSERT_TRUE(res);
  3610. ASSERT_EQ(StatusCode::OK_200, res->status);
  3611. ASSERT_EQ("DELETED", res->body);
  3612. res = cli_.Get("/person/john4");
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3615. }
  3616. TEST_F(ServerTest, DeleteMethod2) {
  3617. auto res = cli_.Get("/person/john5");
  3618. ASSERT_TRUE(res);
  3619. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3620. Params params;
  3621. params.emplace("name", "john5");
  3622. params.emplace("note", "developer");
  3623. res = cli_.Post("/person", params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. res = cli_.Get("/person/john5");
  3627. ASSERT_TRUE(res);
  3628. ASSERT_EQ(StatusCode::OK_200, res->status);
  3629. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3630. ASSERT_EQ("developer", res->body);
  3631. Params delete_params;
  3632. delete_params.emplace("name", "john5");
  3633. Headers headers;
  3634. headers.emplace("Custom-Header", "test-value");
  3635. res = cli_.Delete("/person", headers, delete_params);
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ("DELETED", res->body);
  3639. res = cli_.Get("/person/john5");
  3640. ASSERT_TRUE(res);
  3641. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3642. }
  3643. TEST_F(ServerTest, DeleteMethod3) {
  3644. auto res = cli_.Get("/person/john6");
  3645. ASSERT_TRUE(res);
  3646. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3647. Params params;
  3648. params.emplace("name", "john6");
  3649. params.emplace("note", "tester");
  3650. res = cli_.Post("/person", params);
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. res = cli_.Get("/person/john6");
  3654. ASSERT_TRUE(res);
  3655. ASSERT_EQ(StatusCode::OK_200, res->status);
  3656. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3657. ASSERT_EQ("tester", res->body);
  3658. Params delete_params;
  3659. delete_params.emplace("name", "john6");
  3660. Headers headers;
  3661. headers.emplace("Custom-Header", "test-value");
  3662. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3663. ASSERT_TRUE(res);
  3664. ASSERT_EQ(StatusCode::OK_200, res->status);
  3665. ASSERT_EQ("DELETED", res->body);
  3666. res = cli_.Get("/person/john6");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. }
  3670. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3671. Params params;
  3672. params.emplace("json", JSON_DATA);
  3673. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(StatusCode::OK_200, res->status);
  3676. ASSERT_EQ(JSON_DATA, res->body);
  3677. }
  3678. TEST_F(ServerTest, PostEmptyContent) {
  3679. auto res = cli_.Post("/empty", "", "text/plain");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ("empty", res->body);
  3683. }
  3684. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3685. auto res = cli_.Post("/empty-no-content-type");
  3686. ASSERT_TRUE(res);
  3687. ASSERT_EQ(StatusCode::OK_200, res->status);
  3688. ASSERT_EQ("empty-no-content-type", res->body);
  3689. }
  3690. TEST_F(ServerTest, PostPathOnly) {
  3691. auto res = cli_.Post("/path-only");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("path-only", res->body);
  3695. }
  3696. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3697. auto res = cli_.Post("/path-headers-only",
  3698. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::OK_200, res->status);
  3701. ASSERT_EQ("path-headers-only", res->body);
  3702. }
  3703. TEST_F(ServerTest, PostLarge) {
  3704. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ(LARGE_DATA, res->body);
  3708. }
  3709. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3710. auto res = cli_.Put("/empty-no-content-type");
  3711. ASSERT_TRUE(res);
  3712. ASSERT_EQ(StatusCode::OK_200, res->status);
  3713. ASSERT_EQ("empty-no-content-type", res->body);
  3714. }
  3715. TEST_F(ServerTest, GetMethodDir) {
  3716. auto res = cli_.Get("/dir/");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::OK_200, res->status);
  3719. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3720. auto body = R"(<html>
  3721. <head>
  3722. </head>
  3723. <body>
  3724. <a href="/dir/test.html">Test</a>
  3725. <a href="/hi">hi</a>
  3726. </body>
  3727. </html>
  3728. )";
  3729. EXPECT_EQ(body, res->body);
  3730. }
  3731. TEST_F(ServerTest, GetMethodDirTest) {
  3732. auto res = cli_.Get("/dir/test.html");
  3733. ASSERT_TRUE(res);
  3734. EXPECT_EQ(StatusCode::OK_200, res->status);
  3735. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3736. EXPECT_EQ("test.html", res->body);
  3737. }
  3738. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3739. auto res = cli_.Get("/dir/../dir/test.html");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3743. EXPECT_EQ("test.html", res->body);
  3744. }
  3745. TEST_F(ServerTest, GetMethodInvalidPath) {
  3746. auto res = cli_.Get("/dir/../test.html");
  3747. ASSERT_TRUE(res);
  3748. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3749. }
  3750. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3751. auto res = cli_.Get("/../www/dir/test.html");
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3754. }
  3755. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3756. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3759. }
  3760. TEST_F(ServerTest, GetMethodDirMountTest) {
  3761. auto res = cli_.Get("/mount/dir/test.html");
  3762. ASSERT_TRUE(res);
  3763. EXPECT_EQ(StatusCode::OK_200, res->status);
  3764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3765. EXPECT_EQ("test.html", res->body);
  3766. }
  3767. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3768. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::OK_200, res->status);
  3771. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3772. EXPECT_EQ("test.html", res->body);
  3773. }
  3774. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3775. auto res = cli_.Get("/mount/dir/../test.html");
  3776. ASSERT_TRUE(res);
  3777. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3778. }
  3779. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3780. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3781. ASSERT_TRUE(res);
  3782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3783. }
  3784. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3785. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3786. ASSERT_TRUE(res);
  3787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3788. }
  3789. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3790. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3791. ASSERT_TRUE(res);
  3792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3793. }
  3794. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3795. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3798. }
  3799. TEST_F(ServerTest, PostMethod303) {
  3800. auto res = cli_.Post("/1", "body", "text/plain");
  3801. ASSERT_TRUE(res);
  3802. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3803. EXPECT_EQ("/2", res->get_header_value("Location"));
  3804. }
  3805. TEST_F(ServerTest, PostMethod303Redirect) {
  3806. cli_.set_follow_location(true);
  3807. auto res = cli_.Post("/1", "body", "text/plain");
  3808. ASSERT_TRUE(res);
  3809. EXPECT_EQ(StatusCode::OK_200, res->status);
  3810. EXPECT_EQ("redirected.", res->body);
  3811. EXPECT_EQ("/2", res->location);
  3812. }
  3813. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3814. auto res = cli_.Get("/dir/test.abcde");
  3815. ASSERT_TRUE(res);
  3816. EXPECT_EQ(StatusCode::OK_200, res->status);
  3817. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3818. EXPECT_EQ("abcde", res->body);
  3819. }
  3820. TEST_F(ServerTest, StaticFileRange) {
  3821. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3824. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3825. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3826. EXPECT_EQ(true, res->has_header("Content-Range"));
  3827. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3828. EXPECT_EQ(std::string("cd"), res->body);
  3829. }
  3830. TEST_F(ServerTest, StaticFileRanges) {
  3831. auto res =
  3832. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3833. ASSERT_TRUE(res);
  3834. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3835. EXPECT_TRUE(
  3836. res->get_header_value("Content-Type")
  3837. .find(
  3838. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3839. 0);
  3840. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3841. }
  3842. TEST_F(ServerTest, StaticFileRangeHead) {
  3843. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3844. ASSERT_TRUE(res);
  3845. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3846. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3847. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3848. EXPECT_EQ(true, res->has_header("Content-Range"));
  3849. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3850. }
  3851. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3852. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3856. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3857. EXPECT_EQ(true, res->has_header("Content-Range"));
  3858. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3859. res->get_header_value("Content-Range"));
  3860. EXPECT_EQ("LAST\n", res->body);
  3861. }
  3862. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3863. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3867. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3868. EXPECT_EQ(true, res->has_header("Content-Range"));
  3869. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3870. }
  3871. TEST_F(ServerTest, StaticFileBigFile) {
  3872. auto res = cli_.Get("/dir/1MB.txt");
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::OK_200, res->status);
  3875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3876. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3877. }
  3878. TEST_F(ServerTest, InvalidBaseDirMount) {
  3879. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3880. }
  3881. TEST_F(ServerTest, Binary) {
  3882. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3883. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3884. "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_.Put("/binary", binary.data(), binary.size(),
  3889. "application/octet-stream");
  3890. ASSERT_TRUE(res);
  3891. ASSERT_EQ(StatusCode::OK_200, res->status);
  3892. ASSERT_EQ(4U, res->body.size());
  3893. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3894. "application/octet-stream");
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. ASSERT_EQ(4U, res->body.size());
  3898. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3899. "application/octet-stream");
  3900. ASSERT_TRUE(res);
  3901. ASSERT_EQ(StatusCode::OK_200, res->status);
  3902. ASSERT_EQ(4U, res->body.size());
  3903. }
  3904. TEST_F(ServerTest, BinaryString) {
  3905. auto binary = std::string("\x00\x01\x02\x03", 4);
  3906. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::OK_200, res->status);
  3909. ASSERT_EQ(4U, res->body.size());
  3910. res = cli_.Put("/binary", binary, "application/octet-stream");
  3911. ASSERT_TRUE(res);
  3912. ASSERT_EQ(StatusCode::OK_200, res->status);
  3913. ASSERT_EQ(4U, res->body.size());
  3914. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3915. ASSERT_TRUE(res);
  3916. ASSERT_EQ(StatusCode::OK_200, res->status);
  3917. ASSERT_EQ(4U, res->body.size());
  3918. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3919. ASSERT_TRUE(res);
  3920. ASSERT_EQ(StatusCode::OK_200, res->status);
  3921. ASSERT_EQ(4U, res->body.size());
  3922. }
  3923. TEST_F(ServerTest, EmptyRequest) {
  3924. auto res = cli_.Get("");
  3925. ASSERT_TRUE(!res);
  3926. EXPECT_EQ(Error::Connection, res.error());
  3927. }
  3928. TEST_F(ServerTest, LongRequest) {
  3929. std::string request;
  3930. for (size_t i = 0; i < 545; i++) {
  3931. request += "/TooLongRequest";
  3932. }
  3933. request += "OK";
  3934. auto res = cli_.Get(request.c_str());
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3937. }
  3938. TEST_F(ServerTest, TooLongRequest) {
  3939. std::string request;
  3940. for (size_t i = 0; i < 546; i++) {
  3941. request += "/TooLongRequest";
  3942. }
  3943. request += "_NG";
  3944. auto start = std::chrono::high_resolution_clock::now();
  3945. cli_.set_keep_alive(true);
  3946. auto res = cli_.Get(request.c_str());
  3947. auto end = std::chrono::high_resolution_clock::now();
  3948. auto elapsed =
  3949. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3950. .count();
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3953. EXPECT_LE(elapsed, 1000);
  3954. EXPECT_EQ("close", res->get_header_value("Connection"));
  3955. EXPECT_FALSE(cli_.is_socket_open());
  3956. }
  3957. TEST_F(ServerTest, AlmostTooLongRequest) {
  3958. // test for #2046 - URI length check shouldn't include other content on req
  3959. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3960. // leading /, space, HTTP/1.1)
  3961. std::string request =
  3962. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3963. auto res = cli_.Get(request.c_str());
  3964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3965. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3966. }
  3967. TEST_F(ServerTest, LongHeader) {
  3968. Request req;
  3969. req.method = "GET";
  3970. req.path = "/hi";
  3971. std::string host_and_port;
  3972. host_and_port += HOST;
  3973. host_and_port += ":";
  3974. host_and_port += std::to_string(PORT);
  3975. req.headers.emplace("Host", host_and_port.c_str());
  3976. req.headers.emplace("Accept", "*/*");
  3977. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3978. req.headers.emplace(
  3979. "Header-Name",
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@");
  4009. auto res = std::make_shared<Response>();
  4010. auto error = Error::Success;
  4011. auto ret = cli_.send(req, *res, error);
  4012. ASSERT_TRUE(ret);
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. }
  4015. TEST_F(ServerTest, LongQueryValue) {
  4016. auto start = std::chrono::high_resolution_clock::now();
  4017. cli_.set_keep_alive(true);
  4018. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4019. auto end = std::chrono::high_resolution_clock::now();
  4020. auto elapsed =
  4021. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4022. .count();
  4023. ASSERT_TRUE(res);
  4024. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4025. EXPECT_LE(elapsed, 1000);
  4026. EXPECT_EQ("close", res->get_header_value("Connection"));
  4027. EXPECT_FALSE(cli_.is_socket_open());
  4028. }
  4029. TEST_F(ServerTest, TooLongQueryValue) {
  4030. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4031. ASSERT_FALSE(res);
  4032. EXPECT_EQ(Error::Read, res.error());
  4033. }
  4034. TEST_F(ServerTest, TooLongHeader) {
  4035. Request req;
  4036. req.method = "GET";
  4037. req.path = "/hi";
  4038. std::string host_and_port;
  4039. host_and_port += HOST;
  4040. host_and_port += ":";
  4041. host_and_port += std::to_string(PORT);
  4042. req.headers.emplace("Host", host_and_port.c_str());
  4043. req.headers.emplace("Accept", "*/*");
  4044. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4045. req.headers.emplace(
  4046. "Header-Name",
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4075. "@@@@@@@@@@@@@@@@@");
  4076. auto res = std::make_shared<Response>();
  4077. auto error = Error::Success;
  4078. auto ret = cli_.send(req, *res, error);
  4079. ASSERT_TRUE(ret);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. }
  4082. TEST_F(ServerTest, HeaderCountAtLimit) {
  4083. // Test with headers just under the 100 limit
  4084. httplib::Headers headers;
  4085. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4086. // This should keep us just under the 100 header limit
  4087. for (int i = 0; i < 95; i++) {
  4088. std::string name = "X-Test-Header-" + std::to_string(i);
  4089. std::string value = "value" + std::to_string(i);
  4090. headers.emplace(name, value);
  4091. }
  4092. // This should work fine as we're under the limit
  4093. auto res = cli_.Get("/hi", headers);
  4094. EXPECT_TRUE(res);
  4095. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4096. }
  4097. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4098. // Test with many headers to exceed the 100 limit
  4099. httplib::Headers headers;
  4100. // Add 150 headers to definitely exceed the 100 limit
  4101. for (int i = 0; i < 150; i++) {
  4102. std::string name = "X-Test-Header-" + std::to_string(i);
  4103. std::string value = "value" + std::to_string(i);
  4104. headers.emplace(name, value);
  4105. }
  4106. // This should fail due to exceeding header count limit
  4107. cli_.set_keep_alive(true);
  4108. auto res = cli_.Get("/hi", headers);
  4109. // The server should respond with 400 Bad Request
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4112. EXPECT_EQ("close", res->get_header_value("Connection"));
  4113. EXPECT_FALSE(cli_.is_socket_open());
  4114. }
  4115. TEST_F(ServerTest, PercentEncoding) {
  4116. auto res = cli_.Get("/e%6edwith%");
  4117. ASSERT_TRUE(res);
  4118. EXPECT_EQ(StatusCode::OK_200, res->status);
  4119. }
  4120. TEST_F(ServerTest, PercentEncodingUnicode) {
  4121. auto res = cli_.Get("/e%u006edwith%");
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::OK_200, res->status);
  4124. }
  4125. TEST_F(ServerTest, InvalidPercentEncoding) {
  4126. auto res = cli_.Get("/%endwith%");
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4129. }
  4130. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4131. auto res = cli_.Get("/%uendwith%");
  4132. ASSERT_TRUE(res);
  4133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4134. }
  4135. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4136. auto res = cli_.Get("/hello?aaa=bbb%");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4139. }
  4140. TEST_F(ServerTest, PlusSignEncoding) {
  4141. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4142. ASSERT_TRUE(res);
  4143. EXPECT_EQ(StatusCode::OK_200, res->status);
  4144. EXPECT_EQ("a +b", res->body);
  4145. }
  4146. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4147. // This test simulates a potential DoS attack using many headers
  4148. // to verify our security fix prevents memory exhaustion
  4149. httplib::Headers attack_headers;
  4150. // Attempt to add many headers like an attacker would (200 headers to far
  4151. // exceed limit)
  4152. for (int i = 0; i < 200; i++) {
  4153. std::string name = "X-Attack-Header-" + std::to_string(i);
  4154. std::string value = "attack_payload_" + std::to_string(i);
  4155. attack_headers.emplace(name, value);
  4156. }
  4157. // Try to POST with excessive headers
  4158. cli_.set_keep_alive(true);
  4159. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4160. // Should either fail or return 400 Bad Request due to security limit
  4161. if (res) {
  4162. // If we get a response, it should be 400 Bad Request
  4163. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4164. EXPECT_EQ("close", res->get_header_value("Connection"));
  4165. }
  4166. EXPECT_FALSE(cli_.is_socket_open());
  4167. }
  4168. TEST_F(ServerTest, MultipartFormData) {
  4169. UploadFormDataItems items = {
  4170. {"text1", "text default", "", ""},
  4171. {"text2", "aωb", "", ""},
  4172. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4173. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4174. {"file3", "", "", "application/octet-stream"},
  4175. {"file4", "", "", " application/json tmp-string "}};
  4176. auto res = cli_.Post("/multipart", items);
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ(StatusCode::OK_200, res->status);
  4179. }
  4180. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4181. UploadFormDataItems items = {
  4182. {"text", "default text", "", ""},
  4183. {"multi_text1", "aaaaa", "", ""},
  4184. {"multi_text1", "bbbbb", "", ""},
  4185. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4186. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4187. "application/json"},
  4188. };
  4189. auto res = cli_.Post("/multipart/multi_file_values", items);
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. }
  4193. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4194. auto res = cli_.Get("/hi");
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::OK_200, res->status);
  4197. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4198. EXPECT_EQ("Hello World!", res->body);
  4199. }
  4200. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4201. Request req;
  4202. req.method = "POST";
  4203. req.path = "/chunked";
  4204. std::string host_and_port;
  4205. host_and_port += HOST;
  4206. host_and_port += ":";
  4207. host_and_port += std::to_string(PORT);
  4208. req.headers.emplace("Host", host_and_port.c_str());
  4209. req.headers.emplace("Accept", "*/*");
  4210. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4211. req.headers.emplace("Content-Type", "text/plain");
  4212. req.headers.emplace("Content-Length", "0");
  4213. req.headers.emplace(
  4214. "Transfer-Encoding",
  4215. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4216. // Client does not chunk, so make a chunked body manually.
  4217. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4218. auto res = std::make_shared<Response>();
  4219. auto error = Error::Success;
  4220. auto ret = cli_.send(req, *res, error);
  4221. ASSERT_TRUE(ret);
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. }
  4224. TEST_F(ServerTest, GetStreamed2) {
  4225. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4228. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4229. EXPECT_EQ(true, res->has_header("Content-Range"));
  4230. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4231. EXPECT_EQ(std::string("ab"), res->body);
  4232. }
  4233. TEST_F(ServerTest, GetStreamed) {
  4234. auto res = cli_.Get("/streamed");
  4235. ASSERT_TRUE(res);
  4236. EXPECT_EQ(StatusCode::OK_200, res->status);
  4237. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4238. EXPECT_EQ(std::string("aaabbb"), res->body);
  4239. }
  4240. TEST_F(ServerTest, GetStreamedWithRange1) {
  4241. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4242. ASSERT_TRUE(res);
  4243. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4244. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4245. EXPECT_EQ(true, res->has_header("Content-Range"));
  4246. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4247. EXPECT_EQ(std::string("def"), res->body);
  4248. }
  4249. TEST_F(ServerTest, GetStreamedWithRange2) {
  4250. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4254. EXPECT_EQ(true, res->has_header("Content-Range"));
  4255. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4256. EXPECT_EQ(std::string("bcdefg"), res->body);
  4257. }
  4258. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4259. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4262. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(true, res->has_header("Content-Range"));
  4264. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4265. EXPECT_EQ(std::string("efg"), res->body);
  4266. }
  4267. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4268. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4271. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4272. EXPECT_EQ(false, res->has_header("Content-Range"));
  4273. EXPECT_EQ(0U, res->body.size());
  4274. }
  4275. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4276. auto res = cli_.Get("/streamed-with-range",
  4277. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4278. "92233720368547758079223372036854775807"}});
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4281. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4282. EXPECT_EQ(false, res->has_header("Content-Range"));
  4283. EXPECT_EQ(0U, res->body.size());
  4284. }
  4285. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4286. auto res = cli_.Get(
  4287. "/with-range",
  4288. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4289. {"Accept-Encoding", ""}});
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4292. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4293. EXPECT_EQ(true, res->has_header("Content-Range"));
  4294. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4295. EXPECT_EQ(std::string("abcdefg"), res->body);
  4296. }
  4297. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4298. auto res = cli_.Get("/with-range", {
  4299. {"Range", "bytes=0-"},
  4300. {"Accept-Encoding", ""},
  4301. });
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4304. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4305. EXPECT_EQ(true, res->has_header("Content-Range"));
  4306. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4307. EXPECT_EQ(std::string("abcdefg"), res->body);
  4308. }
  4309. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4310. auto res =
  4311. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4314. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4315. EXPECT_EQ(false, res->has_header("Content-Range"));
  4316. EXPECT_EQ(267U, res->body.size());
  4317. // Check that both range contents are present
  4318. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4319. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4320. // Check that Content-Range headers are present for both ranges
  4321. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4322. std::string::npos);
  4323. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4324. std::string::npos);
  4325. }
  4326. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4327. Ranges ranges;
  4328. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4329. ranges.emplace_back(0, -1);
  4330. }
  4331. auto res =
  4332. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4333. ASSERT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4335. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4336. EXPECT_EQ(false, res->has_header("Content-Range"));
  4337. EXPECT_EQ(0U, res->body.size());
  4338. }
  4339. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4340. auto res =
  4341. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4344. EXPECT_EQ(5U, res->body.size());
  4345. // Check that overlapping ranges are coalesced into a single range
  4346. EXPECT_EQ("bcdef", res->body);
  4347. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4348. // Should be single range, not multipart
  4349. EXPECT_TRUE(res->has_header("Content-Range"));
  4350. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4351. }
  4352. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4353. auto res =
  4354. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4355. ASSERT_TRUE(res);
  4356. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4357. EXPECT_EQ(268U, res->body.size());
  4358. // Check that both range contents are present
  4359. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4360. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4361. // Check that Content-Range headers are present for both ranges
  4362. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4363. std::string::npos);
  4364. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4365. std::string::npos);
  4366. }
  4367. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4368. auto res =
  4369. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4370. ASSERT_TRUE(res);
  4371. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4372. EXPECT_EQ(269U, res->body.size());
  4373. // Check that both duplicate range contents are present
  4374. size_t first_abc = res->body.find("abc\r\n");
  4375. EXPECT_TRUE(first_abc != std::string::npos);
  4376. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4377. EXPECT_TRUE(second_abc != std::string::npos);
  4378. // Check that Content-Range headers are present for both ranges
  4379. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4380. EXPECT_TRUE(first_range != std::string::npos);
  4381. size_t second_range =
  4382. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4383. EXPECT_TRUE(second_range != std::string::npos);
  4384. }
  4385. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4386. auto res = cli_.Get("/streamed-with-range?error",
  4387. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4390. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4391. EXPECT_EQ(false, res->has_header("Content-Range"));
  4392. EXPECT_EQ(0U, res->body.size());
  4393. }
  4394. TEST_F(ServerTest, GetStreamedEndless) {
  4395. uint64_t offset = 0;
  4396. auto res = cli_.Get("/streamed-cancel",
  4397. [&](const char * /*data*/, uint64_t data_length) {
  4398. if (offset < 100) {
  4399. offset += data_length;
  4400. return true;
  4401. }
  4402. return false;
  4403. });
  4404. ASSERT_TRUE(!res);
  4405. EXPECT_EQ(Error::Canceled, res.error());
  4406. }
  4407. TEST_F(ServerTest, ClientStop) {
  4408. std::atomic_size_t count{4};
  4409. std::vector<std::thread> threads;
  4410. for (auto i = count.load(); i != 0; --i) {
  4411. threads.emplace_back([&]() {
  4412. auto res = cli_.Get("/streamed-cancel",
  4413. [&](const char *, uint64_t) { return true; });
  4414. --count;
  4415. ASSERT_TRUE(!res);
  4416. EXPECT_TRUE(res.error() == Error::Canceled ||
  4417. res.error() == Error::Read || res.error() == Error::Write);
  4418. });
  4419. }
  4420. std::this_thread::sleep_for(std::chrono::seconds(2));
  4421. while (count != 0) {
  4422. cli_.stop();
  4423. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4424. }
  4425. for (auto &t : threads) {
  4426. t.join();
  4427. }
  4428. }
  4429. TEST_F(ServerTest, GetWithRange1) {
  4430. auto res = cli_.Get("/with-range", {
  4431. make_range_header({{3, 5}}),
  4432. {"Accept-Encoding", ""},
  4433. });
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4436. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4437. EXPECT_EQ(true, res->has_header("Content-Range"));
  4438. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4439. EXPECT_EQ(std::string("def"), res->body);
  4440. }
  4441. TEST_F(ServerTest, GetWithRange2) {
  4442. auto res = cli_.Get("/with-range", {
  4443. make_range_header({{1, -1}}),
  4444. {"Accept-Encoding", ""},
  4445. });
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(true, res->has_header("Content-Range"));
  4450. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4451. EXPECT_EQ(std::string("bcdefg"), res->body);
  4452. }
  4453. TEST_F(ServerTest, GetWithRange3) {
  4454. auto res = cli_.Get("/with-range", {
  4455. make_range_header({{0, 0}}),
  4456. {"Accept-Encoding", ""},
  4457. });
  4458. ASSERT_TRUE(res);
  4459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4460. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4461. EXPECT_EQ(true, res->has_header("Content-Range"));
  4462. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4463. EXPECT_EQ(std::string("a"), res->body);
  4464. }
  4465. TEST_F(ServerTest, GetWithRange4) {
  4466. auto res = cli_.Get("/with-range", {
  4467. make_range_header({{-1, 2}}),
  4468. {"Accept-Encoding", ""},
  4469. });
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4472. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4473. EXPECT_EQ(true, res->has_header("Content-Range"));
  4474. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4475. EXPECT_EQ(std::string("fg"), res->body);
  4476. }
  4477. TEST_F(ServerTest, GetWithRange5) {
  4478. auto res = cli_.Get("/with-range", {
  4479. make_range_header({{0, 5}}),
  4480. {"Accept-Encoding", ""},
  4481. });
  4482. ASSERT_TRUE(res);
  4483. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4484. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4485. EXPECT_EQ(true, res->has_header("Content-Range"));
  4486. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4487. EXPECT_EQ(std::string("abcdef"), res->body);
  4488. }
  4489. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4490. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4491. ASSERT_TRUE(res);
  4492. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4493. }
  4494. TEST_F(ServerTest, GetWithRangeMultipart) {
  4495. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4496. ASSERT_TRUE(res);
  4497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4498. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4499. EXPECT_EQ(false, res->has_header("Content-Range"));
  4500. EXPECT_EQ(267U, res->body.size());
  4501. }
  4502. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4503. auto res =
  4504. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4507. }
  4508. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4509. auto res = cli_.Get("/with-range-customized-response",
  4510. {{make_range_header({{1, 2}})}});
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4513. EXPECT_EQ(true, res->has_header("Content-Length"));
  4514. EXPECT_EQ(false, res->has_header("Content-Range"));
  4515. EXPECT_EQ(JSON_DATA, res->body);
  4516. }
  4517. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4518. auto res = cli_.Get("/with-range-customized-response",
  4519. {{make_range_header({{1, 2}, {4, 5}})}});
  4520. ASSERT_TRUE(res);
  4521. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4522. EXPECT_EQ(true, res->has_header("Content-Length"));
  4523. EXPECT_EQ(false, res->has_header("Content-Range"));
  4524. EXPECT_EQ(JSON_DATA, res->body);
  4525. }
  4526. TEST_F(ServerTest, Issue1772) {
  4527. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4528. ASSERT_TRUE(res);
  4529. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4530. }
  4531. TEST_F(ServerTest, Issue609) {
  4532. auto res = cli_.Delete("/issue609");
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ(std::string("ok"), res->body);
  4536. }
  4537. TEST_F(ServerTest, GetStreamedChunked) {
  4538. auto res = cli_.Get("/streamed-chunked");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ(std::string("123456789"), res->body);
  4542. }
  4543. TEST_F(ServerTest, GetStreamedChunked2) {
  4544. auto res = cli_.Get("/streamed-chunked2");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ(std::string("123456789"), res->body);
  4548. }
  4549. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4550. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4551. ASSERT_TRUE(res);
  4552. EXPECT_EQ(StatusCode::OK_200, res->status);
  4553. EXPECT_EQ(std::string("123456789"), res->body);
  4554. EXPECT_TRUE(res->has_header("Trailer"));
  4555. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4556. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4557. // Trailers are now stored separately from headers (security fix)
  4558. EXPECT_EQ(2U, res->trailers.size());
  4559. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4560. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4561. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4562. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4563. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4564. // Verify trailers are NOT in headers (security verification)
  4565. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4566. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4567. }
  4568. TEST_F(ServerTest, LargeChunkedPost) {
  4569. Request req;
  4570. req.method = "POST";
  4571. req.path = "/large-chunked";
  4572. std::string host_and_port;
  4573. host_and_port += HOST;
  4574. host_and_port += ":";
  4575. host_and_port += std::to_string(PORT);
  4576. req.headers.emplace("Host", host_and_port.c_str());
  4577. req.headers.emplace("Accept", "*/*");
  4578. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4579. req.headers.emplace("Content-Type", "text/plain");
  4580. req.headers.emplace("Content-Length", "0");
  4581. req.headers.emplace("Transfer-Encoding", "chunked");
  4582. std::string long_string(30 * 1024u, 'a');
  4583. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4584. // Attempt to make a large enough post to exceed OS buffers, to test that
  4585. // the server handles short reads if the full chunk data isn't available.
  4586. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4587. auto res = std::make_shared<Response>();
  4588. auto error = Error::Success;
  4589. auto ret = cli_.send(req, *res, error);
  4590. ASSERT_TRUE(ret);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. }
  4593. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4594. auto res = cli_.Get("/remote_addr");
  4595. ASSERT_TRUE(res);
  4596. EXPECT_EQ(StatusCode::OK_200, res->status);
  4597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4598. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4599. }
  4600. TEST_F(ServerTest, GetMethodLocalAddr) {
  4601. auto res = cli_.Get("/local_addr");
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4605. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4606. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4607. }
  4608. TEST_F(ServerTest, HTTPResponseSplitting) {
  4609. auto res = cli_.Get("/http_response_splitting");
  4610. ASSERT_TRUE(res);
  4611. EXPECT_EQ(StatusCode::OK_200, res->status);
  4612. }
  4613. TEST_F(ServerTest, SlowRequest) {
  4614. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4615. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4616. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4617. }
  4618. #if 0
  4619. TEST_F(ServerTest, SlowPost) {
  4620. char buffer[64 * 1024];
  4621. memset(buffer, 0x42, sizeof(buffer));
  4622. auto res = cli_.Post(
  4623. "/slowpost", 64 * 1024 * 1024,
  4624. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4625. auto ret = sink.write(buffer, sizeof(buffer));
  4626. EXPECT_TRUE(ret);
  4627. return true;
  4628. },
  4629. "text/plain");
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. }
  4633. TEST_F(ServerTest, SlowPostFail) {
  4634. char buffer[64 * 1024];
  4635. memset(buffer, 0x42, sizeof(buffer));
  4636. cli_.set_write_timeout(std::chrono::seconds(0));
  4637. auto res = cli_.Post(
  4638. "/slowpost", 64 * 1024 * 1024,
  4639. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4640. sink.write(buffer, sizeof(buffer));
  4641. return true;
  4642. },
  4643. "text/plain");
  4644. ASSERT_TRUE(!res);
  4645. EXPECT_EQ(Error::Write, res.error());
  4646. }
  4647. #endif
  4648. TEST_F(ServerTest, Put) {
  4649. auto res = cli_.Put("/put", "PUT", "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("PUT", res->body);
  4653. }
  4654. TEST_F(ServerTest, PutWithContentProvider) {
  4655. auto res = cli_.Put(
  4656. "/put", 3,
  4657. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4658. sink.os << "PUT";
  4659. return true;
  4660. },
  4661. "text/plain");
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("PUT", res->body);
  4665. }
  4666. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4667. auto res = cli_.Post(
  4668. "/post", 42,
  4669. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4670. return false;
  4671. },
  4672. "text/plain");
  4673. ASSERT_TRUE(!res);
  4674. EXPECT_EQ(Error::Canceled, res.error());
  4675. }
  4676. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4677. auto res = cli_.Put(
  4678. "/put",
  4679. [](size_t /*offset*/, DataSink &sink) {
  4680. sink.os << "PUT";
  4681. sink.done();
  4682. return true;
  4683. },
  4684. "text/plain");
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::OK_200, res->status);
  4687. EXPECT_EQ("PUT", res->body);
  4688. }
  4689. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4690. auto res = cli_.Post(
  4691. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4692. "text/plain");
  4693. ASSERT_TRUE(!res);
  4694. EXPECT_EQ(Error::Canceled, res.error());
  4695. }
  4696. TEST_F(ServerTest, PostLoopBack) {
  4697. std::string body;
  4698. auto res = cli_.Post(
  4699. "/post-loopback", 9,
  4700. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4701. EXPECT_EQ(9u, length);
  4702. sink.write("123", 3);
  4703. sink.write("456", 3);
  4704. sink.write("789", 3);
  4705. return true;
  4706. },
  4707. "text/plain",
  4708. [&body](const char *data, size_t data_length) {
  4709. body.append(data, data_length);
  4710. return true;
  4711. });
  4712. ASSERT_TRUE(res);
  4713. EXPECT_EQ(StatusCode::OK_200, res->status);
  4714. EXPECT_EQ("123456789", body);
  4715. }
  4716. TEST_F(ServerTest, PutLoopBack) {
  4717. std::string body;
  4718. auto res = cli_.Put(
  4719. "/put-loopback", 9,
  4720. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4721. EXPECT_EQ(9u, length);
  4722. sink.write("123", 3);
  4723. sink.write("456", 3);
  4724. sink.write("789", 3);
  4725. return true;
  4726. },
  4727. "text/plain",
  4728. [&body](const char *data, size_t data_length) {
  4729. body.append(data, data_length);
  4730. return true;
  4731. });
  4732. ASSERT_TRUE(res);
  4733. EXPECT_EQ(StatusCode::OK_200, res->status);
  4734. EXPECT_EQ("123456789", body);
  4735. }
  4736. TEST_F(ServerTest, PatchLoopBack) {
  4737. std::string body;
  4738. auto res = cli_.Patch(
  4739. "/patch-loopback", 9,
  4740. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4741. EXPECT_EQ(9u, length);
  4742. sink.write("123", 3);
  4743. sink.write("456", 3);
  4744. sink.write("789", 3);
  4745. return true;
  4746. },
  4747. "text/plain",
  4748. [&body](const char *data, size_t data_length) {
  4749. body.append(data, data_length);
  4750. return true;
  4751. });
  4752. ASSERT_TRUE(res);
  4753. EXPECT_EQ(StatusCode::OK_200, res->status);
  4754. EXPECT_EQ("123456789", body);
  4755. }
  4756. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4757. std::string body;
  4758. auto res = cli_.Post(
  4759. "/post-loopback",
  4760. [](size_t /*offset*/, DataSink &sink) {
  4761. sink.write("123", 3);
  4762. sink.write("456", 3);
  4763. sink.write("789", 3);
  4764. sink.done();
  4765. return true;
  4766. },
  4767. "text/plain",
  4768. [&body](const char *data, size_t data_length) {
  4769. body.append(data, data_length);
  4770. return true;
  4771. });
  4772. ASSERT_TRUE(res);
  4773. EXPECT_EQ(StatusCode::OK_200, res->status);
  4774. EXPECT_EQ("123456789", body);
  4775. }
  4776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4777. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4778. cli_.set_compress(true);
  4779. auto res = cli_.Put(
  4780. "/put", 3,
  4781. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4782. sink.os << "PUT";
  4783. return true;
  4784. },
  4785. "text/plain");
  4786. ASSERT_TRUE(res);
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. EXPECT_EQ("PUT", res->body);
  4789. }
  4790. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4791. cli_.set_compress(true);
  4792. auto res = cli_.Post(
  4793. "/post", 42,
  4794. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4795. return false;
  4796. },
  4797. "text/plain");
  4798. ASSERT_TRUE(!res);
  4799. EXPECT_EQ(Error::Canceled, res.error());
  4800. }
  4801. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4802. cli_.set_compress(true);
  4803. auto res = cli_.Put(
  4804. "/put",
  4805. [](size_t /*offset*/, DataSink &sink) {
  4806. sink.os << "PUT";
  4807. sink.done();
  4808. return true;
  4809. },
  4810. "text/plain");
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::OK_200, res->status);
  4813. EXPECT_EQ("PUT", res->body);
  4814. }
  4815. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4816. cli_.set_compress(true);
  4817. auto res = cli_.Post(
  4818. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4819. "text/plain");
  4820. ASSERT_TRUE(!res);
  4821. EXPECT_EQ(Error::Canceled, res.error());
  4822. }
  4823. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4824. cli_.set_compress(true);
  4825. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. EXPECT_EQ(LARGE_DATA, res->body);
  4829. }
  4830. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4831. #ifdef CPPHTTPLIB_SSL_ENABLED
  4832. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4833. Client cli(s.c_str());
  4834. cli.enable_server_certificate_verification(false);
  4835. #else
  4836. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4837. Client cli(s.c_str());
  4838. #endif
  4839. cli.set_compress(true);
  4840. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ(LARGE_DATA, res->body);
  4844. // The compressed size should be less than a 10th of the original. May vary
  4845. // depending on the zlib library.
  4846. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4847. static_cast<uint64_t>(10 * 1024 * 1024));
  4848. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4849. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4850. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4851. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4852. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4853. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4854. #endif
  4855. }
  4856. TEST_F(ServerTest, PutContentWithDeflate) {
  4857. cli_.set_compress(false);
  4858. Headers headers;
  4859. headers.emplace("Content-Encoding", "deflate");
  4860. // PUT in deflate format:
  4861. auto res = cli_.Put("/put", headers,
  4862. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. EXPECT_EQ("PUT", res->body);
  4866. }
  4867. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4868. Headers headers;
  4869. headers.emplace("Accept-Encoding", "gzip, deflate");
  4870. auto res = cli_.Get("/streamed-chunked", headers);
  4871. ASSERT_TRUE(res);
  4872. EXPECT_EQ(StatusCode::OK_200, res->status);
  4873. EXPECT_EQ(std::string("123456789"), res->body);
  4874. }
  4875. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4876. Headers headers;
  4877. headers.emplace("Accept-Encoding", "gzip, deflate");
  4878. auto res = cli_.Get("/streamed-chunked2", headers);
  4879. ASSERT_TRUE(res);
  4880. EXPECT_EQ(StatusCode::OK_200, res->status);
  4881. EXPECT_EQ(std::string("123456789"), res->body);
  4882. }
  4883. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4884. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST(GzipDecompressor, ChunkedDecompression) {
  4889. std::string data;
  4890. for (size_t i = 0; i < 32 * 1024; ++i) {
  4891. data.push_back(static_cast<char>('a' + i % 26));
  4892. }
  4893. std::string compressed_data;
  4894. {
  4895. httplib::detail::gzip_compressor compressor;
  4896. bool result = compressor.compress(
  4897. data.data(), data.size(),
  4898. /*last=*/true,
  4899. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4900. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4901. compressed_data_size);
  4902. return true;
  4903. });
  4904. ASSERT_TRUE(result);
  4905. }
  4906. std::string decompressed_data;
  4907. {
  4908. httplib::detail::gzip_decompressor decompressor;
  4909. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4910. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4911. size_t chunk_size = 130;
  4912. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4913. chunk_begin += chunk_size) {
  4914. size_t current_chunk_size =
  4915. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4916. bool result = decompressor.decompress(
  4917. compressed_data.data() + chunk_begin, current_chunk_size,
  4918. [&](const char *decompressed_data_chunk,
  4919. size_t decompressed_data_chunk_size) {
  4920. decompressed_data.insert(decompressed_data.size(),
  4921. decompressed_data_chunk,
  4922. decompressed_data_chunk_size);
  4923. return true;
  4924. });
  4925. ASSERT_TRUE(result);
  4926. }
  4927. }
  4928. ASSERT_EQ(data, decompressed_data);
  4929. }
  4930. TEST(GzipDecompressor, DeflateDecompression) {
  4931. std::string original_text = "Raw deflate without gzip";
  4932. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4933. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4934. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4935. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4936. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4937. std::string decompressed_data;
  4938. {
  4939. httplib::detail::gzip_decompressor decompressor;
  4940. bool result = decompressor.decompress(
  4941. compressed_data.data(), compressed_data.size(),
  4942. [&](const char *decompressed_data_chunk,
  4943. size_t decompressed_data_chunk_size) {
  4944. decompressed_data.insert(decompressed_data.size(),
  4945. decompressed_data_chunk,
  4946. decompressed_data_chunk_size);
  4947. return true;
  4948. });
  4949. ASSERT_TRUE(result);
  4950. }
  4951. ASSERT_EQ(original_text, decompressed_data);
  4952. }
  4953. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4954. std::string original_text = "Raw deflate without gzip";
  4955. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4956. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4957. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4958. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4959. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4960. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4961. std::string decompressed_data;
  4962. {
  4963. httplib::detail::gzip_decompressor decompressor;
  4964. bool result = decompressor.decompress(
  4965. compressed_data.data(), compressed_data.size(),
  4966. [&](const char *decompressed_data_chunk,
  4967. size_t decompressed_data_chunk_size) {
  4968. decompressed_data.insert(decompressed_data.size(),
  4969. decompressed_data_chunk,
  4970. decompressed_data_chunk_size);
  4971. return true;
  4972. });
  4973. ASSERT_TRUE(result);
  4974. }
  4975. ASSERT_EQ(original_text, decompressed_data);
  4976. }
  4977. #endif
  4978. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4979. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4980. Headers headers;
  4981. headers.emplace("Accept-Encoding", "br");
  4982. auto res = cli_.Get("/streamed-chunked", headers);
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ(std::string("123456789"), res->body);
  4986. }
  4987. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4988. Headers headers;
  4989. headers.emplace("Accept-Encoding", "br");
  4990. auto res = cli_.Get("/streamed-chunked2", headers);
  4991. ASSERT_TRUE(res);
  4992. EXPECT_EQ(StatusCode::OK_200, res->status);
  4993. EXPECT_EQ(std::string("123456789"), res->body);
  4994. }
  4995. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4996. cli_.set_compress(true);
  4997. auto res = cli_.Put(
  4998. "/put", 3,
  4999. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5000. sink.os << "PUT";
  5001. return true;
  5002. },
  5003. "text/plain");
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(StatusCode::OK_200, res->status);
  5006. EXPECT_EQ("PUT", res->body);
  5007. }
  5008. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5009. cli_.set_compress(true);
  5010. auto res = cli_.Put(
  5011. "/put",
  5012. [](size_t /*offset*/, DataSink &sink) {
  5013. sink.os << "PUT";
  5014. sink.done();
  5015. return true;
  5016. },
  5017. "text/plain");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. EXPECT_EQ("PUT", res->body);
  5021. }
  5022. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5023. cli_.set_compress(true);
  5024. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5025. ASSERT_TRUE(res);
  5026. EXPECT_EQ(StatusCode::OK_200, res->status);
  5027. EXPECT_EQ(LARGE_DATA, res->body);
  5028. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5029. }
  5030. #endif
  5031. TEST_F(ServerTest, Patch) {
  5032. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("PATCH", res->body);
  5036. }
  5037. TEST_F(ServerTest, Delete) {
  5038. auto res = cli_.Delete("/delete");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. EXPECT_EQ("DELETE", res->body);
  5042. }
  5043. TEST_F(ServerTest, DeleteContentReceiver) {
  5044. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5045. ASSERT_TRUE(res);
  5046. EXPECT_EQ(StatusCode::OK_200, res->status);
  5047. EXPECT_EQ("content", res->body);
  5048. }
  5049. TEST_F(ServerTest, Options) {
  5050. auto res = cli_.Options("*");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5054. EXPECT_TRUE(res->body.empty());
  5055. }
  5056. TEST_F(ServerTest, URL) {
  5057. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5058. ASSERT_TRUE(res);
  5059. EXPECT_EQ(StatusCode::OK_200, res->status);
  5060. }
  5061. TEST_F(ServerTest, ArrayParam) {
  5062. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. }
  5066. TEST_F(ServerTest, NoMultipleHeaders) {
  5067. Headers headers = {{"Content-Length", "5"}};
  5068. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5069. "text/plain");
  5070. ASSERT_TRUE(res);
  5071. EXPECT_EQ(StatusCode::OK_200, res->status);
  5072. }
  5073. TEST_F(ServerTest, PostContentReceiver) {
  5074. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5075. ASSERT_TRUE(res);
  5076. ASSERT_EQ(StatusCode::OK_200, res->status);
  5077. ASSERT_EQ("content", res->body);
  5078. }
  5079. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5080. UploadFormDataItems items = {
  5081. {"text1", "text default", "", ""},
  5082. {"text2", "aωb", "", ""},
  5083. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5084. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5085. {"file3", "", "", "application/octet-stream"},
  5086. };
  5087. auto res = cli_.Post("/content_receiver", items);
  5088. ASSERT_TRUE(res);
  5089. EXPECT_EQ(StatusCode::OK_200, res->status);
  5090. }
  5091. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5092. UploadFormDataItems items = {
  5093. {"text1", "text default", "", ""},
  5094. {"text2", "aωb", "", ""},
  5095. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5096. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5097. {"file3", "", "", "application/octet-stream"},
  5098. };
  5099. auto boundary = std::string("+++++");
  5100. std::string body;
  5101. for (const auto &item : items) {
  5102. body += "--" + boundary + "\r\n";
  5103. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5104. if (!item.filename.empty()) {
  5105. body += "; filename=\"" + item.filename + "\"";
  5106. }
  5107. body += "\r\n";
  5108. if (!item.content_type.empty()) {
  5109. body += "Content-Type: " + item.content_type + "\r\n";
  5110. }
  5111. body += "\r\n";
  5112. body += item.content + "\r\n";
  5113. }
  5114. body += "--" + boundary + "--\r\n";
  5115. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5116. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5117. ASSERT_TRUE(res);
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. }
  5120. TEST_F(ServerTest, PostContentReceiverGzip) {
  5121. cli_.set_compress(true);
  5122. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5123. ASSERT_TRUE(res);
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("content", res->body);
  5126. }
  5127. TEST_F(ServerTest, PutContentReceiver) {
  5128. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5129. ASSERT_TRUE(res);
  5130. ASSERT_EQ(StatusCode::OK_200, res->status);
  5131. ASSERT_EQ("content", res->body);
  5132. }
  5133. TEST_F(ServerTest, PatchContentReceiver) {
  5134. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5135. ASSERT_TRUE(res);
  5136. ASSERT_EQ(StatusCode::OK_200, res->status);
  5137. ASSERT_EQ("content", res->body);
  5138. }
  5139. template <typename ClientType>
  5140. void TestWithHeadersAndContentReceiver(
  5141. ClientType &cli,
  5142. std::function<Result(ClientType &, const std::string &, const Headers &,
  5143. const std::string &, const std::string &,
  5144. ContentReceiver, DownloadProgress)>
  5145. request_func) {
  5146. Headers headers;
  5147. headers.emplace("X-Custom-Header", "test-value");
  5148. std::string received_body;
  5149. auto res = request_func(
  5150. cli, "/content_receiver", headers, "content", "application/json",
  5151. [&](const char *data, size_t data_length) {
  5152. received_body.append(data, data_length);
  5153. return true;
  5154. },
  5155. nullptr);
  5156. ASSERT_TRUE(res);
  5157. EXPECT_EQ(StatusCode::OK_200, res->status);
  5158. EXPECT_EQ("content", received_body);
  5159. }
  5160. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5161. #ifdef CPPHTTPLIB_SSL_ENABLED
  5162. using ClientT = SSLClient;
  5163. #else
  5164. using ClientT = Client;
  5165. #endif
  5166. TestWithHeadersAndContentReceiver<ClientT>(
  5167. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5168. const std::string &body, const std::string &content_type,
  5169. ContentReceiver receiver, DownloadProgress progress) {
  5170. return cli.Post(path, headers, body, content_type, receiver, progress);
  5171. });
  5172. }
  5173. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5174. #ifdef CPPHTTPLIB_SSL_ENABLED
  5175. using ClientT = SSLClient;
  5176. #else
  5177. using ClientT = Client;
  5178. #endif
  5179. TestWithHeadersAndContentReceiver<ClientT>(
  5180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5181. const std::string &body, const std::string &content_type,
  5182. ContentReceiver receiver, DownloadProgress progress) {
  5183. return cli.Put(path, headers, body, content_type, receiver, progress);
  5184. });
  5185. }
  5186. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. using ClientT = SSLClient;
  5189. #else
  5190. using ClientT = Client;
  5191. #endif
  5192. TestWithHeadersAndContentReceiver<ClientT>(
  5193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5194. const std::string &body, const std::string &content_type,
  5195. ContentReceiver receiver, DownloadProgress progress) {
  5196. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5197. });
  5198. }
  5199. template <typename ClientType>
  5200. void TestWithHeadersAndContentReceiverWithProgress(
  5201. ClientType &cli,
  5202. std::function<Result(ClientType &, const std::string &, const Headers &,
  5203. const std::string &, const std::string &,
  5204. ContentReceiver, DownloadProgress)>
  5205. request_func) {
  5206. Headers headers;
  5207. headers.emplace("X-Test-Header", "progress-test");
  5208. std::string received_body;
  5209. auto progress_called = false;
  5210. auto res = request_func(
  5211. cli, "/content_receiver", headers, "content", "text/plain",
  5212. [&](const char *data, size_t data_length) {
  5213. received_body.append(data, data_length);
  5214. return true;
  5215. },
  5216. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5217. progress_called = true;
  5218. return true;
  5219. });
  5220. ASSERT_TRUE(res);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("content", received_body);
  5223. EXPECT_TRUE(progress_called);
  5224. }
  5225. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5226. #ifdef CPPHTTPLIB_SSL_ENABLED
  5227. using ClientT = SSLClient;
  5228. #else
  5229. using ClientT = Client;
  5230. #endif
  5231. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5232. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5233. const std::string &body, const std::string &content_type,
  5234. ContentReceiver receiver, DownloadProgress progress) {
  5235. return cli.Post(path, headers, body, content_type, receiver, progress);
  5236. });
  5237. }
  5238. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5239. #ifdef CPPHTTPLIB_SSL_ENABLED
  5240. using ClientT = SSLClient;
  5241. #else
  5242. using ClientT = Client;
  5243. #endif
  5244. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5245. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5246. const std::string &body, const std::string &content_type,
  5247. ContentReceiver receiver, DownloadProgress progress) {
  5248. return cli.Put(path, headers, body, content_type, receiver, progress);
  5249. });
  5250. }
  5251. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5252. #ifdef CPPHTTPLIB_SSL_ENABLED
  5253. using ClientT = SSLClient;
  5254. #else
  5255. using ClientT = Client;
  5256. #endif
  5257. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5258. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5259. const std::string &body, const std::string &content_type,
  5260. ContentReceiver receiver, DownloadProgress progress) {
  5261. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5262. });
  5263. }
  5264. template <typename ClientType>
  5265. void TestWithHeadersAndContentReceiverError(
  5266. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5267. const Headers &, const std::string &,
  5268. const std::string &, ContentReceiver)>
  5269. request_func) {
  5270. Headers headers;
  5271. headers.emplace("X-Error-Test", "true");
  5272. std::string received_body;
  5273. auto receiver_failed = false;
  5274. auto res =
  5275. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5276. [&](const char *data, size_t data_length) {
  5277. received_body.append(data, data_length);
  5278. receiver_failed = true;
  5279. return false;
  5280. });
  5281. ASSERT_FALSE(res);
  5282. EXPECT_TRUE(receiver_failed);
  5283. }
  5284. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5285. #ifdef CPPHTTPLIB_SSL_ENABLED
  5286. using ClientT = SSLClient;
  5287. #else
  5288. using ClientT = Client;
  5289. #endif
  5290. TestWithHeadersAndContentReceiverError<ClientT>(
  5291. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5292. const std::string &body, const std::string &content_type,
  5293. ContentReceiver receiver) {
  5294. return cli.Post(path, headers, body, content_type, receiver);
  5295. });
  5296. }
  5297. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5298. #ifdef CPPHTTPLIB_SSL_ENABLED
  5299. using ClientT = SSLClient;
  5300. #else
  5301. using ClientT = Client;
  5302. #endif
  5303. TestWithHeadersAndContentReceiverError<ClientT>(
  5304. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5305. const std::string &body, const std::string &content_type,
  5306. ContentReceiver receiver) {
  5307. return cli.Put(path, headers, body, content_type, receiver);
  5308. });
  5309. }
  5310. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5311. #ifdef CPPHTTPLIB_SSL_ENABLED
  5312. using ClientT = SSLClient;
  5313. #else
  5314. using ClientT = Client;
  5315. #endif
  5316. TestWithHeadersAndContentReceiverError<ClientT>(
  5317. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5318. const std::string &body, const std::string &content_type,
  5319. ContentReceiver receiver) {
  5320. return cli.Patch(path, headers, body, content_type, receiver);
  5321. });
  5322. }
  5323. TEST_F(ServerTest, PostQueryStringAndBody) {
  5324. auto res =
  5325. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5326. ASSERT_TRUE(res);
  5327. ASSERT_EQ(StatusCode::OK_200, res->status);
  5328. }
  5329. TEST_F(ServerTest, HTTP2Magic) {
  5330. Request req;
  5331. req.method = "PRI";
  5332. req.path = "*";
  5333. req.body = "SM";
  5334. auto res = std::make_shared<Response>();
  5335. auto error = Error::Success;
  5336. auto ret = cli_.send(req, *res, error);
  5337. ASSERT_TRUE(ret);
  5338. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5339. }
  5340. TEST_F(ServerTest, KeepAlive) {
  5341. auto res = cli_.Get("/hi");
  5342. ASSERT_TRUE(res);
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5345. EXPECT_EQ("Hello World!", res->body);
  5346. res = cli_.Get("/hi");
  5347. ASSERT_TRUE(res);
  5348. EXPECT_EQ(StatusCode::OK_200, res->status);
  5349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5350. EXPECT_EQ("Hello World!", res->body);
  5351. res = cli_.Get("/hi");
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5355. EXPECT_EQ("Hello World!", res->body);
  5356. res = cli_.Get("/not-exist");
  5357. ASSERT_TRUE(res);
  5358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5359. res = cli_.Post("/empty", "", "text/plain");
  5360. ASSERT_TRUE(res);
  5361. EXPECT_EQ(StatusCode::OK_200, res->status);
  5362. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5363. EXPECT_EQ("empty", res->body);
  5364. EXPECT_EQ("close", res->get_header_value("Connection"));
  5365. res = cli_.Post(
  5366. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5367. "text/plain");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("empty", res->body);
  5372. cli_.set_keep_alive(false);
  5373. res = cli_.Get("/last-request");
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ("close", res->get_header_value("Connection"));
  5377. }
  5378. TEST_F(ServerTest, TooManyRedirect) {
  5379. cli_.set_follow_location(true);
  5380. auto res = cli_.Get("/redirect/0");
  5381. ASSERT_TRUE(!res);
  5382. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5383. }
  5384. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5385. Request req;
  5386. req.method = "FOOBAR";
  5387. req.path = "/hi";
  5388. cli_.set_keep_alive(true);
  5389. auto res = cli_.send(req);
  5390. ASSERT_TRUE(res);
  5391. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5392. EXPECT_EQ("close", res->get_header_value("Connection"));
  5393. EXPECT_FALSE(cli_.is_socket_open());
  5394. }
  5395. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5397. TEST_F(ServerTest, Gzip) {
  5398. Headers headers;
  5399. headers.emplace("Accept-Encoding", "gzip, deflate");
  5400. auto res = cli_.Get("/compress", headers);
  5401. ASSERT_TRUE(res);
  5402. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5403. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5404. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5405. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5406. "7890123456789012345678901234567890",
  5407. res->body);
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. }
  5410. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "gzip, deflate");
  5413. auto res = cli_.Get("/compress-with-charset", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5416. EXPECT_EQ("application/json; charset=utf-8",
  5417. res->get_header_value("Content-Type"));
  5418. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5419. "7890123456789012345678901234567890",
  5420. res->body);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. }
  5423. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5424. Headers headers;
  5425. headers.emplace("Accept-Encoding", "");
  5426. auto res = cli_.Get("/compress", headers);
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. res->body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, GzipWithContentReceiver) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. std::string body;
  5440. auto res = cli_.Get("/compress", headers,
  5441. [&](const char *data, uint64_t data_length) {
  5442. EXPECT_EQ(100U, data_length);
  5443. body.append(data, data_length);
  5444. return true;
  5445. });
  5446. ASSERT_TRUE(res);
  5447. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5449. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5451. "7890123456789012345678901234567890",
  5452. body);
  5453. EXPECT_EQ(StatusCode::OK_200, res->status);
  5454. }
  5455. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5456. Headers headers;
  5457. headers.emplace("Accept-Encoding", "gzip, deflate");
  5458. cli_.set_decompress(false);
  5459. auto res = cli_.Get("/compress", headers);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5462. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5463. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5464. EXPECT_EQ(33U, res->body.size());
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. }
  5467. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5468. Headers headers;
  5469. headers.emplace("Accept-Encoding", "");
  5470. std::string body;
  5471. auto res = cli_.Get("/compress", headers,
  5472. [&](const char *data, uint64_t data_length) {
  5473. EXPECT_EQ(100U, data_length);
  5474. body.append(data, data_length);
  5475. return true;
  5476. });
  5477. ASSERT_TRUE(res);
  5478. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5479. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5480. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5481. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5482. "7890123456789012345678901234567890",
  5483. body);
  5484. EXPECT_EQ(StatusCode::OK_200, res->status);
  5485. }
  5486. TEST_F(ServerTest, NoGzip) {
  5487. Headers headers;
  5488. headers.emplace("Accept-Encoding", "gzip, deflate");
  5489. auto res = cli_.Get("/nocompress", headers);
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5492. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5493. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5494. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5495. "7890123456789012345678901234567890",
  5496. res->body);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. }
  5499. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5500. Headers headers;
  5501. headers.emplace("Accept-Encoding", "gzip, deflate");
  5502. std::string body;
  5503. auto res = cli_.Get("/nocompress", headers,
  5504. [&](const char *data, uint64_t data_length) {
  5505. EXPECT_EQ(100U, data_length);
  5506. body.append(data, data_length);
  5507. return true;
  5508. });
  5509. ASSERT_TRUE(res);
  5510. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5511. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5513. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5514. "7890123456789012345678901234567890",
  5515. body);
  5516. EXPECT_EQ(StatusCode::OK_200, res->status);
  5517. }
  5518. TEST_F(ServerTest, MultipartFormDataGzip) {
  5519. UploadFormDataItems items = {
  5520. {"key1", "test", "", ""},
  5521. {"key2", "--abcdefg123", "", ""},
  5522. };
  5523. cli_.set_compress(true);
  5524. auto res = cli_.Post("/compress-multipart", items);
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. #endif
  5529. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5530. TEST_F(ServerTest, Brotli) {
  5531. Headers headers;
  5532. headers.emplace("Accept-Encoding", "br");
  5533. auto res = cli_.Get("/compress", headers);
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5539. "7890123456789012345678901234567890",
  5540. res->body);
  5541. EXPECT_EQ(StatusCode::OK_200, res->status);
  5542. }
  5543. #endif
  5544. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5545. TEST_F(ServerTest, Zstd) {
  5546. Headers headers;
  5547. headers.emplace("Accept-Encoding", "zstd");
  5548. auto res = cli_.Get("/compress", headers);
  5549. ASSERT_TRUE(res);
  5550. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5553. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5554. "7890123456789012345678901234567890",
  5555. res->body);
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. }
  5558. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5559. Headers headers;
  5560. headers.emplace("Accept-Encoding", "");
  5561. auto res = cli_.Get("/compress", headers);
  5562. ASSERT_TRUE(res);
  5563. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5565. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5566. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5567. "7890123456789012345678901234567890",
  5568. res->body);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. }
  5571. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5572. Headers headers;
  5573. headers.emplace("Accept-Encoding", "zstd");
  5574. std::string body;
  5575. auto res = cli_.Get("/compress", headers,
  5576. [&](const char *data, uint64_t data_length) {
  5577. EXPECT_EQ(100U, data_length);
  5578. body.append(data, data_length);
  5579. return true;
  5580. });
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5583. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5584. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5586. "7890123456789012345678901234567890",
  5587. body);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. }
  5590. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5591. Headers headers;
  5592. headers.emplace("Accept-Encoding", "zstd");
  5593. cli_.set_decompress(false);
  5594. auto res = cli_.Get("/compress", headers);
  5595. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5596. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5597. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5598. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. ASSERT_EQ(26U, res->body.size());
  5605. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5606. 0);
  5607. }
  5608. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5609. Headers headers;
  5610. headers.emplace("Accept-Encoding", "");
  5611. std::string body;
  5612. auto res = cli_.Get("/compress", headers,
  5613. [&](const char *data, uint64_t data_length) {
  5614. EXPECT_EQ(100U, data_length);
  5615. body.append(data, data_length);
  5616. return true;
  5617. });
  5618. ASSERT_TRUE(res);
  5619. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5620. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5621. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5622. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5623. "7890123456789012345678901234567890",
  5624. body);
  5625. EXPECT_EQ(StatusCode::OK_200, res->status);
  5626. }
  5627. TEST_F(ServerTest, NoZstd) {
  5628. Headers headers;
  5629. headers.emplace("Accept-Encoding", "zstd");
  5630. auto res = cli_.Get("/nocompress", headers);
  5631. ASSERT_TRUE(res);
  5632. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5633. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5636. "7890123456789012345678901234567890",
  5637. res->body);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. }
  5640. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5641. Headers headers;
  5642. headers.emplace("Accept-Encoding", "zstd");
  5643. std::string body;
  5644. auto res = cli_.Get("/nocompress", headers,
  5645. [&](const char *data, uint64_t data_length) {
  5646. EXPECT_EQ(100U, data_length);
  5647. body.append(data, data_length);
  5648. return true;
  5649. });
  5650. ASSERT_TRUE(res);
  5651. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5652. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5653. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5655. "7890123456789012345678901234567890",
  5656. body);
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. }
  5659. // TODO: How to enable zstd ??
  5660. TEST_F(ServerTest, MultipartFormDataZstd) {
  5661. UploadFormDataItems items = {
  5662. {"key1", "test", "", ""},
  5663. {"key2", "--abcdefg123", "", ""},
  5664. };
  5665. Headers headers;
  5666. headers.emplace("Accept-Encoding", "zstd");
  5667. cli_.set_compress(true);
  5668. auto res = cli_.Post("/compress-multipart", headers, items);
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. }
  5672. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5673. Headers headers;
  5674. headers.emplace("Accept-Encoding", "zstd");
  5675. cli_.set_compress(true);
  5676. auto res = cli_.Put(
  5677. "/put", headers, 3,
  5678. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5679. sink.os << "PUT";
  5680. return true;
  5681. },
  5682. "text/plain");
  5683. ASSERT_TRUE(res);
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ("PUT", res->body);
  5686. }
  5687. // Pre-compression logging tests
  5688. TEST_F(ServerTest, PreCompressionLogging) {
  5689. // Test data for compression (matches the actual /compress endpoint content)
  5690. const std::string test_content =
  5691. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5692. "3456789012345678901234567890";
  5693. // Variables to capture logging data
  5694. std::string pre_compression_body;
  5695. std::string pre_compression_content_type;
  5696. std::string pre_compression_content_encoding;
  5697. std::string post_compression_body;
  5698. std::string post_compression_content_type;
  5699. std::string post_compression_content_encoding;
  5700. // Set up pre-compression logger
  5701. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5702. const Response &res) {
  5703. pre_compression_body = res.body;
  5704. pre_compression_content_type = res.get_header_value("Content-Type");
  5705. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5706. });
  5707. // Set up post-compression logger
  5708. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5709. post_compression_body = res.body;
  5710. post_compression_content_type = res.get_header_value("Content-Type");
  5711. post_compression_content_encoding =
  5712. res.get_header_value("Content-Encoding");
  5713. });
  5714. // Test with gzip compression
  5715. Headers headers;
  5716. headers.emplace("Accept-Encoding", "gzip");
  5717. auto res = cli_.Get("/compress", headers);
  5718. // Verify response was compressed
  5719. ASSERT_TRUE(res);
  5720. EXPECT_EQ(StatusCode::OK_200, res->status);
  5721. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5722. // Verify pre-compression logger captured uncompressed content
  5723. EXPECT_EQ(test_content, pre_compression_body);
  5724. EXPECT_EQ("text/plain", pre_compression_content_type);
  5725. EXPECT_TRUE(pre_compression_content_encoding
  5726. .empty()); // No encoding header before compression
  5727. // Verify post-compression logger captured compressed content
  5728. EXPECT_NE(test_content,
  5729. post_compression_body); // Should be different after compression
  5730. EXPECT_EQ("text/plain", post_compression_content_type);
  5731. EXPECT_EQ("gzip", post_compression_content_encoding);
  5732. // Verify compressed content is smaller
  5733. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5734. }
  5735. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5736. const std::string test_content =
  5737. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5738. "3456789012345678901234567890";
  5739. std::string pre_compression_body;
  5740. std::string post_compression_body;
  5741. svr_.set_pre_compression_logger(
  5742. [&](const Request & /*req*/, const Response &res) {
  5743. pre_compression_body = res.body;
  5744. });
  5745. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5746. post_compression_body = res.body;
  5747. });
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "br");
  5750. auto res = cli_.Get("/compress", headers);
  5751. ASSERT_TRUE(res);
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5754. // Verify pre-compression content is uncompressed
  5755. EXPECT_EQ(test_content, pre_compression_body);
  5756. // Verify post-compression content is compressed
  5757. EXPECT_NE(test_content, post_compression_body);
  5758. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5759. }
  5760. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5761. const std::string test_content =
  5762. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5763. "3456789012345678901234567890";
  5764. std::string pre_compression_body;
  5765. std::string post_compression_body;
  5766. svr_.set_pre_compression_logger(
  5767. [&](const Request & /*req*/, const Response &res) {
  5768. pre_compression_body = res.body;
  5769. });
  5770. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5771. post_compression_body = res.body;
  5772. });
  5773. // Request without compression (use /nocompress endpoint)
  5774. Headers headers;
  5775. auto res = cli_.Get("/nocompress", headers);
  5776. ASSERT_TRUE(res);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5779. // Pre-compression logger should not be called when no compression is applied
  5780. EXPECT_TRUE(
  5781. pre_compression_body.empty()); // Pre-compression logger not called
  5782. EXPECT_EQ(
  5783. test_content,
  5784. post_compression_body); // Post-compression logger captures final content
  5785. }
  5786. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5787. const std::string test_content =
  5788. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5789. "3456789012345678901234567890";
  5790. std::string pre_compression_body;
  5791. bool pre_logger_called = false;
  5792. // Set only pre-compression logger
  5793. svr_.set_pre_compression_logger(
  5794. [&](const Request & /*req*/, const Response &res) {
  5795. pre_compression_body = res.body;
  5796. pre_logger_called = true;
  5797. });
  5798. Headers headers;
  5799. headers.emplace("Accept-Encoding", "gzip");
  5800. auto res = cli_.Get("/compress", headers);
  5801. ASSERT_TRUE(res);
  5802. EXPECT_EQ(StatusCode::OK_200, res->status);
  5803. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5804. // Verify pre-compression logger was called
  5805. EXPECT_TRUE(pre_logger_called);
  5806. EXPECT_EQ(test_content, pre_compression_body);
  5807. }
  5808. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5809. {
  5810. // Test with Expect: 100-continue header - success case
  5811. // Server returns 100 Continue, client sends body, server returns 200 OK
  5812. Request req;
  5813. req.method = "POST";
  5814. req.path = "/post-large";
  5815. req.set_header("Expect", "100-continue");
  5816. req.body = LARGE_DATA;
  5817. Response res;
  5818. auto error = Error::Success;
  5819. cli_.set_keep_alive(true);
  5820. auto ret = cli_.send(req, res, error);
  5821. EXPECT_TRUE(ret);
  5822. EXPECT_EQ(StatusCode::OK_200, res.status);
  5823. EXPECT_EQ(LARGE_DATA, res.body);
  5824. }
  5825. {
  5826. // Test with Expect: 100-continue header - error case
  5827. // Client should not send the body when server returns an error
  5828. Request req;
  5829. req.method = "POST";
  5830. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5831. req.set_header("Expect", "100-continue");
  5832. req.body = LARGE_DATA;
  5833. Response res;
  5834. auto error = Error::Success;
  5835. auto start = std::chrono::high_resolution_clock::now();
  5836. cli_.set_keep_alive(true);
  5837. auto ret = cli_.send(req, res, error);
  5838. auto end = std::chrono::high_resolution_clock::now();
  5839. auto elapsed =
  5840. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5841. .count();
  5842. // With Expect: 100-continue, request completes successfully but with error
  5843. EXPECT_TRUE(ret);
  5844. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5845. EXPECT_EQ("close", res.get_header_value("Connection"));
  5846. EXPECT_FALSE(cli_.is_socket_open());
  5847. EXPECT_LE(elapsed, 200);
  5848. }
  5849. {
  5850. // Send an extra GET request to ensure error recovery without hanging
  5851. Request req;
  5852. req.method = "GET";
  5853. req.path = "/hi";
  5854. auto start = std::chrono::high_resolution_clock::now();
  5855. auto res = cli_.send(req);
  5856. auto end = std::chrono::high_resolution_clock::now();
  5857. auto elapsed =
  5858. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5859. .count();
  5860. ASSERT_TRUE(res);
  5861. EXPECT_EQ(StatusCode::OK_200, res->status);
  5862. EXPECT_EQ("Hello World!", res->body);
  5863. EXPECT_LE(elapsed, 500);
  5864. }
  5865. }
  5866. TEST(ZstdDecompressor, ChunkedDecompression) {
  5867. std::string data;
  5868. for (size_t i = 0; i < 32 * 1024; ++i) {
  5869. data.push_back(static_cast<char>('a' + i % 26));
  5870. }
  5871. std::string compressed_data;
  5872. {
  5873. httplib::detail::zstd_compressor compressor;
  5874. bool result = compressor.compress(
  5875. data.data(), data.size(),
  5876. /*last=*/true,
  5877. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5878. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5879. compressed_data_size);
  5880. return true;
  5881. });
  5882. ASSERT_TRUE(result);
  5883. }
  5884. std::string decompressed_data;
  5885. {
  5886. httplib::detail::zstd_decompressor decompressor;
  5887. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5888. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5889. size_t chunk_size = 130;
  5890. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5891. chunk_begin += chunk_size) {
  5892. size_t current_chunk_size =
  5893. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5894. bool result = decompressor.decompress(
  5895. compressed_data.data() + chunk_begin, current_chunk_size,
  5896. [&](const char *decompressed_data_chunk,
  5897. size_t decompressed_data_chunk_size) {
  5898. decompressed_data.insert(decompressed_data.size(),
  5899. decompressed_data_chunk,
  5900. decompressed_data_chunk_size);
  5901. return true;
  5902. });
  5903. ASSERT_TRUE(result);
  5904. }
  5905. }
  5906. ASSERT_EQ(data, decompressed_data);
  5907. }
  5908. TEST(ZstdDecompressor, Decompress) {
  5909. std::string original_text = "Compressed with ZSTD";
  5910. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5911. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5912. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5913. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5914. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5915. std::string decompressed_data;
  5916. {
  5917. httplib::detail::zstd_decompressor decompressor;
  5918. bool result = decompressor.decompress(
  5919. compressed_data.data(), compressed_data.size(),
  5920. [&](const char *decompressed_data_chunk,
  5921. size_t decompressed_data_chunk_size) {
  5922. decompressed_data.insert(decompressed_data.size(),
  5923. decompressed_data_chunk,
  5924. decompressed_data_chunk_size);
  5925. return true;
  5926. });
  5927. ASSERT_TRUE(result);
  5928. }
  5929. ASSERT_EQ(original_text, decompressed_data);
  5930. }
  5931. #endif
  5932. // Sends a raw request to a server listening at HOST:PORT.
  5933. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5934. std::string *resp = nullptr) {
  5935. auto error = Error::Success;
  5936. auto client_sock = detail::create_client_socket(
  5937. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5938. /*connection_timeout_sec=*/5, 0,
  5939. /*read_timeout_sec=*/5, 0,
  5940. /*write_timeout_sec=*/5, 0, std::string(), error);
  5941. if (client_sock == INVALID_SOCKET) { return false; }
  5942. auto ret = detail::process_client_socket(
  5943. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5944. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5945. if (req.size() !=
  5946. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5947. return false;
  5948. }
  5949. char buf[512];
  5950. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5951. while (line_reader.getline()) {
  5952. if (resp) { *resp += line_reader.ptr(); }
  5953. }
  5954. return true;
  5955. });
  5956. detail::close_socket(client_sock);
  5957. return ret;
  5958. }
  5959. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5960. Server svr;
  5961. std::string header_value;
  5962. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5963. header_value = req.get_header_value("foo");
  5964. res.set_content("ok", "text/plain");
  5965. });
  5966. thread t = thread([&] { svr.listen(HOST, PORT); });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. t.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5974. // like characters are not treated the same - use vertical tab and escape.
  5975. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5976. "foo: \t \v bar \x1B\t \r\n"
  5977. "Connection: close\r\n"
  5978. "\r\n";
  5979. std::string res;
  5980. ASSERT_TRUE(send_request(5, req, &res));
  5981. EXPECT_EQ(header_value, "");
  5982. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5983. }
  5984. // Sends a raw request and verifies that there isn't a crash or exception.
  5985. static void test_raw_request(const std::string &req,
  5986. std::string *out = nullptr) {
  5987. Server svr;
  5988. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5989. res.set_content("ok", "text/plain");
  5990. });
  5991. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5992. res.set_content("ok", "text/plain");
  5993. });
  5994. svr.Get("/header_field_value_check",
  5995. [&](const Request & /*req*/, Response &res) {
  5996. res.set_content("ok", "text/plain");
  5997. });
  5998. // Server read timeout must be longer than the client read timeout for the
  5999. // bug to reproduce, probably to force the server to process a request
  6000. // without a trailing blank line.
  6001. const time_t client_read_timeout_sec = 1;
  6002. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6003. bool listen_thread_ok = false;
  6004. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6005. auto se = detail::scope_exit([&] {
  6006. svr.stop();
  6007. t.join();
  6008. ASSERT_FALSE(svr.is_running());
  6009. EXPECT_TRUE(listen_thread_ok);
  6010. });
  6011. svr.wait_until_ready();
  6012. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6013. }
  6014. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6015. // A certain header line causes an exception if the header property is parsed
  6016. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6017. test_raw_request(
  6018. "GET /hi HTTP/1.1\r\n"
  6019. " : "
  6020. " "
  6021. " ");
  6022. }
  6023. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6024. // A certain header line causes an exception if the header property *name* is
  6025. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6026. // greedy matcher and requires backtracking when there are a lot of ":"
  6027. // characters.
  6028. // This occurs with libc++ but not libstdc++.
  6029. test_raw_request(
  6030. "GET /hi HTTP/1.1\r\n"
  6031. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6032. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6033. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6034. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6035. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6036. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6037. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6038. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6039. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6040. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6041. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6042. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6043. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6044. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6045. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6046. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6047. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6048. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6049. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6050. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6051. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6052. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6053. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6054. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6055. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6056. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6057. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6058. "&&&%%%");
  6059. }
  6060. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6061. // Make sure this doesn't crash the server.
  6062. // In a previous version of the header line regex, the "\r" rendered the line
  6063. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6064. // a new position where the leading white space ended and the field value
  6065. // began.
  6066. // The crash occurs with libc++ but not libstdc++.
  6067. test_raw_request("GET /hi HTTP/1.1\r\n"
  6068. "a:" +
  6069. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6070. "\r\n"
  6071. "\r\n");
  6072. }
  6073. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6074. std::string out;
  6075. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6076. "Content-Type: text/plain\r\n"
  6077. "Transfer-Encoding: chunked\r\n"
  6078. "\r\n"
  6079. "nothex\r\n",
  6080. &out);
  6081. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6082. }
  6083. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6084. std::string out;
  6085. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6086. "Content-Type: text/plain\r\n"
  6087. "Transfer-Encoding: chunked\r\n"
  6088. "\r\n"
  6089. "3\r\n"
  6090. "xyz\r\n"
  6091. "NaN\r\n",
  6092. &out);
  6093. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6094. }
  6095. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6096. std::string out;
  6097. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6098. "Content-Type: text/plain\r\n"
  6099. "Transfer-Encoding: chunked\r\n"
  6100. "\r\n"
  6101. // Length is too large for 64 bits.
  6102. "1ffffffffffffffff\r\n"
  6103. "xyz\r\n",
  6104. &out);
  6105. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6106. }
  6107. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6108. test_raw_request("GET /hi HTTP/1.1\r\n"
  6109. "Content-Type: text/plain\r\n\r");
  6110. }
  6111. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6112. std::string out;
  6113. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6114. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6115. }
  6116. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6117. Server svr;
  6118. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6119. EXPECT_TRUE(!req.remote_addr.empty());
  6120. });
  6121. thread t = thread([&] { svr.listen(HOST, PORT); });
  6122. auto se = detail::scope_exit([&] {
  6123. svr.stop();
  6124. t.join();
  6125. ASSERT_FALSE(svr.is_running());
  6126. });
  6127. svr.wait_until_ready();
  6128. // Send an invalid request line to trigger Bad Request
  6129. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6130. std::string out;
  6131. ASSERT_TRUE(send_request(5, bad_req, &out));
  6132. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6133. }
  6134. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6135. std::string out;
  6136. std::string request(
  6137. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6138. test_raw_request(request, &out);
  6139. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6140. }
  6141. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6142. std::string out;
  6143. std::string request(
  6144. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6145. test_raw_request(request, &out);
  6146. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6147. }
  6148. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6149. std::string out;
  6150. std::string request(
  6151. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6152. test_raw_request(request, &out);
  6153. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6154. }
  6155. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6156. std::string out;
  6157. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6158. "Test: \r\n\r\n",
  6159. &out);
  6160. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6161. }
  6162. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6163. Server svr;
  6164. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6165. res.set_header("Cache-Control", "no-cache");
  6166. res.set_chunked_content_provider(
  6167. "text/event-stream", [](size_t offset, DataSink &sink) {
  6168. std::string s = "data:";
  6169. s += std::to_string(offset);
  6170. s += "\n\n";
  6171. auto ret = sink.write(s.data(), s.size());
  6172. EXPECT_TRUE(ret);
  6173. std::this_thread::sleep_for(std::chrono::seconds(1));
  6174. return true;
  6175. });
  6176. });
  6177. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6178. svr.wait_until_ready();
  6179. Client client(HOST, PORT);
  6180. const Headers headers = {{"Accept", "text/event-stream"}};
  6181. auto get_thread = std::thread([&client, &headers]() {
  6182. auto res = client.Get(
  6183. "/events", headers,
  6184. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6185. });
  6186. auto se = detail::scope_exit([&] {
  6187. svr.stop();
  6188. get_thread.join();
  6189. listen_thread.join();
  6190. ASSERT_FALSE(svr.is_running());
  6191. });
  6192. // Give GET time to get a few messages.
  6193. std::this_thread::sleep_for(std::chrono::seconds(2));
  6194. }
  6195. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6196. httplib::Server svr;
  6197. svr.Post("/hi",
  6198. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6199. res.status = StatusCode::OK_200;
  6200. });
  6201. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6202. svr.wait_until_ready();
  6203. Client cli(HOST, PORT);
  6204. auto res = cli.Post("/hi", "data", "text/plain");
  6205. ASSERT_TRUE(res);
  6206. EXPECT_EQ(StatusCode::OK_200, res->status);
  6207. svr.stop();
  6208. thread.join();
  6209. ASSERT_FALSE(svr.is_running());
  6210. res = cli.Post("/hi", "data", "text/plain");
  6211. ASSERT_FALSE(res);
  6212. }
  6213. TEST(ServerStopTest, ListenFailure) {
  6214. Server svr;
  6215. auto t = thread([&]() {
  6216. auto ret = svr.listen("????", PORT);
  6217. EXPECT_FALSE(ret);
  6218. });
  6219. svr.wait_until_ready();
  6220. svr.stop();
  6221. t.join();
  6222. }
  6223. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6224. TEST(ServerStopTest, Decommision) {
  6225. Server svr;
  6226. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6227. for (int i = 0; i < 4; i++) {
  6228. auto is_even = !(i % 2);
  6229. std::thread t{[&] {
  6230. try {
  6231. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6232. if (is_even) {
  6233. throw std::runtime_error("Some thing that happens to go wrong.");
  6234. }
  6235. svr.listen(HOST, PORT);
  6236. } catch (...) { svr.decommission(); }
  6237. }};
  6238. svr.wait_until_ready();
  6239. // Server is up
  6240. {
  6241. Client cli(HOST, PORT);
  6242. auto res = cli.Get("/hi");
  6243. if (is_even) {
  6244. EXPECT_FALSE(res);
  6245. } else {
  6246. EXPECT_TRUE(res);
  6247. EXPECT_EQ("hi...", res->body);
  6248. }
  6249. }
  6250. svr.stop();
  6251. t.join();
  6252. // Server is down...
  6253. {
  6254. Client cli(HOST, PORT);
  6255. auto res = cli.Get("/hi");
  6256. EXPECT_FALSE(res);
  6257. }
  6258. }
  6259. }
  6260. #endif
  6261. // Helper function for string body upload progress tests
  6262. template <typename SetupHandler, typename ClientCall>
  6263. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6264. ClientCall &&client_call,
  6265. const string &body) {
  6266. Server svr;
  6267. setup_handler(svr);
  6268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6269. auto se = detail::scope_exit([&] {
  6270. svr.stop();
  6271. t.join();
  6272. });
  6273. svr.wait_until_ready();
  6274. Client cli(HOST, PORT);
  6275. vector<uint64_t> progress_values;
  6276. bool progress_called = false;
  6277. auto res =
  6278. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6279. progress_values.push_back(current);
  6280. progress_called = true;
  6281. return true;
  6282. });
  6283. ASSERT_TRUE(res);
  6284. EXPECT_EQ(200, res->status);
  6285. EXPECT_TRUE(progress_called);
  6286. }
  6287. TEST(UploadProgressTest, PostStringBodyBasic) {
  6288. TestStringBodyUploadProgress(
  6289. [](Server &svr) {
  6290. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6291. res.set_content("received", "text/plain");
  6292. });
  6293. },
  6294. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6295. return cli.Post("/test", body, "text/plain", progress_callback);
  6296. },
  6297. "test data for upload progress");
  6298. }
  6299. TEST(UploadProgressTest, PutStringBodyBasic) {
  6300. TestStringBodyUploadProgress(
  6301. [](Server &svr) {
  6302. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6303. res.set_content("put received", "text/plain");
  6304. });
  6305. },
  6306. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6307. return cli.Put("/test", body, "text/plain", progress_callback);
  6308. },
  6309. "put test data for upload progress");
  6310. }
  6311. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6312. TestStringBodyUploadProgress(
  6313. [](Server &svr) {
  6314. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6315. res.set_content("patch received", "text/plain");
  6316. });
  6317. },
  6318. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6319. return cli.Patch("/test", body, "text/plain", progress_callback);
  6320. },
  6321. "patch test data for upload progress");
  6322. }
  6323. // Helper function for content provider upload progress tests
  6324. template <typename SetupHandler, typename ClientCall>
  6325. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6326. ClientCall &&client_call) {
  6327. Server svr;
  6328. setup_handler(svr);
  6329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6330. auto se = detail::scope_exit([&] {
  6331. svr.stop();
  6332. t.join();
  6333. });
  6334. svr.wait_until_ready();
  6335. Client cli(HOST, PORT);
  6336. vector<uint64_t> progress_values;
  6337. auto res =
  6338. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6339. progress_values.push_back(current);
  6340. return true;
  6341. });
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(200, res->status);
  6344. EXPECT_FALSE(progress_values.empty());
  6345. }
  6346. TEST(UploadProgressTest, PostContentProviderProgress) {
  6347. TestContentProviderUploadProgress(
  6348. [](Server &svr) {
  6349. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6350. res.set_content("provider received", "text/plain");
  6351. });
  6352. },
  6353. [](Client &cli, UploadProgress progress_callback) {
  6354. return cli.Post(
  6355. "/test", 10,
  6356. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6357. sink.os << "test data";
  6358. return true;
  6359. },
  6360. "text/plain", progress_callback);
  6361. });
  6362. }
  6363. // Helper function for multipart upload progress tests
  6364. template <typename SetupHandler, typename ClientCall>
  6365. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6366. ClientCall &&client_call,
  6367. const string &endpoint) {
  6368. Server svr;
  6369. setup_handler(svr);
  6370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6371. auto se = detail::scope_exit([&] {
  6372. svr.stop();
  6373. t.join();
  6374. });
  6375. svr.wait_until_ready();
  6376. Client cli(HOST, PORT);
  6377. vector<uint64_t> progress_values;
  6378. UploadFormDataItems items = {
  6379. {"field1", "value1", "", ""},
  6380. {"field2", "longer value for progress tracking test", "", ""},
  6381. {"file1", "file content data for upload progress", "test.txt",
  6382. "text/plain"}};
  6383. auto res = client_call(cli, endpoint, items,
  6384. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6385. progress_values.push_back(current);
  6386. return true;
  6387. });
  6388. ASSERT_TRUE(res);
  6389. EXPECT_EQ(200, res->status);
  6390. EXPECT_FALSE(progress_values.empty());
  6391. }
  6392. TEST(UploadProgressTest, PostMultipartProgress) {
  6393. TestMultipartUploadProgress(
  6394. [](Server &svr) {
  6395. svr.Post("/multipart", [](const Request &req, Response &res) {
  6396. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6397. res.set_content("multipart received", "text/plain");
  6398. });
  6399. },
  6400. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6401. UploadProgress progress_callback) {
  6402. return cli.Post(endpoint, items, progress_callback);
  6403. },
  6404. "/multipart");
  6405. }
  6406. // Helper function for basic download progress tests
  6407. template <typename SetupHandler, typename ClientCall>
  6408. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6409. ClientCall &&client_call, const string &endpoint,
  6410. size_t expected_content_size) {
  6411. Server svr;
  6412. setup_handler(svr);
  6413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6414. auto se = detail::scope_exit([&] {
  6415. svr.stop();
  6416. t.join();
  6417. });
  6418. svr.wait_until_ready();
  6419. Client cli(HOST, PORT);
  6420. vector<uint64_t> progress_values;
  6421. auto res = client_call(cli, endpoint,
  6422. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6423. progress_values.push_back(current);
  6424. return true;
  6425. });
  6426. ASSERT_TRUE(res);
  6427. EXPECT_EQ(200, res->status);
  6428. EXPECT_FALSE(progress_values.empty());
  6429. EXPECT_EQ(expected_content_size, res->body.size());
  6430. }
  6431. TEST(DownloadProgressTest, GetBasic) {
  6432. TestBasicDownloadProgress(
  6433. [](Server &svr) {
  6434. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6435. string content(1000, 'D');
  6436. res.set_content(content, "text/plain");
  6437. });
  6438. },
  6439. [](Client &cli, const string &endpoint,
  6440. DownloadProgress progress_callback) {
  6441. return cli.Get(endpoint, progress_callback);
  6442. },
  6443. "/download", 1000u);
  6444. }
  6445. // Helper function for content receiver download progress tests
  6446. template <typename SetupHandler, typename ClientCall>
  6447. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6448. ClientCall &&client_call,
  6449. const string &endpoint,
  6450. size_t expected_content_size) {
  6451. Server svr;
  6452. setup_handler(svr);
  6453. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6454. auto se = detail::scope_exit([&] {
  6455. svr.stop();
  6456. t.join();
  6457. });
  6458. svr.wait_until_ready();
  6459. Client cli(HOST, PORT);
  6460. vector<uint64_t> progress_values;
  6461. string received_body;
  6462. auto res = client_call(
  6463. cli, endpoint,
  6464. [&](const char *data, size_t data_length) -> bool {
  6465. received_body.append(data, data_length);
  6466. return true;
  6467. },
  6468. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6469. progress_values.push_back(current);
  6470. return true;
  6471. });
  6472. ASSERT_TRUE(res);
  6473. EXPECT_EQ(200, res->status);
  6474. EXPECT_FALSE(progress_values.empty());
  6475. EXPECT_EQ(expected_content_size, received_body.size());
  6476. EXPECT_TRUE(res->body.empty());
  6477. }
  6478. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6479. TestContentReceiverDownloadProgress(
  6480. [](Server &svr) {
  6481. svr.Get("/download-receiver",
  6482. [](const Request & /*req*/, Response &res) {
  6483. string content(2000, 'R');
  6484. res.set_content(content, "text/plain");
  6485. });
  6486. },
  6487. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6488. DownloadProgress progress_callback) {
  6489. return cli.Get(endpoint, content_receiver, progress_callback);
  6490. },
  6491. "/download-receiver", 2000u);
  6492. }
  6493. TEST(StreamingTest, NoContentLengthStreaming) {
  6494. Server svr;
  6495. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6496. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6497. if (offset < 6) {
  6498. sink.os << (offset < 3 ? "a" : "b");
  6499. } else {
  6500. sink.done();
  6501. }
  6502. return true;
  6503. });
  6504. });
  6505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6506. auto listen_se = detail::scope_exit([&] {
  6507. svr.stop();
  6508. listen_thread.join();
  6509. ASSERT_FALSE(svr.is_running());
  6510. });
  6511. svr.wait_until_ready();
  6512. Client client(HOST, PORT);
  6513. auto get_thread = std::thread([&client]() {
  6514. std::string s;
  6515. auto res =
  6516. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6517. s += std::string(data, len);
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("aaabbb", s);
  6523. });
  6524. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6525. // Give GET time to get a few messages.
  6526. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6527. }
  6528. TEST(MountTest, Unmount) {
  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.wait_until_ready();
  6537. Client cli("localhost", PORT);
  6538. svr.set_mount_point("/mount2", "./www2");
  6539. auto res = cli.Get("/");
  6540. ASSERT_TRUE(res);
  6541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6542. res = cli.Get("/mount2/dir/test.html");
  6543. ASSERT_TRUE(res);
  6544. EXPECT_EQ(StatusCode::OK_200, res->status);
  6545. svr.set_mount_point("/", "./www");
  6546. res = cli.Get("/dir/");
  6547. ASSERT_TRUE(res);
  6548. EXPECT_EQ(StatusCode::OK_200, res->status);
  6549. svr.remove_mount_point("/");
  6550. res = cli.Get("/dir/");
  6551. ASSERT_TRUE(res);
  6552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6553. svr.remove_mount_point("/mount2");
  6554. res = cli.Get("/mount2/dir/test.html");
  6555. ASSERT_TRUE(res);
  6556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6557. }
  6558. TEST(MountTest, Redicect) {
  6559. Server svr;
  6560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6561. auto se = detail::scope_exit([&] {
  6562. svr.stop();
  6563. listen_thread.join();
  6564. ASSERT_FALSE(svr.is_running());
  6565. });
  6566. svr.set_mount_point("/", "./www");
  6567. svr.wait_until_ready();
  6568. Client cli("localhost", PORT);
  6569. auto res = cli.Get("/dir/");
  6570. ASSERT_TRUE(res);
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. res = cli.Get("/dir");
  6573. ASSERT_TRUE(res);
  6574. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6575. res = cli.Get("/file");
  6576. ASSERT_TRUE(res);
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. res = cli.Get("/file/");
  6579. ASSERT_TRUE(res);
  6580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6581. cli.set_follow_location(true);
  6582. res = cli.Get("/dir");
  6583. ASSERT_TRUE(res);
  6584. EXPECT_EQ(StatusCode::OK_200, res->status);
  6585. }
  6586. TEST(MountTest, MultibytesPathName) {
  6587. Server svr;
  6588. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6589. auto se = detail::scope_exit([&] {
  6590. svr.stop();
  6591. listen_thread.join();
  6592. ASSERT_FALSE(svr.is_running());
  6593. });
  6594. svr.set_mount_point("/", "./www");
  6595. svr.wait_until_ready();
  6596. Client cli("localhost", PORT);
  6597. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6598. ASSERT_TRUE(res);
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6601. }
  6602. TEST(KeepAliveTest, ReadTimeout) {
  6603. Server svr;
  6604. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6605. std::this_thread::sleep_for(std::chrono::seconds(2));
  6606. res.set_content("a", "text/plain");
  6607. });
  6608. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6609. res.set_content("b", "text/plain");
  6610. });
  6611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6612. auto se = detail::scope_exit([&] {
  6613. svr.stop();
  6614. listen_thread.join();
  6615. ASSERT_FALSE(svr.is_running());
  6616. });
  6617. svr.wait_until_ready();
  6618. Client cli("localhost", PORT);
  6619. cli.set_keep_alive(true);
  6620. cli.set_read_timeout(std::chrono::seconds(1));
  6621. auto resa = cli.Get("/a");
  6622. ASSERT_FALSE(resa);
  6623. EXPECT_EQ(Error::Read, resa.error());
  6624. auto resb = cli.Get("/b");
  6625. ASSERT_TRUE(resb);
  6626. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6627. EXPECT_EQ("b", resb->body);
  6628. }
  6629. TEST(KeepAliveTest, MaxCount) {
  6630. size_t keep_alive_max_count = 3;
  6631. Server svr;
  6632. svr.set_keep_alive_max_count(keep_alive_max_count);
  6633. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6634. res.set_content("Hello World!", "text/plain");
  6635. });
  6636. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6637. auto se = detail::scope_exit([&] {
  6638. svr.stop();
  6639. listen_thread.join();
  6640. ASSERT_FALSE(svr.is_running());
  6641. });
  6642. svr.wait_until_ready();
  6643. Client cli(HOST, PORT);
  6644. cli.set_keep_alive(true);
  6645. for (size_t i = 0; i < 5; i++) {
  6646. auto result = cli.Get("/hi");
  6647. ASSERT_TRUE(result);
  6648. EXPECT_EQ(StatusCode::OK_200, result->status);
  6649. if (i == keep_alive_max_count - 1) {
  6650. EXPECT_EQ("close", result->get_header_value("Connection"));
  6651. } else {
  6652. EXPECT_FALSE(result->has_header("Connection"));
  6653. }
  6654. }
  6655. }
  6656. TEST(KeepAliveTest, Issue1041) {
  6657. Server svr;
  6658. svr.set_keep_alive_timeout(3);
  6659. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6660. res.set_content("Hello World!", "text/plain");
  6661. });
  6662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. Client cli(HOST, PORT);
  6670. cli.set_keep_alive(true);
  6671. auto result = cli.Get("/hi");
  6672. ASSERT_TRUE(result);
  6673. EXPECT_EQ(StatusCode::OK_200, result->status);
  6674. std::this_thread::sleep_for(std::chrono::seconds(5));
  6675. result = cli.Get("/hi");
  6676. ASSERT_TRUE(result);
  6677. EXPECT_EQ(StatusCode::OK_200, result->status);
  6678. }
  6679. TEST(KeepAliveTest, Issue1959) {
  6680. Server svr;
  6681. svr.set_keep_alive_timeout(5);
  6682. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6683. res.set_content("a", "text/plain");
  6684. });
  6685. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6686. auto se = detail::scope_exit([&] {
  6687. if (!svr.is_running()) return;
  6688. svr.stop();
  6689. listen_thread.join();
  6690. ASSERT_FALSE(svr.is_running());
  6691. });
  6692. svr.wait_until_ready();
  6693. Client cli("localhost", PORT);
  6694. cli.set_keep_alive(true);
  6695. using namespace std::chrono;
  6696. auto start = steady_clock::now();
  6697. cli.Get("/a");
  6698. svr.stop();
  6699. listen_thread.join();
  6700. auto end = steady_clock::now();
  6701. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6702. EXPECT_LT(elapsed, 5000);
  6703. }
  6704. #ifdef CPPHTTPLIB_SSL_ENABLED
  6705. TEST(KeepAliveTest, SSLClientReconnection) {
  6706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6707. ASSERT_TRUE(svr.is_valid());
  6708. svr.set_keep_alive_timeout(1);
  6709. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6710. res.set_content("Hello World!", "text/plain");
  6711. });
  6712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6713. auto se = detail::scope_exit([&] {
  6714. svr.stop();
  6715. listen_thread.join();
  6716. ASSERT_FALSE(svr.is_running());
  6717. });
  6718. svr.wait_until_ready();
  6719. SSLClient cli(HOST, PORT);
  6720. cli.enable_server_certificate_verification(false);
  6721. cli.set_keep_alive(true);
  6722. auto result = cli.Get("/hi");
  6723. ASSERT_TRUE(result);
  6724. EXPECT_EQ(StatusCode::OK_200, result->status);
  6725. result = cli.Get("/hi");
  6726. ASSERT_TRUE(result);
  6727. EXPECT_EQ(StatusCode::OK_200, result->status);
  6728. std::this_thread::sleep_for(std::chrono::seconds(2));
  6729. // Recoonect
  6730. result = cli.Get("/hi");
  6731. ASSERT_TRUE(result);
  6732. EXPECT_EQ(StatusCode::OK_200, result->status);
  6733. result = cli.Get("/hi");
  6734. ASSERT_TRUE(result);
  6735. EXPECT_EQ(StatusCode::OK_200, result->status);
  6736. }
  6737. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6739. ASSERT_TRUE(svr.is_valid());
  6740. svr.set_keep_alive_timeout(1);
  6741. std::string content = "reconnect";
  6742. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6743. res.set_content("Hello World!", "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. SSLClient cli(HOST, PORT);
  6753. cli.enable_server_certificate_verification(false);
  6754. cli.set_keep_alive(true);
  6755. auto result = cli.Post(
  6756. "/hi", content.size(),
  6757. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6758. sink.write(content.c_str(), content.size());
  6759. return true;
  6760. },
  6761. "text/plain");
  6762. ASSERT_TRUE(result);
  6763. EXPECT_EQ(200, result->status);
  6764. std::this_thread::sleep_for(std::chrono::seconds(2));
  6765. // Recoonect
  6766. result = cli.Post(
  6767. "/hi", content.size(),
  6768. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6769. sink.write(content.c_str(), content.size());
  6770. return true;
  6771. },
  6772. "text/plain");
  6773. ASSERT_TRUE(result);
  6774. EXPECT_EQ(200, result->status);
  6775. result = cli.Post(
  6776. "/hi", content.size(),
  6777. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6778. sink.write(content.c_str(), content.size());
  6779. return true;
  6780. },
  6781. "text/plain");
  6782. ASSERT_TRUE(result);
  6783. EXPECT_EQ(200, result->status);
  6784. }
  6785. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6786. using namespace httplib::tls;
  6787. {
  6788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6789. ASSERT_TRUE(svr.is_valid());
  6790. svr.Get("/sni", [&](const Request &req, Response &res) {
  6791. std::string expected = req.sni();
  6792. EXPECT_EQ(expected, req.get_param_value("expected"));
  6793. res.set_content("ok", "text/plain");
  6794. });
  6795. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6796. auto se = detail::scope_exit([&] {
  6797. svr.stop();
  6798. listen_thread.join();
  6799. ASSERT_FALSE(svr.is_running());
  6800. });
  6801. svr.wait_until_ready();
  6802. {
  6803. SSLClient cli("localhost", PORT);
  6804. cli.enable_server_certificate_verification(false);
  6805. auto res = cli.Get("/sni?expected=localhost");
  6806. ASSERT_TRUE(res);
  6807. }
  6808. {
  6809. SSLClient cli("::1", PORT);
  6810. cli.enable_server_certificate_verification(false);
  6811. auto res = cli.Get("/sni?expected=");
  6812. // NOTE: This may fail if the server is listening on IPv4 only
  6813. // (e.g., when localhost resolves to 127.0.0.1 only)
  6814. if (res) {
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. } else {
  6817. EXPECT_EQ(Error::Connection, res.error());
  6818. }
  6819. }
  6820. }
  6821. }
  6822. #endif
  6823. TEST(ClientProblemDetectionTest, ContentProvider) {
  6824. Server svr;
  6825. size_t content_length = 1024 * 1024;
  6826. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6827. res.set_content_provider(
  6828. content_length, "text/plain",
  6829. [&](size_t offset, size_t length, DataSink &sink) {
  6830. auto out_len = std::min(length, static_cast<size_t>(1024));
  6831. std::string out(out_len, '@');
  6832. sink.write(out.data(), out_len);
  6833. return offset < 4096;
  6834. },
  6835. [](bool success) { ASSERT_FALSE(success); });
  6836. });
  6837. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6838. res.set_content_provider(
  6839. 0, "text/plain",
  6840. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6841. EXPECT_TRUE(false);
  6842. return true;
  6843. },
  6844. [](bool success) { ASSERT_FALSE(success); });
  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. {
  6855. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6856. size_t /*data_length*/) { return false; });
  6857. ASSERT_FALSE(res);
  6858. }
  6859. {
  6860. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6861. size_t /*data_length*/) { return false; });
  6862. ASSERT_TRUE(res);
  6863. }
  6864. }
  6865. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6866. Server svr;
  6867. svr.set_error_handler([](Request const &, Response &res) -> void {
  6868. res.set_chunked_content_provider(
  6869. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6870. sink.os << "hello";
  6871. sink.os << "world";
  6872. sink.done();
  6873. return true;
  6874. });
  6875. });
  6876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6877. auto se = detail::scope_exit([&] {
  6878. svr.stop();
  6879. listen_thread.join();
  6880. ASSERT_FALSE(svr.is_running());
  6881. });
  6882. svr.wait_until_ready();
  6883. Client cli("localhost", PORT);
  6884. auto res = cli.Get("/");
  6885. ASSERT_TRUE(res);
  6886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6887. EXPECT_EQ("helloworld", res->body);
  6888. }
  6889. TEST(LongPollingTest, ClientCloseDetection) {
  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. auto count = 10;
  6897. while (count > 0 && sink.is_writable()) {
  6898. this_thread::sleep_for(chrono::milliseconds(10));
  6899. count--;
  6900. }
  6901. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6902. return true;
  6903. });
  6904. });
  6905. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6906. auto se = detail::scope_exit([&] {
  6907. svr.stop();
  6908. listen_thread.join();
  6909. ASSERT_FALSE(svr.is_running());
  6910. });
  6911. svr.wait_until_ready();
  6912. Client cli("localhost", PORT);
  6913. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6914. EXPECT_EQ("hello", string(data, data_length));
  6915. return false; // close the socket immediately.
  6916. });
  6917. ASSERT_FALSE(res);
  6918. }
  6919. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6920. Server svr;
  6921. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6922. res.set_chunked_content_provider(
  6923. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6924. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6925. sink.os << "hello";
  6926. EXPECT_TRUE(sink.os.good());
  6927. // Wait for the client to close the connection
  6928. auto count = 10;
  6929. while (count > 0 && sink.is_writable()) {
  6930. this_thread::sleep_for(chrono::milliseconds(10));
  6931. count--;
  6932. }
  6933. // After client disconnect, write repeatedly until the socket
  6934. // write actually fails (small writes may be absorbed by the
  6935. // kernel buffer)
  6936. std::string chunk(1024, 'x');
  6937. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6938. sink.os << chunk;
  6939. }
  6940. EXPECT_TRUE(sink.os.fail());
  6941. return true;
  6942. });
  6943. });
  6944. auto port = svr.bind_to_any_port("localhost");
  6945. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6946. auto se = detail::scope_exit([&] {
  6947. svr.stop();
  6948. listen_thread.join();
  6949. ASSERT_FALSE(svr.is_running());
  6950. });
  6951. svr.wait_until_ready();
  6952. Client cli("localhost", port);
  6953. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6954. EXPECT_EQ("hello", string(data, data_length));
  6955. return false; // close the socket immediately.
  6956. });
  6957. ASSERT_FALSE(res);
  6958. }
  6959. TEST(GetWithParametersTest, GetWithParameters) {
  6960. Server svr;
  6961. svr.Get("/", [&](const Request &req, Response &) {
  6962. EXPECT_EQ("world", req.get_param_value("hello"));
  6963. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6964. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6965. });
  6966. svr.Get("/params", [&](const Request &req, Response &) {
  6967. EXPECT_EQ("world", req.get_param_value("hello"));
  6968. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6969. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6970. });
  6971. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6972. EXPECT_EQ("resource-id", req.matches[1]);
  6973. EXPECT_EQ("foo", req.get_param_value("param1"));
  6974. EXPECT_EQ("bar", req.get_param_value("param2"));
  6975. });
  6976. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6977. EXPECT_EQ("user-id", req.path_params.at("id"));
  6978. EXPECT_EQ("foo", req.get_param_value("param1"));
  6979. EXPECT_EQ("bar", req.get_param_value("param2"));
  6980. });
  6981. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6982. auto se = detail::scope_exit([&] {
  6983. svr.stop();
  6984. listen_thread.join();
  6985. ASSERT_FALSE(svr.is_running());
  6986. });
  6987. svr.wait_until_ready();
  6988. {
  6989. Client cli(HOST, PORT);
  6990. Params params;
  6991. params.emplace("hello", "world");
  6992. params.emplace("hello2", "world2");
  6993. params.emplace("hello3", "world3");
  6994. auto res = cli.Get("/", params, Headers{});
  6995. ASSERT_TRUE(res);
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. {
  6999. Client cli(HOST, PORT);
  7000. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7001. ASSERT_TRUE(res);
  7002. EXPECT_EQ(StatusCode::OK_200, res->status);
  7003. }
  7004. {
  7005. Client cli(HOST, PORT);
  7006. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. }
  7010. {
  7011. Client cli(HOST, PORT);
  7012. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7013. ASSERT_TRUE(res);
  7014. EXPECT_EQ(StatusCode::OK_200, res->status);
  7015. }
  7016. }
  7017. TEST(GetWithParametersTest, GetWithParameters2) {
  7018. Server svr;
  7019. svr.Get("/", [&](const Request &req, Response &res) {
  7020. auto text = req.get_param_value("hello");
  7021. res.set_content(text, "text/plain");
  7022. });
  7023. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7024. auto se = detail::scope_exit([&] {
  7025. svr.stop();
  7026. listen_thread.join();
  7027. ASSERT_FALSE(svr.is_running());
  7028. });
  7029. svr.wait_until_ready();
  7030. Client cli("localhost", PORT);
  7031. Params params;
  7032. params.emplace("hello", "world");
  7033. std::string body;
  7034. auto res = cli.Get("/", params, Headers{},
  7035. [&](const char *data, size_t data_length) {
  7036. body.append(data, data_length);
  7037. return true;
  7038. });
  7039. ASSERT_TRUE(res);
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. EXPECT_EQ("world", body);
  7042. }
  7043. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7044. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7045. auto host = "httpcan.org";
  7046. auto path = std::string{"/range/32"};
  7047. #else
  7048. auto host = "nghttp2.org";
  7049. auto path = std::string{"/httpbin/range/32"};
  7050. #endif
  7051. #ifdef CPPHTTPLIB_SSL_ENABLED
  7052. SSLClient cli(host);
  7053. #else
  7054. Client cli(host);
  7055. #endif
  7056. cli.set_default_headers({make_range_header({{1, 10}})});
  7057. cli.set_connection_timeout(5);
  7058. {
  7059. auto res = cli.Get(path);
  7060. ASSERT_TRUE(res);
  7061. EXPECT_EQ("bcdefghijk", res->body);
  7062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7063. }
  7064. {
  7065. auto res = cli.Get(path);
  7066. ASSERT_TRUE(res);
  7067. EXPECT_EQ("bcdefghijk", res->body);
  7068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7069. }
  7070. }
  7071. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7072. Server svr;
  7073. svr.set_default_headers({{"Hello", "World"}});
  7074. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7075. res.set_content("ok", "text/plain");
  7076. });
  7077. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7078. auto se = detail::scope_exit([&] {
  7079. svr.stop();
  7080. listen_thread.join();
  7081. ASSERT_FALSE(svr.is_running());
  7082. });
  7083. svr.wait_until_ready();
  7084. Client cli("localhost", PORT);
  7085. auto res = cli.Get("/");
  7086. ASSERT_TRUE(res);
  7087. EXPECT_EQ(StatusCode::OK_200, res->status);
  7088. EXPECT_EQ("ok", res->body);
  7089. EXPECT_EQ("World", res->get_header_value("Hello"));
  7090. }
  7091. #ifdef CPPHTTPLIB_SSL_ENABLED
  7092. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7094. ASSERT_TRUE(svr.is_valid());
  7095. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7096. std::this_thread::sleep_for(std::chrono::seconds(2));
  7097. res.set_content("a", "text/plain");
  7098. });
  7099. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7100. res.set_content("b", "text/plain");
  7101. });
  7102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7103. auto se = detail::scope_exit([&] {
  7104. svr.stop();
  7105. listen_thread.join();
  7106. ASSERT_FALSE(svr.is_running());
  7107. });
  7108. svr.wait_until_ready();
  7109. SSLClient cli("localhost", PORT);
  7110. cli.enable_server_certificate_verification(false);
  7111. cli.set_keep_alive(true);
  7112. cli.set_read_timeout(std::chrono::seconds(1));
  7113. auto resa = cli.Get("/a");
  7114. ASSERT_TRUE(!resa);
  7115. EXPECT_EQ(Error::Read, resa.error());
  7116. auto resb = cli.Get("/b");
  7117. ASSERT_TRUE(resb);
  7118. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7119. EXPECT_EQ("b", resb->body);
  7120. }
  7121. #endif
  7122. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7123. protected:
  7124. ServerTestWithAI_PASSIVE()
  7125. : cli_(HOST, PORT)
  7126. #ifdef CPPHTTPLIB_SSL_ENABLED
  7127. ,
  7128. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7129. #endif
  7130. {
  7131. #ifdef CPPHTTPLIB_SSL_ENABLED
  7132. cli_.enable_server_certificate_verification(false);
  7133. #endif
  7134. }
  7135. virtual void SetUp() {
  7136. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7137. res.set_content("Hello World!", "text/plain");
  7138. });
  7139. t_ = thread(
  7140. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7141. svr_.wait_until_ready();
  7142. }
  7143. virtual void TearDown() {
  7144. svr_.stop();
  7145. t_.join();
  7146. }
  7147. #ifdef CPPHTTPLIB_SSL_ENABLED
  7148. SSLClient cli_;
  7149. SSLServer svr_;
  7150. #else
  7151. Client cli_;
  7152. Server svr_;
  7153. #endif
  7154. thread t_;
  7155. };
  7156. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7157. auto res = cli_.Get("/hi");
  7158. ASSERT_TRUE(res);
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7161. EXPECT_EQ("Hello World!", res->body);
  7162. }
  7163. class ServerUpDownTest : public ::testing::Test {
  7164. protected:
  7165. ServerUpDownTest() : cli_(HOST, PORT) {}
  7166. virtual void SetUp() {
  7167. t_ = thread([&]() {
  7168. svr_.bind_to_any_port(HOST);
  7169. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7170. ASSERT_TRUE(svr_.listen_after_bind());
  7171. });
  7172. svr_.wait_until_ready();
  7173. }
  7174. virtual void TearDown() {
  7175. svr_.stop();
  7176. t_.join();
  7177. }
  7178. Client cli_;
  7179. Server svr_;
  7180. thread t_;
  7181. };
  7182. TEST_F(ServerUpDownTest, QuickStartStop) {
  7183. // Should not crash, especially when run with
  7184. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7185. }
  7186. class PayloadMaxLengthTest : public ::testing::Test {
  7187. protected:
  7188. PayloadMaxLengthTest()
  7189. : cli_(HOST, PORT)
  7190. #ifdef CPPHTTPLIB_SSL_ENABLED
  7191. ,
  7192. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7193. #endif
  7194. {
  7195. #ifdef CPPHTTPLIB_SSL_ENABLED
  7196. cli_.enable_server_certificate_verification(false);
  7197. #endif
  7198. }
  7199. virtual void SetUp() {
  7200. svr_.set_payload_max_length(8);
  7201. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7202. res.set_content("test", "text/plain");
  7203. });
  7204. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7205. svr_.wait_until_ready();
  7206. }
  7207. virtual void TearDown() {
  7208. svr_.stop();
  7209. t_.join();
  7210. }
  7211. #ifdef CPPHTTPLIB_SSL_ENABLED
  7212. SSLClient cli_;
  7213. SSLServer svr_;
  7214. #else
  7215. Client cli_;
  7216. Server svr_;
  7217. #endif
  7218. thread t_;
  7219. };
  7220. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7221. auto res = cli_.Post("/test", "123456789", "text/plain");
  7222. ASSERT_TRUE(res);
  7223. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7224. res = cli_.Post("/test", "12345678", "text/plain");
  7225. ASSERT_TRUE(res);
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. }
  7228. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7229. // Test chunked encoding with payload exceeding the 8-byte limit
  7230. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7231. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7232. ASSERT_TRUE(res);
  7233. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7234. }
  7235. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7236. // Test chunked encoding with payload within the 8-byte limit
  7237. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7238. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7239. ASSERT_TRUE(res);
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7243. // Test using send_request to send chunked data exceeding payload limit
  7244. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7245. "Host: " +
  7246. std::string(HOST) + ":" + std::to_string(PORT) +
  7247. "\r\n"
  7248. "Transfer-Encoding: chunked\r\n"
  7249. "Connection: close\r\n"
  7250. "\r\n"
  7251. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7252. "0123456789\r\n"
  7253. "0\r\n" // End chunk
  7254. "\r\n";
  7255. std::string response;
  7256. bool result = send_request(1, chunked_request, &response);
  7257. if (!result) {
  7258. // If send_request fails, it might be because the server closed the
  7259. // connection due to payload limit enforcement, which is acceptable
  7260. SUCCEED()
  7261. << "Server rejected oversized chunked request (connection closed)";
  7262. } else {
  7263. // If we got a response, check if it's an error response or connection was
  7264. // closed early Short response length indicates connection was closed due to
  7265. // payload limit
  7266. if (response.length() <= 10) {
  7267. SUCCEED() << "Server closed connection for oversized chunked request";
  7268. } else {
  7269. // Check for error status codes
  7270. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7271. response.find("Payload Too Large") != std::string::npos ||
  7272. response.find("400") != std::string::npos);
  7273. }
  7274. }
  7275. }
  7276. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7277. // Test request without Content-Length header exceeding payload limit
  7278. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7279. "Host: " +
  7280. std::string(HOST) + ":" +
  7281. std::to_string(PORT) +
  7282. "\r\n"
  7283. "Connection: close\r\n"
  7284. "\r\n";
  7285. // Add payload exceeding the 8-byte limit
  7286. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7287. request_without_content_length += large_payload;
  7288. std::string response;
  7289. bool result = send_request(1, request_without_content_length, &response);
  7290. if (!result) {
  7291. // If send_request fails, server likely closed connection due to payload
  7292. // limit
  7293. SUCCEED() << "Server rejected oversized request without Content-Length "
  7294. "(connection closed)";
  7295. } else {
  7296. // Check if server responded with error or closed connection early
  7297. if (response.length() <= 10) {
  7298. SUCCEED() << "Server closed connection for oversized request without "
  7299. "Content-Length";
  7300. } else {
  7301. // Check for error status codes
  7302. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7303. response.find("Payload Too Large") != std::string::npos ||
  7304. response.find("400") != std::string::npos);
  7305. }
  7306. }
  7307. }
  7308. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7309. // Test request without Content-Length header within payload limit
  7310. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7311. "Host: " +
  7312. std::string(HOST) + ":" +
  7313. std::to_string(PORT) +
  7314. "\r\n"
  7315. "Connection: close\r\n"
  7316. "\r\n";
  7317. // Add payload within the 8-byte limit
  7318. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7319. request_without_content_length += small_payload;
  7320. std::string response;
  7321. bool result = send_request(1, request_without_content_length, &response);
  7322. // For requests without Content-Length, the server may have different behavior
  7323. // The key is that it should not reject due to payload limit for small
  7324. // payloads
  7325. if (result) {
  7326. // Check for any HTTP response (success or error, but not connection closed)
  7327. if (response.length() > 10) {
  7328. SUCCEED()
  7329. << "Server processed request without Content-Length within limit";
  7330. } else {
  7331. // Short response might indicate connection closed, which is acceptable
  7332. SUCCEED() << "Server closed connection for request without "
  7333. "Content-Length (acceptable behavior)";
  7334. }
  7335. } else {
  7336. // Connection failure might be due to protocol requirements
  7337. SUCCEED() << "Connection issue with request without Content-Length "
  7338. "(environment-specific)";
  7339. }
  7340. }
  7341. class LargePayloadMaxLengthTest : public ::testing::Test {
  7342. protected:
  7343. LargePayloadMaxLengthTest()
  7344. : cli_(HOST, PORT)
  7345. #ifdef CPPHTTPLIB_SSL_ENABLED
  7346. ,
  7347. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7348. #endif
  7349. {
  7350. #ifdef CPPHTTPLIB_SSL_ENABLED
  7351. cli_.enable_server_certificate_verification(false);
  7352. #endif
  7353. }
  7354. virtual void SetUp() {
  7355. // Set 10MB payload limit
  7356. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7357. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7358. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7359. res.set_content("Large payload test", "text/plain");
  7360. });
  7361. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7362. svr_.wait_until_ready();
  7363. }
  7364. virtual void TearDown() {
  7365. svr_.stop();
  7366. t_.join();
  7367. }
  7368. #ifdef CPPHTTPLIB_SSL_ENABLED
  7369. SSLClient cli_;
  7370. SSLServer svr_;
  7371. #else
  7372. Client cli_;
  7373. Server svr_;
  7374. #endif
  7375. thread t_;
  7376. };
  7377. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7378. // Test chunked encoding with payload within 10MB limit
  7379. std::string medium_payload(5 * 1024 * 1024,
  7380. 'A'); // 5MB payload, within 10MB limit
  7381. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7382. ASSERT_TRUE(res);
  7383. EXPECT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7386. // Test chunked encoding with payload exceeding 10MB limit
  7387. std::string large_payload(12 * 1024 * 1024,
  7388. 'B'); // 12MB payload, exceeds 10MB limit
  7389. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7390. // Server may either return 413 or close the connection
  7391. if (res) {
  7392. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7393. } else {
  7394. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7395. }
  7396. }
  7397. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7398. // Test request without Content-Length header within 10MB limit
  7399. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7400. "Host: " +
  7401. std::string(HOST) + ":" +
  7402. std::to_string(PORT) +
  7403. "\r\n"
  7404. "Connection: close\r\n"
  7405. "\r\n";
  7406. // Add 1MB payload (within 10MB limit)
  7407. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7408. request_without_content_length += medium_payload;
  7409. std::string response;
  7410. bool result = send_request(5, request_without_content_length, &response);
  7411. if (result) {
  7412. // Should get a proper HTTP response for payloads within limit
  7413. if (response.length() > 10) {
  7414. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7415. "10MB limit";
  7416. } else {
  7417. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7418. "Content-Length)";
  7419. }
  7420. } else {
  7421. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7422. }
  7423. }
  7424. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7425. // Test request without Content-Length header exceeding 10MB limit
  7426. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7427. "Host: " +
  7428. std::string(HOST) + ":" +
  7429. std::to_string(PORT) +
  7430. "\r\n"
  7431. "Connection: close\r\n"
  7432. "\r\n";
  7433. // Add 12MB payload (exceeds 10MB limit)
  7434. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7435. request_without_content_length += large_payload;
  7436. std::string response;
  7437. bool result = send_request(10, request_without_content_length, &response);
  7438. if (!result) {
  7439. // Server should close connection due to payload limit
  7440. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7441. "(connection closed)";
  7442. } else {
  7443. // Check for error response
  7444. if (response.length() <= 10) {
  7445. SUCCEED()
  7446. << "Server closed connection for 12MB request exceeding 10MB limit";
  7447. } else {
  7448. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7449. response.find("Payload Too Large") != std::string::npos ||
  7450. response.find("400") != std::string::npos);
  7451. }
  7452. }
  7453. }
  7454. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7455. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7456. // path.
  7457. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7458. Server svr;
  7459. const size_t LIMIT = 64 * 1024; // 64KB
  7460. svr.set_payload_max_length(LIMIT);
  7461. size_t total = 0;
  7462. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7463. const ContentReader &content_reader) {
  7464. content_reader([&](const char * /*data*/, size_t len) {
  7465. total += len;
  7466. return true;
  7467. });
  7468. res.status = 200;
  7469. res.set_content("stream_ok", "text/plain");
  7470. });
  7471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7472. auto se = detail::scope_exit([&] {
  7473. svr.stop();
  7474. thread.join();
  7475. ASSERT_FALSE(svr.is_running());
  7476. });
  7477. svr.wait_until_ready();
  7478. // Prepare 256KB raw data and gzip-compress it
  7479. std::string raw(256 * 1024, 'A');
  7480. std::string gz;
  7481. {
  7482. z_stream zs{};
  7483. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7484. Z_DEFAULT_STRATEGY);
  7485. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7486. zs.avail_in = static_cast<uInt>(raw.size());
  7487. char outbuf[4096];
  7488. int ret;
  7489. do {
  7490. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7491. zs.avail_out = sizeof(outbuf);
  7492. ret = deflate(&zs, Z_FINISH);
  7493. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7494. } while (ret != Z_STREAM_END);
  7495. deflateEnd(&zs);
  7496. }
  7497. Client cli(HOST, PORT);
  7498. cli.set_connection_timeout(std::chrono::seconds(5));
  7499. Headers headers = {{"Content-Encoding", "gzip"}};
  7500. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7501. "application/octet-stream");
  7502. ASSERT_TRUE(res);
  7503. // Server must reject oversized decompressed payloads with 413.
  7504. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7505. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7506. EXPECT_LE(total, LIMIT);
  7507. }
  7508. #endif
  7509. // Regression test for DoS vulnerability: a malicious server sending a response
  7510. // without Content-Length header must not cause unbounded memory consumption on
  7511. // the client side. The client should stop reading after a reasonable limit,
  7512. // similar to the server-side set_payload_max_length protection.
  7513. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7514. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7515. #ifndef _WIN32
  7516. signal(SIGPIPE, SIG_IGN);
  7517. #endif
  7518. auto server_thread = std::thread([] {
  7519. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7521. default_socket_options(srv);
  7522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7524. sockaddr_in addr{};
  7525. addr.sin_family = AF_INET;
  7526. addr.sin_port = htons(PORT + 2);
  7527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7528. int opt = 1;
  7529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7530. #ifdef _WIN32
  7531. reinterpret_cast<const char *>(&opt),
  7532. #else
  7533. &opt,
  7534. #endif
  7535. sizeof(opt));
  7536. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7537. ::listen(srv, 1);
  7538. sockaddr_in cli_addr{};
  7539. socklen_t cli_len = sizeof(cli_addr);
  7540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7541. if (cli != INVALID_SOCKET) {
  7542. char buf[4096];
  7543. ::recv(cli, buf, sizeof(buf), 0);
  7544. // Malicious response: no Content-Length, no chunked encoding
  7545. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7546. "Connection: close\r\n"
  7547. "\r\n";
  7548. ::send(cli,
  7549. #ifdef _WIN32
  7550. static_cast<const char *>(response_header.c_str()),
  7551. static_cast<int>(response_header.size()),
  7552. #else
  7553. response_header.c_str(), response_header.size(),
  7554. #endif
  7555. 0);
  7556. // Send 10MB of data
  7557. std::string chunk(64 * 1024, 'A');
  7558. size_t total_sent = 0;
  7559. while (total_sent < MALICIOUS_DATA_SIZE) {
  7560. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7561. auto sent = ::send(cli,
  7562. #ifdef _WIN32
  7563. static_cast<const char *>(chunk.c_str()),
  7564. static_cast<int>(to_send),
  7565. #else
  7566. chunk.c_str(), to_send,
  7567. #endif
  7568. 0);
  7569. if (sent <= 0) break;
  7570. total_sent += static_cast<size_t>(sent);
  7571. }
  7572. detail::close_socket(cli);
  7573. }
  7574. detail::close_socket(srv);
  7575. });
  7576. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7577. size_t total_read = 0;
  7578. {
  7579. Client cli("127.0.0.1", PORT + 2);
  7580. cli.set_read_timeout(5, 0);
  7581. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7582. auto stream = cli.open_stream("GET", "/malicious");
  7583. ASSERT_TRUE(stream.is_valid());
  7584. char buffer[64 * 1024];
  7585. ssize_t n;
  7586. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7587. total_read += static_cast<size_t>(n);
  7588. }
  7589. } // StreamHandle and Client destroyed here, closing the socket
  7590. server_thread.join();
  7591. // With set_payload_max_length, the client must stop reading before consuming
  7592. // all 10MB. The read loop should be cut off at or near the configured limit.
  7593. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7594. << "Client read " << total_read << " bytes, exceeding the configured "
  7595. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7596. }
  7597. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7598. // the entire response body without truncation.
  7599. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7600. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7601. #ifndef _WIN32
  7602. signal(SIGPIPE, SIG_IGN);
  7603. #endif
  7604. auto server_thread = std::thread([] {
  7605. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7606. default_socket_options(srv);
  7607. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7608. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7609. sockaddr_in addr{};
  7610. addr.sin_family = AF_INET;
  7611. addr.sin_port = htons(PORT + 2);
  7612. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7613. int opt = 1;
  7614. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7615. #ifdef _WIN32
  7616. reinterpret_cast<const char *>(&opt),
  7617. #else
  7618. &opt,
  7619. #endif
  7620. sizeof(opt));
  7621. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7622. ::listen(srv, 1);
  7623. sockaddr_in cli_addr{};
  7624. socklen_t cli_len = sizeof(cli_addr);
  7625. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7626. if (cli != INVALID_SOCKET) {
  7627. char buf[4096];
  7628. ::recv(cli, buf, sizeof(buf), 0);
  7629. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7630. "Connection: close\r\n"
  7631. "\r\n";
  7632. ::send(cli,
  7633. #ifdef _WIN32
  7634. static_cast<const char *>(response_header.c_str()),
  7635. static_cast<int>(response_header.size()),
  7636. #else
  7637. response_header.c_str(), response_header.size(),
  7638. #endif
  7639. 0);
  7640. std::string chunk(64 * 1024, 'A');
  7641. size_t total_sent = 0;
  7642. while (total_sent < DATA_SIZE) {
  7643. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7644. auto sent = ::send(cli,
  7645. #ifdef _WIN32
  7646. static_cast<const char *>(chunk.c_str()),
  7647. static_cast<int>(to_send),
  7648. #else
  7649. chunk.c_str(), to_send,
  7650. #endif
  7651. 0);
  7652. if (sent <= 0) break;
  7653. total_sent += static_cast<size_t>(sent);
  7654. }
  7655. #ifdef _WIN32
  7656. ::shutdown(cli, SD_SEND);
  7657. #else
  7658. ::shutdown(cli, SHUT_WR);
  7659. #endif
  7660. // Drain until the client closes its end, ensuring all data is delivered
  7661. char drain[1024];
  7662. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7663. detail::close_socket(cli);
  7664. }
  7665. detail::close_socket(srv);
  7666. });
  7667. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7668. size_t total_read = 0;
  7669. {
  7670. Client cli("127.0.0.1", PORT + 2);
  7671. cli.set_read_timeout(5, 0);
  7672. cli.set_payload_max_length(0); // 0 means no limit
  7673. auto stream = cli.open_stream("GET", "/data");
  7674. ASSERT_TRUE(stream.is_valid());
  7675. char buffer[64 * 1024];
  7676. ssize_t n;
  7677. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7678. total_read += static_cast<size_t>(n);
  7679. }
  7680. }
  7681. server_thread.join();
  7682. EXPECT_EQ(total_read, DATA_SIZE)
  7683. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7684. << " bytes without truncation, but only read " << total_read << " bytes.";
  7685. }
  7686. // Verify that content_receiver bypasses the default payload_max_length,
  7687. // allowing streaming downloads larger than 100MB without requiring an explicit
  7688. // set_payload_max_length call.
  7689. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7690. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7691. #ifndef _WIN32
  7692. signal(SIGPIPE, SIG_IGN);
  7693. #endif
  7694. auto server_thread = std::thread([] {
  7695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7696. default_socket_options(srv);
  7697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7699. sockaddr_in addr{};
  7700. addr.sin_family = AF_INET;
  7701. addr.sin_port = htons(PORT + 2);
  7702. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7703. int opt = 1;
  7704. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7705. #ifdef _WIN32
  7706. reinterpret_cast<const char *>(&opt),
  7707. #else
  7708. &opt,
  7709. #endif
  7710. sizeof(opt));
  7711. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7712. ::listen(srv, 1);
  7713. sockaddr_in cli_addr{};
  7714. socklen_t cli_len = sizeof(cli_addr);
  7715. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7716. if (cli != INVALID_SOCKET) {
  7717. char buf[4096];
  7718. ::recv(cli, buf, sizeof(buf), 0);
  7719. // Response with Content-Length larger than default 100MB limit
  7720. auto content_length = std::to_string(DATA_SIZE);
  7721. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7722. "Content-Length: " +
  7723. content_length +
  7724. "\r\n"
  7725. "Connection: close\r\n"
  7726. "\r\n";
  7727. ::send(cli,
  7728. #ifdef _WIN32
  7729. static_cast<const char *>(response_header.c_str()),
  7730. static_cast<int>(response_header.size()),
  7731. #else
  7732. response_header.c_str(), response_header.size(),
  7733. #endif
  7734. 0);
  7735. std::string chunk(64 * 1024, 'A');
  7736. size_t total_sent = 0;
  7737. while (total_sent < DATA_SIZE) {
  7738. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7739. auto sent = ::send(cli,
  7740. #ifdef _WIN32
  7741. static_cast<const char *>(chunk.c_str()),
  7742. static_cast<int>(to_send),
  7743. #else
  7744. chunk.c_str(), to_send,
  7745. #endif
  7746. 0);
  7747. if (sent <= 0) break;
  7748. total_sent += static_cast<size_t>(sent);
  7749. }
  7750. detail::close_socket(cli);
  7751. }
  7752. detail::close_socket(srv);
  7753. });
  7754. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7755. size_t total_received = 0;
  7756. {
  7757. Client cli("127.0.0.1", PORT + 2);
  7758. cli.set_read_timeout(10, 0);
  7759. // Do NOT call set_payload_max_length — use the default 100MB limit
  7760. auto res =
  7761. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7762. total_received += data_length;
  7763. return true;
  7764. });
  7765. ASSERT_TRUE(res);
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. server_thread.join();
  7769. EXPECT_EQ(total_received, DATA_SIZE)
  7770. << "With content_receiver, the client should read all " << DATA_SIZE
  7771. << " bytes despite the default 100MB payload_max_length, but only read "
  7772. << total_received << " bytes.";
  7773. }
  7774. // Verify that an explicit set_payload_max_length smaller than the response is
  7775. // enforced even when a content_receiver is used.
  7776. TEST(ClientVulnerabilityTest,
  7777. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7778. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7779. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7780. #ifndef _WIN32
  7781. signal(SIGPIPE, SIG_IGN);
  7782. #endif
  7783. auto server_thread = std::thread([] {
  7784. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7785. default_socket_options(srv);
  7786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7788. sockaddr_in addr{};
  7789. addr.sin_family = AF_INET;
  7790. addr.sin_port = htons(PORT + 2);
  7791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7792. int opt = 1;
  7793. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7794. #ifdef _WIN32
  7795. reinterpret_cast<const char *>(&opt),
  7796. #else
  7797. &opt,
  7798. #endif
  7799. sizeof(opt));
  7800. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7801. ::listen(srv, 1);
  7802. sockaddr_in cli_addr{};
  7803. socklen_t cli_len = sizeof(cli_addr);
  7804. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7805. if (cli != INVALID_SOCKET) {
  7806. char buf[4096];
  7807. ::recv(cli, buf, sizeof(buf), 0);
  7808. auto content_length = std::to_string(DATA_SIZE);
  7809. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7810. "Content-Length: " +
  7811. content_length +
  7812. "\r\n"
  7813. "Connection: close\r\n"
  7814. "\r\n";
  7815. ::send(cli,
  7816. #ifdef _WIN32
  7817. static_cast<const char *>(response_header.c_str()),
  7818. static_cast<int>(response_header.size()),
  7819. #else
  7820. response_header.c_str(), response_header.size(),
  7821. #endif
  7822. 0);
  7823. std::string chunk(64 * 1024, 'A');
  7824. size_t total_sent = 0;
  7825. while (total_sent < DATA_SIZE) {
  7826. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7827. auto sent = ::send(cli,
  7828. #ifdef _WIN32
  7829. static_cast<const char *>(chunk.c_str()),
  7830. static_cast<int>(to_send),
  7831. #else
  7832. chunk.c_str(), to_send,
  7833. #endif
  7834. 0);
  7835. if (sent <= 0) break;
  7836. total_sent += static_cast<size_t>(sent);
  7837. }
  7838. detail::close_socket(cli);
  7839. }
  7840. detail::close_socket(srv);
  7841. });
  7842. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7843. size_t total_received = 0;
  7844. {
  7845. Client cli("127.0.0.1", PORT + 2);
  7846. cli.set_read_timeout(10, 0);
  7847. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7848. auto res =
  7849. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7850. total_received += data_length;
  7851. return true;
  7852. });
  7853. // Should fail because 200MB exceeds the explicit 150MB limit
  7854. EXPECT_FALSE(res);
  7855. }
  7856. server_thread.join();
  7857. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7858. << "Client with content_receiver should respect the explicit "
  7859. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7860. << total_received << " bytes.";
  7861. }
  7862. // Verify that an explicit set_payload_max_length larger than the response
  7863. // allows the content_receiver to read all data successfully.
  7864. TEST(ClientVulnerabilityTest,
  7865. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7866. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7867. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7868. #ifndef _WIN32
  7869. signal(SIGPIPE, SIG_IGN);
  7870. #endif
  7871. auto server_thread = std::thread([] {
  7872. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7873. default_socket_options(srv);
  7874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7875. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7876. sockaddr_in addr{};
  7877. addr.sin_family = AF_INET;
  7878. addr.sin_port = htons(PORT + 2);
  7879. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7880. int opt = 1;
  7881. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7882. #ifdef _WIN32
  7883. reinterpret_cast<const char *>(&opt),
  7884. #else
  7885. &opt,
  7886. #endif
  7887. sizeof(opt));
  7888. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7889. ::listen(srv, 1);
  7890. sockaddr_in cli_addr{};
  7891. socklen_t cli_len = sizeof(cli_addr);
  7892. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7893. if (cli != INVALID_SOCKET) {
  7894. char buf[4096];
  7895. ::recv(cli, buf, sizeof(buf), 0);
  7896. auto content_length = std::to_string(DATA_SIZE);
  7897. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7898. "Content-Length: " +
  7899. content_length +
  7900. "\r\n"
  7901. "Connection: close\r\n"
  7902. "\r\n";
  7903. ::send(cli,
  7904. #ifdef _WIN32
  7905. static_cast<const char *>(response_header.c_str()),
  7906. static_cast<int>(response_header.size()),
  7907. #else
  7908. response_header.c_str(), response_header.size(),
  7909. #endif
  7910. 0);
  7911. std::string chunk(64 * 1024, 'A');
  7912. size_t total_sent = 0;
  7913. while (total_sent < DATA_SIZE) {
  7914. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7915. auto sent = ::send(cli,
  7916. #ifdef _WIN32
  7917. static_cast<const char *>(chunk.c_str()),
  7918. static_cast<int>(to_send),
  7919. #else
  7920. chunk.c_str(), to_send,
  7921. #endif
  7922. 0);
  7923. if (sent <= 0) break;
  7924. total_sent += static_cast<size_t>(sent);
  7925. }
  7926. #ifdef _WIN32
  7927. ::shutdown(cli, SD_SEND);
  7928. #else
  7929. ::shutdown(cli, SHUT_WR);
  7930. #endif
  7931. char drain[1024];
  7932. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7933. detail::close_socket(cli);
  7934. }
  7935. detail::close_socket(srv);
  7936. });
  7937. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7938. size_t total_received = 0;
  7939. {
  7940. Client cli("127.0.0.1", PORT + 2);
  7941. cli.set_read_timeout(10, 0);
  7942. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7943. auto res =
  7944. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7945. total_received += data_length;
  7946. return true;
  7947. });
  7948. ASSERT_TRUE(res);
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. }
  7951. server_thread.join();
  7952. EXPECT_EQ(total_received, DATA_SIZE)
  7953. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7954. << " bytes (larger than " << DATA_SIZE
  7955. << " bytes response), content_receiver should read all data, but only "
  7956. "read "
  7957. << total_received << " bytes.";
  7958. }
  7959. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7960. // Regression test for "zip bomb" attack on the client side: a malicious server
  7961. // sends a small gzip-compressed response that decompresses to a huge payload.
  7962. // The client must enforce payload_max_length on the decompressed size.
  7963. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7964. constexpr size_t DECOMPRESSED_SIZE =
  7965. 10 * 1024 * 1024; // 10MB after decompression
  7966. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7967. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7968. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7969. std::string compressed;
  7970. {
  7971. httplib::detail::gzip_compressor compressor;
  7972. bool ok =
  7973. compressor.compress(uncompressed.data(), uncompressed.size(),
  7974. /*last=*/true, [&](const char *buf, size_t len) {
  7975. compressed.append(buf, len);
  7976. return true;
  7977. });
  7978. ASSERT_TRUE(ok);
  7979. }
  7980. // Sanity: compressed data should be much smaller than the decompressed size
  7981. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7982. #ifndef _WIN32
  7983. signal(SIGPIPE, SIG_IGN);
  7984. #endif
  7985. // Set up the listening socket in the main thread so the server is guaranteed
  7986. // to be ready before the client connects (eliminates race condition).
  7987. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7988. default_socket_options(srv);
  7989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7991. sockaddr_in addr{};
  7992. addr.sin_family = AF_INET;
  7993. addr.sin_port = htons(PORT + 3);
  7994. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7995. int opt = 1;
  7996. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7997. #ifdef _WIN32
  7998. reinterpret_cast<const char *>(&opt),
  7999. #else
  8000. &opt,
  8001. #endif
  8002. sizeof(opt));
  8003. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8004. ASSERT_EQ(0, ::listen(srv, 1));
  8005. auto server_thread = std::thread([&compressed, srv] {
  8006. sockaddr_in cli_addr{};
  8007. socklen_t cli_len = sizeof(cli_addr);
  8008. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8009. if (cli != INVALID_SOCKET) {
  8010. // Read the full HTTP request (until \r\n\r\n)
  8011. char buf[4096];
  8012. size_t total = 0;
  8013. while (total < sizeof(buf)) {
  8014. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8015. if (n <= 0) break;
  8016. total += static_cast<size_t>(n);
  8017. // Check for end of headers
  8018. if (total >= 4) {
  8019. std::string req(buf, total);
  8020. if (req.find("\r\n\r\n") != std::string::npos) break;
  8021. }
  8022. }
  8023. // Malicious response: gzip-compressed body, no Content-Length
  8024. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8025. "Content-Encoding: gzip\r\n"
  8026. "Connection: close\r\n"
  8027. "\r\n";
  8028. ::send(cli,
  8029. #ifdef _WIN32
  8030. static_cast<const char *>(response_header.c_str()),
  8031. static_cast<int>(response_header.size()),
  8032. #else
  8033. response_header.c_str(), response_header.size(),
  8034. #endif
  8035. 0);
  8036. // Send the compressed payload (small on the wire, huge when decompressed)
  8037. size_t total_sent = 0;
  8038. while (total_sent < compressed.size()) {
  8039. auto to_send = std::min(compressed.size() - total_sent,
  8040. static_cast<size_t>(64 * 1024));
  8041. auto sent =
  8042. ::send(cli,
  8043. #ifdef _WIN32
  8044. static_cast<const char *>(compressed.c_str() + total_sent),
  8045. static_cast<int>(to_send),
  8046. #else
  8047. compressed.c_str() + total_sent, to_send,
  8048. #endif
  8049. 0);
  8050. if (sent <= 0) break;
  8051. total_sent += static_cast<size_t>(sent);
  8052. }
  8053. detail::close_socket(cli);
  8054. }
  8055. });
  8056. auto se = detail::scope_exit([&] {
  8057. detail::close_socket(srv);
  8058. server_thread.join();
  8059. });
  8060. size_t total_decompressed = 0;
  8061. {
  8062. Client cli("127.0.0.1", PORT + 3);
  8063. cli.set_read_timeout(5, 0);
  8064. cli.set_decompress(true);
  8065. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8066. auto stream = cli.open_stream("GET", "/zipbomb");
  8067. ASSERT_TRUE(stream.is_valid());
  8068. char buffer[64 * 1024];
  8069. ssize_t n;
  8070. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8071. total_decompressed += static_cast<size_t>(n);
  8072. }
  8073. }
  8074. // The decompressed size must be capped by payload_max_length. Without
  8075. // protection, the client would decompress the full 10MB from a tiny
  8076. // compressed payload, enabling a zip bomb DoS attack.
  8077. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8078. << "Client decompressed " << total_decompressed
  8079. << " bytes from a gzip response. The decompressed size should be "
  8080. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8081. }
  8082. #endif
  8083. TEST(HostAndPortPropertiesTest, NoSSL) {
  8084. httplib::Client cli("www.google.com", 1234);
  8085. ASSERT_EQ("www.google.com", cli.host());
  8086. ASSERT_EQ(1234, cli.port());
  8087. }
  8088. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8089. httplib::Client cli("www.google.com:1234");
  8090. ASSERT_EQ("www.google.com", cli.host());
  8091. ASSERT_EQ(1234, cli.port());
  8092. }
  8093. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8094. // Port number that overflows int — should not crash, client becomes invalid
  8095. httplib::Client cli("http://www.google.com:99999999999999999999");
  8096. ASSERT_FALSE(cli.is_valid());
  8097. }
  8098. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8099. // Port 99999 exceeds valid range (1-65535) — should not crash
  8100. httplib::Client cli("http://www.google.com:99999");
  8101. ASSERT_FALSE(cli.is_valid());
  8102. }
  8103. #ifdef CPPHTTPLIB_SSL_ENABLED
  8104. TEST(HostAndPortPropertiesTest, SSL) {
  8105. httplib::SSLClient cli("www.google.com");
  8106. ASSERT_EQ("www.google.com", cli.host());
  8107. ASSERT_EQ(443, cli.port());
  8108. }
  8109. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8110. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8111. std::string cert;
  8112. read_file(CA_CERT_FILE, cert);
  8113. httplib::SSLClient httplib_client("www.google.com");
  8114. // Load CA store first time
  8115. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8116. // Load CA store second time (update)
  8117. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8118. // Verify client is still valid and can make connections
  8119. httplib_client.enable_server_certificate_verification(true);
  8120. auto res = httplib_client.Get("/");
  8121. ASSERT_TRUE(res);
  8122. // Google may return 200 or 301 depending on various factors
  8123. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8124. res->status == StatusCode::MovedPermanently_301);
  8125. }
  8126. TEST(SSLClientTest, ServerNameIndication_Online) {
  8127. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8128. auto host = "httpcan.org";
  8129. auto path = std::string{"/get"};
  8130. #else
  8131. auto host = "nghttp2.org";
  8132. auto path = std::string{"/httpbin/get"};
  8133. #endif
  8134. SSLClient cli(host, 443);
  8135. auto res = cli.Get(path);
  8136. ASSERT_TRUE(res);
  8137. ASSERT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8140. // Use a site that will cause SSL verification failure due to self-signed cert
  8141. SSLClient cli("self-signed.badssl.com", 443);
  8142. cli.enable_server_certificate_verification(true);
  8143. auto res = cli.Get("/");
  8144. ASSERT_TRUE(!res);
  8145. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8146. // Verify backend error is captured for SSLServerVerification
  8147. // This occurs when certificate verification fails
  8148. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8149. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8150. EXPECT_NE(0UL, res.ssl_backend_error());
  8151. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8152. // For OpenSSL, ssl_error is 0 for verification errors
  8153. EXPECT_EQ(0, res.ssl_error());
  8154. #if !defined(_WIN32) || \
  8155. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8156. // On non-Windows or when Windows Schannel is disabled, the error comes
  8157. // from OpenSSL's verification
  8158. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8159. res.ssl_backend_error());
  8160. #endif
  8161. #endif
  8162. }
  8163. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8164. // Use a site where hostname doesn't match the certificate
  8165. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8166. SSLClient cli("wrong.host.badssl.com", 443);
  8167. cli.enable_server_certificate_verification(true);
  8168. cli.enable_server_hostname_verification(true);
  8169. auto res = cli.Get("/");
  8170. ASSERT_TRUE(!res);
  8171. // The error type depends on when hostname verification occurs:
  8172. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8173. // - Mbed TLS: SSLServerVerification (during handshake)
  8174. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8175. res.error() == Error::SSLServerVerification);
  8176. // Verify backend error is captured for hostname verification failure
  8177. EXPECT_NE(0UL, res.ssl_backend_error());
  8178. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8179. // For OpenSSL, ssl_error is 0 for verification errors
  8180. EXPECT_EQ(0, res.ssl_error());
  8181. #if !defined(_WIN32) || \
  8182. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8183. // On non-Windows or when Windows Schannel is disabled, the error comes
  8184. // from OpenSSL's hostname verification
  8185. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8186. res.ssl_backend_error());
  8187. #endif
  8188. #endif
  8189. }
  8190. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8191. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8192. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8193. SSLClient cli("www.google.com", 443);
  8194. cli.enable_server_certificate_verification(true);
  8195. auto res = cli.Get("/");
  8196. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8197. }
  8198. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8199. SSLClient cli("www.google.com", 443);
  8200. cli.enable_server_certificate_verification(true);
  8201. cli.enable_windows_certificate_verification(false);
  8202. auto res = cli.Get("/");
  8203. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8204. }
  8205. #endif
  8206. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8207. Client cli("https://google.com");
  8208. auto res = cli.Get("/");
  8209. ASSERT_TRUE(res);
  8210. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8211. }
  8212. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8213. SSLClient cli("google.com");
  8214. cli.set_ca_cert_path(CA_CERT_FILE);
  8215. auto res = cli.Get("/");
  8216. ASSERT_TRUE(res);
  8217. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8218. }
  8219. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8220. SSLClient cli("google.com");
  8221. cli.enable_server_certificate_verification(true);
  8222. cli.set_ca_cert_path("hello");
  8223. auto res = cli.Get("/");
  8224. ASSERT_TRUE(!res);
  8225. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8226. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8227. // should be set
  8228. EXPECT_EQ(0, res.ssl_error());
  8229. // Verify backend error is captured for SSLLoadingCerts
  8230. // This error occurs when loading CA certificates fails
  8231. EXPECT_NE(0UL, res.ssl_backend_error());
  8232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8233. // OpenSSL specific error codes:
  8234. // > openssl errstr 0x80000002
  8235. // error:80000002:system library::No such file or directory
  8236. // > openssl errstr 0xA000126
  8237. // error:0A000126:SSL routines::unexpected eof while reading
  8238. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8239. res.ssl_backend_error() == 0xA000126);
  8240. #endif
  8241. }
  8242. TEST(SSLClientTest, ServerCertificateVerification4) {
  8243. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8244. ASSERT_TRUE(svr.is_valid());
  8245. svr.Get("/test", [&](const Request &, Response &res) {
  8246. res.set_content("test", "text/plain");
  8247. svr.stop();
  8248. ASSERT_TRUE(true);
  8249. });
  8250. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8251. auto se = detail::scope_exit([&] {
  8252. t.join();
  8253. ASSERT_FALSE(svr.is_running());
  8254. });
  8255. svr.wait_until_ready();
  8256. SSLClient cli("127.0.0.1", PORT);
  8257. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8258. cli.enable_server_certificate_verification(true);
  8259. cli.set_connection_timeout(30);
  8260. auto res = cli.Get("/test");
  8261. ASSERT_TRUE(res);
  8262. ASSERT_EQ(StatusCode::OK_200, res->status);
  8263. }
  8264. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8265. std::string cert;
  8266. read_file(CA_CERT_FILE, cert);
  8267. SSLClient cli("google.com");
  8268. cli.load_ca_cert_store(cert.data(), cert.size());
  8269. const auto res = cli.Get("/");
  8270. ASSERT_TRUE(res);
  8271. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8272. }
  8273. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8274. // clang-format off
  8275. static constexpr char cert[] =
  8276. "GlobalSign Root CA\n"
  8277. "==================\n"
  8278. "-----BEGIN CERTIFICATE-----\n"
  8279. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8280. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8281. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8282. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8283. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8284. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8285. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8286. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8287. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8288. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8289. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8290. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8291. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8292. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8293. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8294. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8295. "-----END CERTIFICATE-----\n";
  8296. // clang-format on
  8297. SSLClient cli("google.com");
  8298. cli.load_ca_cert_store(cert, sizeof(cert));
  8299. const auto res = cli.Get("/");
  8300. ASSERT_TRUE(res);
  8301. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8302. }
  8303. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8304. SSLClient cli("www.youtube.com");
  8305. cli.set_ca_cert_path(CA_CERT_FILE);
  8306. cli.enable_server_certificate_verification(true);
  8307. cli.set_follow_location(true);
  8308. auto res = cli.Get("/");
  8309. ASSERT_TRUE(res);
  8310. ASSERT_EQ(StatusCode::OK_200, res->status);
  8311. }
  8312. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8313. SSLClient cli("wWw.YouTube.Com");
  8314. cli.set_ca_cert_path(CA_CERT_FILE);
  8315. cli.enable_server_certificate_verification(true);
  8316. cli.enable_server_hostname_verification(true);
  8317. cli.set_follow_location(true);
  8318. auto res = cli.Get("/");
  8319. ASSERT_TRUE(res);
  8320. ASSERT_EQ(StatusCode::OK_200, res->status);
  8321. }
  8322. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8323. SSLClient cli("gOoGlE.COm");
  8324. cli.enable_server_certificate_verification(true);
  8325. cli.enable_server_hostname_verification(true);
  8326. cli.set_follow_location(true);
  8327. auto res = cli.Get("/");
  8328. ASSERT_TRUE(res);
  8329. ASSERT_EQ(StatusCode::OK_200, res->status);
  8330. }
  8331. TEST(SSLClientTest, Issue2004_Online) {
  8332. Client client("https://google.com");
  8333. client.set_follow_location(true);
  8334. auto res = client.Get("/");
  8335. ASSERT_TRUE(res);
  8336. ASSERT_EQ(StatusCode::OK_200, res->status);
  8337. auto body = res->body;
  8338. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8339. }
  8340. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8341. // Create SSLClient with invalid cert/key to make is_valid() return false
  8342. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8343. "nonexistent_key.pem");
  8344. // is_valid() should be false due to cert loading failure
  8345. ASSERT_FALSE(cli.is_valid());
  8346. auto res = cli.Get("/");
  8347. ASSERT_FALSE(res);
  8348. EXPECT_EQ(Error::SSLConnection, res.error());
  8349. }
  8350. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8351. // Test for Issue #2251: SSL error not properly reported when client cert
  8352. // and key paths are swapped or mismatched
  8353. // This simulates the scenario where user accidentally swaps the cert and key
  8354. // files
  8355. // Using client cert file as private key and vice versa (completely wrong)
  8356. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8357. // Should fail validation due to cert/key mismatch
  8358. ASSERT_FALSE(cli.is_valid());
  8359. // Attempt to make a request should fail with proper error
  8360. auto res = cli.Get("/");
  8361. ASSERT_FALSE(res);
  8362. EXPECT_EQ(Error::SSLConnection, res.error());
  8363. // SSL error should be recorded in the Result object (this is the key fix for
  8364. // Issue #2251)
  8365. auto backend_error = res.ssl_backend_error();
  8366. EXPECT_NE(0u, backend_error);
  8367. }
  8368. // Tests cert/key mismatch detection at the TLS context level
  8369. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8370. // Test that using mismatched cert/key causes connection failure.
  8371. // We verify this at the SSLClient level rather than through internal
  8372. // TLS API functions.
  8373. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8374. cli.enable_server_certificate_verification(false);
  8375. cli.set_connection_timeout(2);
  8376. // The mismatch should cause a connection or handshake error
  8377. auto res = cli.Get("/test");
  8378. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8379. // Either way, the request should fail
  8380. EXPECT_FALSE(res);
  8381. }
  8382. #endif
  8383. #if 0
  8384. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8385. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8386. ASSERT_TRUE(cli != nullptr);
  8387. cli->set_address_family(AF_INET6);
  8388. cli->set_interface("en0");
  8389. auto res = cli->Get("/get");
  8390. ASSERT_TRUE(res);
  8391. ASSERT_EQ(StatusCode::OK_200, res->status);
  8392. }
  8393. #endif
  8394. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8395. #ifdef CPPHTTPLIB_SSL_ENABLED
  8396. void ClientCertPresent(
  8397. const std::string &client_cert_file,
  8398. const std::string &client_private_key_file,
  8399. const std::string &client_encrypted_private_key_pass = std::string()) {
  8400. using namespace httplib::tls;
  8401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8402. CLIENT_CA_CERT_DIR);
  8403. ASSERT_TRUE(svr.is_valid());
  8404. svr.Get("/test", [&](const Request &req, Response &res) {
  8405. res.set_content("test", "text/plain");
  8406. auto cert = req.peer_cert();
  8407. ASSERT_TRUE(static_cast<bool>(cert));
  8408. std::string common_name = cert.subject_cn();
  8409. EXPECT_EQ("Common Name", common_name);
  8410. });
  8411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8412. auto se = detail::scope_exit([&] {
  8413. svr.stop();
  8414. t.join();
  8415. ASSERT_FALSE(svr.is_running());
  8416. });
  8417. svr.wait_until_ready();
  8418. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8419. client_encrypted_private_key_pass);
  8420. cli.enable_server_certificate_verification(false);
  8421. cli.set_connection_timeout(30);
  8422. auto res = cli.Get("/test");
  8423. ASSERT_TRUE(res);
  8424. ASSERT_EQ(StatusCode::OK_200, res->status);
  8425. }
  8426. TEST(SSLClientServerTest, ClientCertPresent) {
  8427. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8428. }
  8429. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8430. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8431. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8432. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8433. }
  8434. // PEM memory-based constructor tests (works with all TLS backends)
  8435. void PemMemoryClientCertPresent(
  8436. const std::string &client_cert_file,
  8437. const std::string &client_private_key_file,
  8438. const std::string &client_encrypted_private_key_pass = std::string()) {
  8439. // Read PEM files into memory
  8440. std::string server_cert_pem, server_key_pem;
  8441. std::string client_ca_pem;
  8442. std::string client_cert_pem, client_key_pem;
  8443. read_file(SERVER_CERT_FILE, server_cert_pem);
  8444. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8445. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8446. read_file(client_cert_file, client_cert_pem);
  8447. read_file(client_private_key_file, client_key_pem);
  8448. // Create server with PEM memory
  8449. SSLServer::PemMemory server_pem = {
  8450. server_cert_pem.c_str(),
  8451. server_cert_pem.size(),
  8452. server_key_pem.c_str(),
  8453. server_key_pem.size(),
  8454. client_ca_pem.c_str(),
  8455. client_ca_pem.size(),
  8456. nullptr // no password for server key
  8457. };
  8458. SSLServer svr(server_pem);
  8459. ASSERT_TRUE(svr.is_valid());
  8460. svr.Get("/test", [&](const Request &, Response &res) {
  8461. res.set_content("test", "text/plain");
  8462. });
  8463. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8464. auto se = detail::scope_exit([&] {
  8465. svr.stop();
  8466. t.join();
  8467. ASSERT_FALSE(svr.is_running());
  8468. });
  8469. svr.wait_until_ready();
  8470. // Create client with PEM memory
  8471. const char *password = client_encrypted_private_key_pass.empty()
  8472. ? nullptr
  8473. : client_encrypted_private_key_pass.c_str();
  8474. SSLClient::PemMemory client_pem = {
  8475. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8476. client_key_pem.size(), password};
  8477. SSLClient cli(HOST, PORT, client_pem);
  8478. cli.enable_server_certificate_verification(false);
  8479. cli.set_connection_timeout(30);
  8480. auto res = cli.Get("/test");
  8481. ASSERT_TRUE(res);
  8482. ASSERT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8485. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8486. }
  8487. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8488. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8489. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8490. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8491. }
  8492. TEST(SSLClientServerTest, ClientCertMissing) {
  8493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8494. CLIENT_CA_CERT_DIR);
  8495. ASSERT_TRUE(svr.is_valid());
  8496. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8498. auto se = detail::scope_exit([&] {
  8499. svr.stop();
  8500. t.join();
  8501. ASSERT_FALSE(svr.is_running());
  8502. });
  8503. svr.wait_until_ready();
  8504. SSLClient cli(HOST, PORT);
  8505. cli.set_connection_timeout(30);
  8506. auto res = cli.Get("/test");
  8507. ASSERT_TRUE(!res);
  8508. // When client cert is missing and server requires it, connection fails
  8509. // Error type depends on backend implementation
  8510. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8511. res.error() == Error::SSLConnection);
  8512. // Verify backend error is captured
  8513. // Note: This test may have different error codes depending on the exact
  8514. // verification failure
  8515. EXPECT_NE(0UL, res.ssl_backend_error());
  8516. }
  8517. TEST(SSLClientServerTest, TrustDirOptional) {
  8518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8519. ASSERT_TRUE(svr.is_valid());
  8520. svr.Get("/test", [&](const Request &, Response &res) {
  8521. res.set_content("test", "text/plain");
  8522. });
  8523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8524. auto se = detail::scope_exit([&] {
  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(30);
  8533. auto res = cli.Get("/test");
  8534. ASSERT_TRUE(res);
  8535. ASSERT_EQ(StatusCode::OK_200, res->status);
  8536. }
  8537. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8538. class NoListenSSLServer : public SSLServer {
  8539. public:
  8540. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8541. const char *client_ca_cert_file_path,
  8542. const char *client_ca_cert_dir_path = nullptr)
  8543. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8544. client_ca_cert_dir_path),
  8545. stop_(false) {}
  8546. std::atomic_bool stop_;
  8547. private:
  8548. bool process_and_close_socket(socket_t /*sock*/) override {
  8549. // Don't create SSL context
  8550. while (!stop_.load()) {
  8551. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8552. }
  8553. return true;
  8554. }
  8555. };
  8556. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8557. CLIENT_CA_CERT_FILE);
  8558. ASSERT_TRUE(svr.is_valid());
  8559. svr.Get("/test", [&](const Request &, Response &res) {
  8560. res.set_content("test", "text/plain");
  8561. });
  8562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8563. auto se = detail::scope_exit([&] {
  8564. svr.stop_ = true;
  8565. svr.stop();
  8566. t.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8571. cli.enable_server_certificate_verification(false);
  8572. cli.set_connection_timeout(1);
  8573. auto res = cli.Get("/test");
  8574. ASSERT_TRUE(!res);
  8575. EXPECT_EQ(Error::SSLConnection, res.error());
  8576. // Timeout results in WantRead error code (maps to backend-specific value)
  8577. EXPECT_NE(0, res.ssl_error());
  8578. }
  8579. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8580. // Test SSLServer with client certificate verification using the standard
  8581. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8583. CLIENT_CA_CERT_DIR);
  8584. ASSERT_TRUE(svr.is_valid());
  8585. svr.Get("/test", [&](const Request &req, Response &res) {
  8586. res.set_content("test", "text/plain");
  8587. auto cert = req.peer_cert();
  8588. ASSERT_TRUE(static_cast<bool>(cert));
  8589. auto common_name = cert.subject_cn();
  8590. EXPECT_EQ("Common Name", common_name);
  8591. });
  8592. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8593. auto se = detail::scope_exit([&] {
  8594. svr.stop();
  8595. t.join();
  8596. ASSERT_FALSE(svr.is_running());
  8597. });
  8598. svr.wait_until_ready();
  8599. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8600. cli.enable_server_certificate_verification(false);
  8601. cli.set_connection_timeout(30);
  8602. auto res = cli.Get("/test");
  8603. ASSERT_TRUE(res);
  8604. ASSERT_EQ(StatusCode::OK_200, res->status);
  8605. }
  8606. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8607. // Verifies that wildcard matching and exact matching work consistently
  8608. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8609. using namespace httplib::tls;
  8610. // We need a running server to test against
  8611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8612. ASSERT_TRUE(svr.is_valid());
  8613. svr.Get("/test", [](const Request &, Response &res) {
  8614. res.set_content("ok", "text/plain");
  8615. });
  8616. thread t([&]() { svr.listen(HOST, PORT); });
  8617. auto se = detail::scope_exit([&] {
  8618. svr.stop();
  8619. t.join();
  8620. });
  8621. svr.wait_until_ready();
  8622. bool verify_callback_called = false;
  8623. bool verify_result_wrong = false;
  8624. SSLClient cli(HOST, PORT);
  8625. cli.enable_server_certificate_verification(true);
  8626. cli.set_ca_cert_path(CA_CERT_FILE);
  8627. cli.set_connection_timeout(5);
  8628. // Note: Test certificate has CN="Common Name", not "localhost"
  8629. bool verify_result_cn = false;
  8630. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8631. verify_callback_called = true;
  8632. if (!ctx.cert) return false;
  8633. // Test 1: "Common Name" should match (our test server cert CN)
  8634. verify_result_cn = ctx.check_hostname("Common Name");
  8635. // Test 2: wrong hostname should not match
  8636. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8637. return true; // Accept for the purpose of this test
  8638. });
  8639. auto res = cli.Get("/test");
  8640. // The request may succeed or fail depending on cert configuration
  8641. // but the callback should have been called
  8642. ASSERT_TRUE(verify_callback_called)
  8643. << "Verify callback should have been called";
  8644. // CN="Common Name" should match our test certificate
  8645. EXPECT_TRUE(verify_result_cn)
  8646. << "verify_hostname should match 'Common Name' (certificate CN)";
  8647. // Wrong hostname should not match
  8648. EXPECT_FALSE(verify_result_wrong)
  8649. << "verify_hostname should not match 'wronghost.example.com'";
  8650. }
  8651. #endif
  8652. // mbedTLS-specific callback constructor test
  8653. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8654. #ifdef CPPHTTPLIB_SSL_ENABLED
  8655. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8657. ASSERT_TRUE(svr.is_valid());
  8658. // Set up a handler to verify client certificate is present
  8659. bool client_cert_verified = false;
  8660. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8661. // Verify that client certificate was provided
  8662. client_cert_verified = true;
  8663. res.set_content("success", "text/plain");
  8664. });
  8665. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8666. auto se = detail::scope_exit([&] {
  8667. svr.stop();
  8668. t.join();
  8669. ASSERT_FALSE(svr.is_running());
  8670. });
  8671. svr.wait_until_ready();
  8672. // Client with certificate
  8673. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8674. cli.enable_server_certificate_verification(false);
  8675. cli.set_connection_timeout(30);
  8676. auto res = cli.Get("/test");
  8677. ASSERT_TRUE(res);
  8678. ASSERT_EQ(StatusCode::OK_200, res->status);
  8679. ASSERT_TRUE(client_cert_verified);
  8680. EXPECT_EQ("success", res->body);
  8681. }
  8682. #endif
  8683. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8684. // backends
  8685. #ifdef CPPHTTPLIB_SSL_ENABLED
  8686. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8687. using namespace httplib::tls;
  8688. // Test that when client CA cert file is provided,
  8689. // the server properly requests and validates client certificates
  8690. // Create a server with client authentication
  8691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8692. ASSERT_TRUE(svr.is_valid());
  8693. bool handler_called = false;
  8694. svr.Get("/test", [&](const Request &req, Response &res) {
  8695. handler_called = true;
  8696. // Verify that a client certificate was provided
  8697. auto cert = req.peer_cert();
  8698. ASSERT_TRUE(static_cast<bool>(cert));
  8699. // Get the issuer name
  8700. std::string issuer_str = cert.issuer_name();
  8701. ASSERT_FALSE(issuer_str.empty());
  8702. // The client certificate should be issued by our test CA
  8703. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8704. res.set_content("authenticated", "text/plain");
  8705. });
  8706. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8707. auto se = detail::scope_exit([&] {
  8708. svr.stop();
  8709. t.join();
  8710. ASSERT_FALSE(svr.is_running());
  8711. });
  8712. svr.wait_until_ready();
  8713. // Connect with a client certificate issued by the CA
  8714. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8715. cli.enable_server_certificate_verification(false);
  8716. cli.set_connection_timeout(30);
  8717. auto res = cli.Get("/test");
  8718. ASSERT_TRUE(res);
  8719. ASSERT_EQ(StatusCode::OK_200, res->status);
  8720. ASSERT_TRUE(handler_called);
  8721. EXPECT_EQ("authenticated", res->body);
  8722. }
  8723. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8724. using namespace httplib::tls;
  8725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8726. ASSERT_TRUE(svr.is_valid());
  8727. svr.Get("/test", [](const Request &, Response &res) {
  8728. res.set_content("ok", "text/plain");
  8729. });
  8730. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8731. auto se = detail::scope_exit([&] {
  8732. svr.stop();
  8733. t.join();
  8734. });
  8735. svr.wait_until_ready();
  8736. SSLClient cli(HOST, PORT);
  8737. cli.enable_server_certificate_verification(false);
  8738. cli.set_connection_timeout(30);
  8739. bool cert_checked = false;
  8740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8741. if (ctx.cert) {
  8742. auto sans = ctx.sans();
  8743. // Test certificate may or may not have SANs - just verify the API
  8744. // works If SANs exist, verify the types are valid
  8745. for (const auto &san : sans) {
  8746. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8747. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8748. san.type == SanType::OTHER);
  8749. EXPECT_FALSE(san.value.empty());
  8750. }
  8751. cert_checked = true;
  8752. }
  8753. return true;
  8754. });
  8755. auto res = cli.Get("/test");
  8756. ASSERT_TRUE(res);
  8757. EXPECT_TRUE(cert_checked);
  8758. }
  8759. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8760. using namespace httplib::tls;
  8761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8762. ASSERT_TRUE(svr.is_valid());
  8763. svr.Get("/test", [](const Request &, Response &res) {
  8764. res.set_content("ok", "text/plain");
  8765. });
  8766. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8767. auto se = detail::scope_exit([&] {
  8768. svr.stop();
  8769. t.join();
  8770. });
  8771. svr.wait_until_ready();
  8772. SSLClient cli(HOST, PORT);
  8773. cli.enable_server_certificate_verification(false);
  8774. cli.set_connection_timeout(30);
  8775. bool validity_checked = false;
  8776. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8777. if (ctx.cert) {
  8778. time_t not_before = 0, not_after = 0;
  8779. bool result = ctx.validity(not_before, not_after);
  8780. EXPECT_TRUE(result);
  8781. // Verify that not_before < now < not_after for a valid cert
  8782. time_t now = time(nullptr);
  8783. EXPECT_LT(not_before, now);
  8784. EXPECT_GT(not_after, now);
  8785. validity_checked = true;
  8786. }
  8787. return true;
  8788. });
  8789. auto res = cli.Get("/test");
  8790. ASSERT_TRUE(res);
  8791. EXPECT_TRUE(validity_checked);
  8792. }
  8793. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8794. using namespace httplib::tls;
  8795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8796. ASSERT_TRUE(svr.is_valid());
  8797. svr.Get("/test", [](const Request &, Response &res) {
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. });
  8805. svr.wait_until_ready();
  8806. SSLClient cli(HOST, PORT);
  8807. cli.enable_server_certificate_verification(false);
  8808. cli.set_connection_timeout(30);
  8809. bool serial_checked = false;
  8810. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8811. if (ctx.cert) {
  8812. std::string serial = ctx.serial();
  8813. EXPECT_FALSE(serial.empty());
  8814. // Serial should be a hex string
  8815. for (char c : serial) {
  8816. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8817. (c >= 'a' && c <= 'f'));
  8818. }
  8819. serial_checked = true;
  8820. }
  8821. return true;
  8822. });
  8823. auto res = cli.Get("/test");
  8824. ASSERT_TRUE(res);
  8825. EXPECT_TRUE(serial_checked);
  8826. }
  8827. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8828. // Test 1: Valid CA file - no error should be recorded
  8829. {
  8830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8831. CLIENT_CA_CERT_FILE);
  8832. ASSERT_TRUE(svr.is_valid());
  8833. // With valid setup, last_ssl_error should be 0
  8834. EXPECT_EQ(0, svr.ssl_last_error());
  8835. }
  8836. // Test 2: Invalid CA file content
  8837. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8838. {
  8839. // Create a temporary file with completely invalid content
  8840. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8841. {
  8842. std::ofstream ofs(temp_invalid_ca);
  8843. ofs << "This is not a certificate file at all\n";
  8844. ofs << "Just plain text content\n";
  8845. }
  8846. // Create server with invalid CA file
  8847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8848. // Clean up temporary file
  8849. std::remove(temp_invalid_ca);
  8850. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8851. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8852. // Note: SSL_CTX_load_verify_locations typically fails first,
  8853. // but our error handling code path is still exercised
  8854. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8855. }
  8856. }
  8857. TEST(VerifyCallbackTest, VerifyContextFields) {
  8858. using namespace httplib::tls;
  8859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8860. ASSERT_TRUE(svr.is_valid());
  8861. svr.Get("/test", [](const Request &, Response &res) {
  8862. res.set_content("ok", "text/plain");
  8863. });
  8864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8865. auto se = detail::scope_exit([&] {
  8866. svr.stop();
  8867. t.join();
  8868. });
  8869. svr.wait_until_ready();
  8870. SSLClient cli(HOST, PORT);
  8871. cli.enable_server_certificate_verification(false);
  8872. cli.set_connection_timeout(30);
  8873. int callback_count = 0;
  8874. bool saw_leaf_cert = false;
  8875. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8876. if (ctx.cert) {
  8877. callback_count++;
  8878. // We should see at least one certificate (the leaf)
  8879. std::string cn = ctx.subject_cn();
  8880. if (!cn.empty()) { saw_leaf_cert = true; }
  8881. // Verify context fields are populated
  8882. EXPECT_NE(ctx.session, nullptr);
  8883. EXPECT_GE(ctx.depth, 0);
  8884. }
  8885. return true;
  8886. });
  8887. auto res = cli.Get("/test");
  8888. ASSERT_TRUE(res);
  8889. EXPECT_GT(callback_count, 0);
  8890. EXPECT_TRUE(saw_leaf_cert);
  8891. }
  8892. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8893. using httplib::tls::TlsError;
  8894. // Test that verify_error_to_string returns empty for success
  8895. std::string success_str = TlsError::verify_error_to_string(0);
  8896. EXPECT_TRUE(success_str.empty());
  8897. // Test that verify_error_to_string returns non-empty for error codes
  8898. // Using a common error code (certificate expired)
  8899. std::string error_str =
  8900. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8901. EXPECT_FALSE(error_str.empty());
  8902. }
  8903. TEST(SessionVerifierTest, CertificateAccepted) {
  8904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8905. ASSERT_TRUE(svr.is_valid());
  8906. svr.Get("/test", [](const Request &, Response &res) {
  8907. res.set_content("ok", "text/plain");
  8908. });
  8909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8910. auto se = detail::scope_exit([&] {
  8911. svr.stop();
  8912. t.join();
  8913. });
  8914. svr.wait_until_ready();
  8915. SSLClient cli(HOST, PORT);
  8916. cli.enable_server_certificate_verification(false);
  8917. cli.set_connection_timeout(30);
  8918. bool callback_called = false;
  8919. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8920. EXPECT_NE(session, nullptr);
  8921. callback_called = true;
  8922. return SSLVerifierResponse::CertificateAccepted;
  8923. });
  8924. auto res = cli.Get("/test");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(200, res->status);
  8927. EXPECT_TRUE(callback_called);
  8928. }
  8929. TEST(SessionVerifierTest, CertificateRejected) {
  8930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8931. ASSERT_TRUE(svr.is_valid());
  8932. svr.Get("/test", [](const Request &, Response &res) {
  8933. res.set_content("ok", "text/plain");
  8934. });
  8935. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8936. auto se = detail::scope_exit([&] {
  8937. svr.stop();
  8938. t.join();
  8939. });
  8940. svr.wait_until_ready();
  8941. SSLClient cli(HOST, PORT);
  8942. cli.enable_server_certificate_verification(false);
  8943. cli.set_connection_timeout(30);
  8944. bool callback_called = false;
  8945. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8946. EXPECT_NE(session, nullptr);
  8947. callback_called = true;
  8948. return SSLVerifierResponse::CertificateRejected;
  8949. });
  8950. auto res = cli.Get("/test");
  8951. EXPECT_FALSE(res);
  8952. EXPECT_TRUE(callback_called);
  8953. }
  8954. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8956. ASSERT_TRUE(svr.is_valid());
  8957. svr.Get("/test", [](const Request &, Response &res) {
  8958. res.set_content("ok", "text/plain");
  8959. });
  8960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8961. auto se = detail::scope_exit([&] {
  8962. svr.stop();
  8963. t.join();
  8964. });
  8965. svr.wait_until_ready();
  8966. // NoDecisionMade with verification disabled should succeed (no default check)
  8967. SSLClient cli(HOST, PORT);
  8968. cli.enable_server_certificate_verification(false);
  8969. cli.set_connection_timeout(30);
  8970. bool callback_called = false;
  8971. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8972. EXPECT_NE(session, nullptr);
  8973. callback_called = true;
  8974. return SSLVerifierResponse::NoDecisionMade;
  8975. });
  8976. auto res = cli.Get("/test");
  8977. ASSERT_TRUE(res);
  8978. EXPECT_EQ(200, res->status);
  8979. EXPECT_TRUE(callback_called);
  8980. }
  8981. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8983. ASSERT_TRUE(svr.is_valid());
  8984. svr.Get("/test", [](const Request &, Response &res) {
  8985. res.set_content("ok", "text/plain");
  8986. });
  8987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. });
  8992. svr.wait_until_ready();
  8993. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8994. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8995. // so we only check that the request fails, not whether the callback was
  8996. // called.
  8997. SSLClient cli(HOST, PORT);
  8998. cli.enable_server_certificate_verification(true);
  8999. cli.set_connection_timeout(30);
  9000. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9001. EXPECT_NE(session, nullptr);
  9002. return SSLVerifierResponse::NoDecisionMade;
  9003. });
  9004. auto res = cli.Get("/test");
  9005. EXPECT_FALSE(res);
  9006. }
  9007. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9008. // Test SSL server using PemMemory constructor with client CA certificates
  9009. // Read PEM files
  9010. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9011. read_file(SERVER_CERT_FILE, server_cert_pem);
  9012. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9013. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9014. // Create SSLServer with PemMemory constructor including client CA
  9015. SSLServer::PemMemory server_pem = {
  9016. server_cert_pem.c_str(),
  9017. server_cert_pem.size(),
  9018. server_key_pem.c_str(),
  9019. server_key_pem.size(),
  9020. client_ca_pem.c_str(),
  9021. client_ca_pem.size(),
  9022. nullptr // no password for server key
  9023. };
  9024. SSLServer svr(server_pem);
  9025. ASSERT_TRUE(svr.is_valid());
  9026. // No SSL error should be recorded for valid setup
  9027. EXPECT_EQ(0, svr.ssl_last_error());
  9028. // Set up server endpoints
  9029. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9030. res.set_content("ok", "text/plain");
  9031. });
  9032. // Start server in a thread
  9033. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9034. svr.wait_until_ready();
  9035. // Connect with client certificate (using constructor with paths)
  9036. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9037. cli.enable_server_certificate_verification(false);
  9038. auto res = cli.Get("/test-pem-ca");
  9039. ASSERT_TRUE(res);
  9040. EXPECT_EQ(200, res->status);
  9041. EXPECT_EQ("ok", res->body);
  9042. svr.stop();
  9043. server_thread.join();
  9044. }
  9045. #endif
  9046. #ifdef _WIN32
  9047. TEST(CleanupTest, WSACleanup) {
  9048. int ret = WSACleanup();
  9049. ASSERT_EQ(0, ret);
  9050. }
  9051. #endif
  9052. #ifndef CPPHTTPLIB_SSL_ENABLED
  9053. TEST(NoSSLSupport, SimpleInterface) {
  9054. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9055. }
  9056. #endif
  9057. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9058. TEST(InvalidScheme, SimpleInterface) {
  9059. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9060. }
  9061. #endif
  9062. TEST(NoScheme, SimpleInterface) {
  9063. Client cli("yahoo.com:80");
  9064. ASSERT_TRUE(cli.is_valid());
  9065. }
  9066. TEST(SendAPI, SimpleInterface_Online) {
  9067. Client cli("http://yahoo.com");
  9068. Request req;
  9069. req.method = "GET";
  9070. req.path = "/";
  9071. auto res = cli.send(req);
  9072. ASSERT_TRUE(res);
  9073. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9074. }
  9075. TEST(SendAPI, WithParamsInRequest) {
  9076. Server svr;
  9077. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9078. EXPECT_TRUE(req.has_param("test"));
  9079. EXPECT_EQ("test_value", req.get_param_value("test"));
  9080. });
  9081. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9082. auto se = detail::scope_exit([&] {
  9083. svr.stop();
  9084. t.join();
  9085. ASSERT_FALSE(svr.is_running());
  9086. });
  9087. svr.wait_until_ready();
  9088. Client cli(HOST, PORT);
  9089. {
  9090. Request req;
  9091. req.method = "GET";
  9092. req.path = "/";
  9093. req.params.emplace("test", "test_value");
  9094. auto res = cli.send(req);
  9095. ASSERT_TRUE(res);
  9096. }
  9097. {
  9098. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9099. ASSERT_TRUE(res);
  9100. }
  9101. }
  9102. TEST(ClientImplMethods, GetSocketTest) {
  9103. httplib::Server svr;
  9104. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9105. res.status = StatusCode::OK_200;
  9106. });
  9107. auto port = svr.bind_to_any_port("127.0.0.1");
  9108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9109. auto se = detail::scope_exit([&] {
  9110. svr.stop();
  9111. thread.join();
  9112. ASSERT_FALSE(svr.is_running());
  9113. });
  9114. svr.wait_until_ready();
  9115. {
  9116. httplib::Client cli("127.0.0.1", port);
  9117. cli.set_keep_alive(true);
  9118. // Use the behavior of cpp-httplib of opening the connection
  9119. // only when the first request happens. If that changes,
  9120. // this test would be obsolete.
  9121. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9122. // This also implicitly tests the server. But other tests would fail much
  9123. // earlier than this one to be considered.
  9124. auto res = cli.Get("/");
  9125. ASSERT_TRUE(res);
  9126. EXPECT_EQ(StatusCode::OK_200, res->status);
  9127. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9128. }
  9129. }
  9130. #ifdef CPPHTTPLIB_SSL_ENABLED
  9131. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9132. Client cli("http://yahoo.com");
  9133. auto res = cli.Get("/");
  9134. ASSERT_TRUE(res);
  9135. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9136. cli.set_follow_location(true);
  9137. res = cli.Get("/");
  9138. ASSERT_TRUE(res);
  9139. EXPECT_EQ(StatusCode::OK_200, res->status);
  9140. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9141. }
  9142. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9143. Client cli("https://yahoo.com");
  9144. auto res = cli.Get("/");
  9145. ASSERT_TRUE(res);
  9146. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9147. cli.set_follow_location(true);
  9148. res = cli.Get("/");
  9149. ASSERT_TRUE(res);
  9150. EXPECT_EQ(StatusCode::OK_200, res->status);
  9151. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9152. }
  9153. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9154. Client cli("https://yahoo.com");
  9155. auto res = cli.Get("/");
  9156. ASSERT_TRUE(res);
  9157. ASSERT_FALSE(!res);
  9158. ASSERT_TRUE(res);
  9159. ASSERT_FALSE(res == nullptr);
  9160. ASSERT_TRUE(res != nullptr);
  9161. EXPECT_EQ(Error::Success, res.error());
  9162. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9163. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9164. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9165. cli.set_follow_location(true);
  9166. res = cli.Get("/");
  9167. ASSERT_TRUE(res);
  9168. EXPECT_EQ(Error::Success, res.error());
  9169. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9170. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9171. EXPECT_EQ(StatusCode::OK_200, res->status);
  9172. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9173. }
  9174. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9175. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9176. Client cli("https://cdnjs.cloudflare.com");
  9177. auto res =
  9178. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9179. ASSERT_TRUE(res);
  9180. EXPECT_EQ(StatusCode::OK_200, res->status);
  9181. EXPECT_EQ(287630U, res->body.size());
  9182. EXPECT_EQ("application/javascript; charset=utf-8",
  9183. res->get_header_value("Content-Type"));
  9184. }
  9185. #endif
  9186. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9187. #undef REDIR_HOST // Silence compiler warning
  9188. #define REDIR_HOST "https://httpbingo.org"
  9189. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9190. Client cli(REDIR_HOST);
  9191. cli.set_follow_location(true);
  9192. auto res =
  9193. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9194. ASSERT_TRUE(res);
  9195. EXPECT_EQ(StatusCode::OK_200, res->status);
  9196. }
  9197. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9198. Client cli(REDIR_HOST);
  9199. cli.set_follow_location(true);
  9200. Params params;
  9201. params.emplace("url", "http://example.com");
  9202. params.emplace("status_code", "302");
  9203. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9204. ASSERT_TRUE(res);
  9205. EXPECT_EQ(StatusCode::OK_200, res->status);
  9206. }
  9207. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9208. Client cli(REDIR_HOST);
  9209. cli.set_follow_location(true);
  9210. Params params;
  9211. params.emplace("url", "http://example.com");
  9212. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9213. ASSERT_TRUE(res);
  9214. EXPECT_EQ(StatusCode::OK_200, res->status);
  9215. }
  9216. TEST(HttpToHttpsRedirectTest, CertFile) {
  9217. auto ssl_port = PORT + 1;
  9218. Server svr;
  9219. ASSERT_TRUE(svr.is_valid());
  9220. svr.Get("/index", [&](const Request &, Response &res) {
  9221. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9222. "/index");
  9223. svr.stop();
  9224. });
  9225. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9226. ASSERT_TRUE(ssl_svr.is_valid());
  9227. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9228. res.set_content("test", "text/plain");
  9229. ssl_svr.stop();
  9230. });
  9231. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9232. thread t2 =
  9233. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9234. auto se = detail::scope_exit([&] {
  9235. t2.join();
  9236. t.join();
  9237. ASSERT_FALSE(svr.is_running());
  9238. });
  9239. svr.wait_until_ready();
  9240. ssl_svr.wait_until_ready();
  9241. Client cli("127.0.0.1", PORT);
  9242. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9243. cli.enable_server_certificate_verification(true);
  9244. cli.set_follow_location(true);
  9245. cli.set_connection_timeout(30);
  9246. auto res = cli.Get("/index");
  9247. ASSERT_TRUE(res);
  9248. ASSERT_EQ(StatusCode::OK_200, res->status);
  9249. }
  9250. TEST(SSLClientRedirectTest, CertFile) {
  9251. auto ssl_port = PORT + 1;
  9252. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9253. ASSERT_TRUE(ssl_svr1.is_valid());
  9254. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9255. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9256. "/index");
  9257. ssl_svr1.stop();
  9258. });
  9259. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9260. ASSERT_TRUE(ssl_svr2.is_valid());
  9261. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9262. res.set_content("test", "text/plain");
  9263. ssl_svr2.stop();
  9264. });
  9265. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9266. thread t2 =
  9267. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9268. auto se = detail::scope_exit([&] {
  9269. t2.join();
  9270. t.join();
  9271. ASSERT_FALSE(ssl_svr1.is_running());
  9272. });
  9273. ssl_svr1.wait_until_ready();
  9274. ssl_svr2.wait_until_ready();
  9275. SSLClient cli("127.0.0.1", PORT);
  9276. std::string cert;
  9277. read_file(SERVER_CERT2_FILE, cert);
  9278. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9279. cli.enable_server_certificate_verification(true);
  9280. cli.set_follow_location(true);
  9281. cli.set_connection_timeout(30);
  9282. auto res = cli.Get("/index");
  9283. ASSERT_TRUE(res);
  9284. ASSERT_EQ(StatusCode::OK_200, res->status);
  9285. }
  9286. #endif
  9287. #ifdef CPPHTTPLIB_SSL_ENABLED
  9288. // Test that set_ca_cert_store() skips system certs (consistent with
  9289. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9290. // should be trusted - system certs should NOT be loaded.
  9291. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9292. // Load a specific cert that is NOT a system CA cert
  9293. std::string cert;
  9294. read_file(SERVER_CERT2_FILE, cert);
  9295. SSLClient cli("google.com");
  9296. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9297. cli.enable_server_certificate_verification(true);
  9298. // This should FAIL because:
  9299. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9300. // 2. System certs should NOT be loaded when custom store is set
  9301. // If system certs WERE loaded, this would succeed
  9302. auto res = cli.Get("/");
  9303. ASSERT_FALSE(res);
  9304. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9305. }
  9306. TEST(MultipartFormDataTest, LargeData) {
  9307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9308. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9309. const ContentReader &content_reader) {
  9310. if (req.is_multipart_form_data()) {
  9311. std::vector<FormData> items;
  9312. content_reader(
  9313. [&](const FormData &file) {
  9314. items.push_back(file);
  9315. return true;
  9316. },
  9317. [&](const char *data, size_t data_length) {
  9318. items.back().content.append(data, data_length);
  9319. return true;
  9320. });
  9321. EXPECT_TRUE(std::string(items[0].name) == "document");
  9322. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9323. EXPECT_TRUE(items[0].filename == "2MB_data");
  9324. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9325. EXPECT_TRUE(items[1].name == "hello");
  9326. EXPECT_TRUE(items[1].content == "world");
  9327. EXPECT_TRUE(items[1].filename == "");
  9328. EXPECT_TRUE(items[1].content_type == "");
  9329. } else {
  9330. std::string body;
  9331. content_reader([&](const char *data, size_t data_length) {
  9332. body.append(data, data_length);
  9333. return true;
  9334. });
  9335. }
  9336. });
  9337. auto port = svr.bind_to_any_port(HOST);
  9338. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9339. auto se = detail::scope_exit([&] {
  9340. svr.stop();
  9341. t.join();
  9342. ASSERT_FALSE(svr.is_running());
  9343. });
  9344. svr.wait_until_ready();
  9345. {
  9346. std::string data(1024 * 1024 * 2, '.');
  9347. std::stringstream buffer;
  9348. buffer << data;
  9349. SSLClient cli(HOST, port);
  9350. cli.enable_server_certificate_verification(false);
  9351. UploadFormDataItems items{
  9352. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9353. {"hello", "world", "", ""},
  9354. };
  9355. auto res = cli.Post("/post", items);
  9356. ASSERT_TRUE(res);
  9357. ASSERT_EQ(StatusCode::OK_200, res->status);
  9358. }
  9359. }
  9360. TEST(MultipartFormDataTest, DataProviderItems) {
  9361. std::random_device seed_gen;
  9362. std::mt19937 random(seed_gen());
  9363. std::string rand1;
  9364. rand1.resize(1000);
  9365. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9366. std::string rand2;
  9367. rand2.resize(3000);
  9368. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9370. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9371. const ContentReader &content_reader) {
  9372. ASSERT_FALSE(req.is_multipart_form_data());
  9373. std::string body;
  9374. content_reader([&](const char *data, size_t data_length) {
  9375. body.append(data, data_length);
  9376. return true;
  9377. });
  9378. EXPECT_EQ(body, "");
  9379. });
  9380. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9381. const ContentReader &content_reader) {
  9382. ASSERT_TRUE(req.is_multipart_form_data());
  9383. std::vector<FormData> items;
  9384. content_reader(
  9385. [&](const FormData &file) {
  9386. items.push_back(file);
  9387. return true;
  9388. },
  9389. [&](const char *data, size_t data_length) {
  9390. items.back().content.append(data, data_length);
  9391. return true;
  9392. });
  9393. ASSERT_TRUE(items.size() == 2);
  9394. EXPECT_EQ(std::string(items[0].name), "name1");
  9395. EXPECT_EQ(items[0].content, "Testing123");
  9396. EXPECT_EQ(items[0].filename, "filename1");
  9397. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9398. EXPECT_EQ(items[1].name, "name2");
  9399. EXPECT_EQ(items[1].content, "Testing456");
  9400. EXPECT_EQ(items[1].filename, "");
  9401. EXPECT_EQ(items[1].content_type, "");
  9402. });
  9403. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9404. const ContentReader &content_reader) {
  9405. ASSERT_TRUE(req.is_multipart_form_data());
  9406. std::vector<FormData> items;
  9407. content_reader(
  9408. [&](const FormData &file) {
  9409. items.push_back(file);
  9410. return true;
  9411. },
  9412. [&](const char *data, size_t data_length) {
  9413. items.back().content.append(data, data_length);
  9414. return true;
  9415. });
  9416. ASSERT_TRUE(items.size() == 2);
  9417. EXPECT_EQ(items[0].name, "name3");
  9418. EXPECT_EQ(items[0].content, rand1);
  9419. EXPECT_EQ(items[0].filename, "filename3");
  9420. EXPECT_EQ(items[0].content_type, "");
  9421. EXPECT_EQ(items[1].name, "name4");
  9422. EXPECT_EQ(items[1].content, rand2);
  9423. EXPECT_EQ(items[1].filename, "filename4");
  9424. EXPECT_EQ(items[1].content_type, "");
  9425. });
  9426. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9427. const ContentReader &content_reader) {
  9428. ASSERT_TRUE(req.is_multipart_form_data());
  9429. std::vector<FormData> items;
  9430. content_reader(
  9431. [&](const FormData &file) {
  9432. items.push_back(file);
  9433. return true;
  9434. },
  9435. [&](const char *data, size_t data_length) {
  9436. items.back().content.append(data, data_length);
  9437. return true;
  9438. });
  9439. ASSERT_TRUE(items.size() == 4);
  9440. EXPECT_EQ(std::string(items[0].name), "name1");
  9441. EXPECT_EQ(items[0].content, "Testing123");
  9442. EXPECT_EQ(items[0].filename, "filename1");
  9443. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9444. EXPECT_EQ(items[1].name, "name2");
  9445. EXPECT_EQ(items[1].content, "Testing456");
  9446. EXPECT_EQ(items[1].filename, "");
  9447. EXPECT_EQ(items[1].content_type, "");
  9448. EXPECT_EQ(items[2].name, "name3");
  9449. EXPECT_EQ(items[2].content, rand1);
  9450. EXPECT_EQ(items[2].filename, "filename3");
  9451. EXPECT_EQ(items[2].content_type, "");
  9452. EXPECT_EQ(items[3].name, "name4");
  9453. EXPECT_EQ(items[3].content, rand2);
  9454. EXPECT_EQ(items[3].filename, "filename4");
  9455. EXPECT_EQ(items[3].content_type, "");
  9456. });
  9457. auto port = svr.bind_to_any_port("localhost");
  9458. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. {
  9466. SSLClient cli("localhost", port);
  9467. cli.enable_server_certificate_verification(false);
  9468. UploadFormDataItems items{
  9469. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9470. {"name2", "Testing456", "", ""}, // not a file
  9471. };
  9472. {
  9473. auto res = cli.Post("/post-none", {}, {}, {});
  9474. ASSERT_TRUE(res);
  9475. ASSERT_EQ(StatusCode::OK_200, res->status);
  9476. }
  9477. FormDataProviderItems providers;
  9478. {
  9479. auto res =
  9480. cli.Post("/post-items", {}, items, providers); // empty providers
  9481. ASSERT_TRUE(res);
  9482. ASSERT_EQ(StatusCode::OK_200, res->status);
  9483. }
  9484. providers.push_back({"name3",
  9485. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9486. // test the offset is given correctly at each step
  9487. if (!offset)
  9488. sink.os.write(rand1.data(), 30);
  9489. else if (offset == 30)
  9490. sink.os.write(rand1.data() + 30, 300);
  9491. else if (offset == 330)
  9492. sink.os.write(rand1.data() + 330, 670);
  9493. else if (offset == rand1.size())
  9494. sink.done();
  9495. return true;
  9496. },
  9497. "filename3",
  9498. {}});
  9499. providers.push_back({"name4",
  9500. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9501. // test the offset is given correctly at each step
  9502. if (!offset)
  9503. sink.os.write(rand2.data(), 2000);
  9504. else if (offset == 2000)
  9505. sink.os.write(rand2.data() + 2000, 1);
  9506. else if (offset == 2001)
  9507. sink.os.write(rand2.data() + 2001, 999);
  9508. else if (offset == rand2.size())
  9509. sink.done();
  9510. return true;
  9511. },
  9512. "filename4",
  9513. {}});
  9514. {
  9515. auto res = cli.Post("/post-providers", {}, {}, providers);
  9516. ASSERT_TRUE(res);
  9517. ASSERT_EQ(StatusCode::OK_200, res->status);
  9518. }
  9519. {
  9520. auto res = cli.Post("/post-both", {}, items, providers);
  9521. ASSERT_TRUE(res);
  9522. ASSERT_EQ(StatusCode::OK_200, res->status);
  9523. }
  9524. }
  9525. }
  9526. TEST(MultipartFormDataTest, BadHeader) {
  9527. Server svr;
  9528. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9529. res.set_content("ok", "text/plain");
  9530. });
  9531. thread t = thread([&] { svr.listen(HOST, PORT); });
  9532. auto se = detail::scope_exit([&] {
  9533. svr.stop();
  9534. t.join();
  9535. ASSERT_FALSE(svr.is_running());
  9536. });
  9537. svr.wait_until_ready();
  9538. const std::string body =
  9539. "This is the preamble. It is to be ignored, though it\r\n"
  9540. "is a handy place for composition agents to include an\r\n"
  9541. "explanatory note to non-MIME conformant readers.\r\n"
  9542. "\r\n"
  9543. "\r\n"
  9544. "--simple boundary\r\n"
  9545. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9546. ": BAD...\r\n"
  9547. "\r\n"
  9548. "value1\r\n"
  9549. "--simple boundary\r\n"
  9550. "Content-Disposition: form-data; name=\"field2\"; "
  9551. "filename=\"example.txt\"\r\n"
  9552. "\r\n"
  9553. "value2\r\n"
  9554. "--simple boundary--\r\n"
  9555. "This is the epilogue. It is also to be ignored.\r\n";
  9556. std::string content_type =
  9557. R"(multipart/form-data; boundary="simple boundary")";
  9558. Client cli(HOST, PORT);
  9559. auto res = cli.Post("/post", body, content_type.c_str());
  9560. ASSERT_TRUE(res);
  9561. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9562. }
  9563. TEST(MultipartFormDataTest, WithPreamble) {
  9564. Server svr;
  9565. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9566. res.set_content("ok", "text/plain");
  9567. });
  9568. thread t = thread([&] { svr.listen(HOST, PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. t.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.wait_until_ready();
  9575. const std::string body =
  9576. "This is the preamble. It is to be ignored, though it\r\n"
  9577. "is a handy place for composition agents to include an\r\n"
  9578. "explanatory note to non-MIME conformant readers.\r\n"
  9579. "\r\n"
  9580. "\r\n"
  9581. "--simple boundary\r\n"
  9582. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9583. "\r\n"
  9584. "value1\r\n"
  9585. "--simple boundary\r\n"
  9586. "Content-Disposition: form-data; name=\"field2\"; "
  9587. "filename=\"example.txt\"\r\n"
  9588. "\r\n"
  9589. "value2\r\n"
  9590. "--simple boundary--\r\n"
  9591. "This is the epilogue. It is also to be ignored.\r\n";
  9592. std::string content_type =
  9593. R"(multipart/form-data; boundary="simple boundary")";
  9594. Client cli(HOST, PORT);
  9595. auto res = cli.Post("/post", body, content_type.c_str());
  9596. ASSERT_TRUE(res);
  9597. EXPECT_EQ(StatusCode::OK_200, res->status);
  9598. }
  9599. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9601. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9602. const ContentReader &content_reader) {
  9603. if (req.is_multipart_form_data()) {
  9604. std::vector<FormData> items;
  9605. content_reader(
  9606. [&](const FormData &file) {
  9607. items.push_back(file);
  9608. return true;
  9609. },
  9610. [&](const char *data, size_t data_length) {
  9611. items.back().content.append(data, data_length);
  9612. return true;
  9613. });
  9614. EXPECT_TRUE(std::string(items[0].name) == "document");
  9615. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9616. EXPECT_TRUE(items[0].filename == "2MB_data");
  9617. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9618. EXPECT_TRUE(items[1].name == "hello");
  9619. EXPECT_TRUE(items[1].content == "world");
  9620. EXPECT_TRUE(items[1].filename == "");
  9621. EXPECT_TRUE(items[1].content_type == "");
  9622. } else {
  9623. std::string body;
  9624. content_reader([&](const char *data, size_t data_length) {
  9625. body.append(data, data_length);
  9626. return true;
  9627. });
  9628. }
  9629. });
  9630. auto port = svr.bind_to_any_port("localhost");
  9631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9632. auto se = detail::scope_exit([&] {
  9633. svr.stop();
  9634. t.join();
  9635. ASSERT_FALSE(svr.is_running());
  9636. });
  9637. svr.wait_until_ready();
  9638. {
  9639. std::string data(1024 * 1024 * 2, '.');
  9640. std::stringstream buffer;
  9641. buffer << data;
  9642. SSLClient cli("localhost", port);
  9643. cli.enable_server_certificate_verification(false);
  9644. UploadFormDataItems items{
  9645. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9646. {"hello", "world", "", ""},
  9647. };
  9648. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9649. ASSERT_TRUE(res);
  9650. ASSERT_EQ(StatusCode::OK_200, res->status);
  9651. }
  9652. }
  9653. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9654. std::string data(1024 * 1024 * 2, '&');
  9655. std::stringstream buffer;
  9656. buffer << data;
  9657. Client cli("https://localhost:8080");
  9658. UploadFormDataItems items{
  9659. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9660. {"hello", "world", "", ""},
  9661. };
  9662. for (const char &c : " \t\r\n") {
  9663. auto res =
  9664. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9665. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9666. ASSERT_FALSE(res);
  9667. }
  9668. }
  9669. TEST(MultipartFormDataTest, PutFormData) {
  9670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9671. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9672. const ContentReader &content_reader) {
  9673. if (req.is_multipart_form_data()) {
  9674. std::vector<FormData> items;
  9675. content_reader(
  9676. [&](const FormData &file) {
  9677. items.push_back(file);
  9678. return true;
  9679. },
  9680. [&](const char *data, size_t data_length) {
  9681. items.back().content.append(data, data_length);
  9682. return true;
  9683. });
  9684. EXPECT_TRUE(std::string(items[0].name) == "document");
  9685. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9686. EXPECT_TRUE(items[0].filename == "2MB_data");
  9687. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9688. EXPECT_TRUE(items[1].name == "hello");
  9689. EXPECT_TRUE(items[1].content == "world");
  9690. EXPECT_TRUE(items[1].filename == "");
  9691. EXPECT_TRUE(items[1].content_type == "");
  9692. } else {
  9693. std::string body;
  9694. content_reader([&](const char *data, size_t data_length) {
  9695. body.append(data, data_length);
  9696. return true;
  9697. });
  9698. }
  9699. });
  9700. auto port = svr.bind_to_any_port("localhost");
  9701. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9702. auto se = detail::scope_exit([&] {
  9703. svr.stop();
  9704. t.join();
  9705. ASSERT_FALSE(svr.is_running());
  9706. });
  9707. svr.wait_until_ready();
  9708. {
  9709. std::string data(1024 * 1024 * 2, '&');
  9710. std::stringstream buffer;
  9711. buffer << data;
  9712. SSLClient cli("localhost", port);
  9713. cli.enable_server_certificate_verification(false);
  9714. UploadFormDataItems items{
  9715. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9716. {"hello", "world", "", ""},
  9717. };
  9718. auto res = cli.Put("/put", items);
  9719. ASSERT_TRUE(res);
  9720. ASSERT_EQ(StatusCode::OK_200, res->status);
  9721. }
  9722. }
  9723. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9725. svr.Put("/put_customboundary",
  9726. [&](const Request &req, const Response & /*res*/,
  9727. const ContentReader &content_reader) {
  9728. if (req.is_multipart_form_data()) {
  9729. std::vector<FormData> items;
  9730. content_reader(
  9731. [&](const FormData &file) {
  9732. items.push_back(file);
  9733. return true;
  9734. },
  9735. [&](const char *data, size_t data_length) {
  9736. items.back().content.append(data, data_length);
  9737. return true;
  9738. });
  9739. EXPECT_TRUE(std::string(items[0].name) == "document");
  9740. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9741. EXPECT_TRUE(items[0].filename == "2MB_data");
  9742. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9743. EXPECT_TRUE(items[1].name == "hello");
  9744. EXPECT_TRUE(items[1].content == "world");
  9745. EXPECT_TRUE(items[1].filename == "");
  9746. EXPECT_TRUE(items[1].content_type == "");
  9747. } else {
  9748. std::string body;
  9749. content_reader([&](const char *data, size_t data_length) {
  9750. body.append(data, data_length);
  9751. return true;
  9752. });
  9753. }
  9754. });
  9755. auto port = svr.bind_to_any_port("localhost");
  9756. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9757. auto se = detail::scope_exit([&] {
  9758. svr.stop();
  9759. t.join();
  9760. ASSERT_FALSE(svr.is_running());
  9761. });
  9762. svr.wait_until_ready();
  9763. {
  9764. std::string data(1024 * 1024 * 2, '&');
  9765. std::stringstream buffer;
  9766. buffer << data;
  9767. SSLClient cli("localhost", port);
  9768. cli.enable_server_certificate_verification(false);
  9769. UploadFormDataItems items{
  9770. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9771. {"hello", "world", "", ""},
  9772. };
  9773. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9774. ASSERT_TRUE(res);
  9775. ASSERT_EQ(StatusCode::OK_200, res->status);
  9776. }
  9777. }
  9778. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9779. std::string data(1024 * 1024 * 2, '&');
  9780. std::stringstream buffer;
  9781. buffer << data;
  9782. Client cli("https://localhost:8080");
  9783. cli.enable_server_certificate_verification(false);
  9784. UploadFormDataItems items{
  9785. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9786. {"hello", "world", "", ""},
  9787. };
  9788. for (const char &c : " \t\r\n") {
  9789. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9790. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9791. ASSERT_FALSE(res);
  9792. }
  9793. }
  9794. TEST(MultipartFormDataTest, AlternateFilename) {
  9795. auto handled = false;
  9796. Server svr;
  9797. svr.Post("/test", [&](const Request &req, Response &res) {
  9798. ASSERT_EQ(2u, req.form.files.size());
  9799. ASSERT_EQ(1u, req.form.fields.size());
  9800. // Test files
  9801. const auto &file1 = req.form.get_file("file1");
  9802. ASSERT_EQ("file1", file1.name);
  9803. ASSERT_EQ("A.txt", file1.filename);
  9804. ASSERT_EQ("text/plain", file1.content_type);
  9805. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9806. const auto &file2 = req.form.get_file("file2");
  9807. ASSERT_EQ("file2", file2.name);
  9808. ASSERT_EQ("a.html", file2.filename);
  9809. ASSERT_EQ("text/html", file2.content_type);
  9810. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9811. file2.content);
  9812. // Test text field
  9813. const auto &text = req.form.get_field("text");
  9814. ASSERT_EQ("text default", text);
  9815. res.set_content("ok", "text/plain");
  9816. handled = true;
  9817. });
  9818. thread t = thread([&] { svr.listen(HOST, PORT); });
  9819. auto se = detail::scope_exit([&] {
  9820. svr.stop();
  9821. t.join();
  9822. ASSERT_FALSE(svr.is_running());
  9823. ASSERT_TRUE(handled);
  9824. });
  9825. svr.wait_until_ready();
  9826. auto req = "POST /test HTTP/1.1\r\n"
  9827. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9828. "Content-Length: 399\r\n"
  9829. "\r\n"
  9830. "----------\r\n"
  9831. "Content-Disposition: form-data; name=\"text\"\r\n"
  9832. "\r\n"
  9833. "text default\r\n"
  9834. "----------\r\n"
  9835. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9836. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9837. "Content-Type: text/plain\r\n"
  9838. "\r\n"
  9839. "Content of a.txt.\r\n"
  9840. "\r\n"
  9841. "----------\r\n"
  9842. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9843. "\"a.html\"\r\n"
  9844. "Content-Type: text/html\r\n"
  9845. "\r\n"
  9846. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9847. "\r\n"
  9848. "------------\r\n";
  9849. ASSERT_TRUE(send_request(1, req));
  9850. }
  9851. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9852. auto handled = false;
  9853. Server svr;
  9854. svr.Post("/test", [&](const Request &req, Response &res) {
  9855. // Case-insensitive "utf-8''" prefix with a long value
  9856. const auto &file = req.form.get_file("file1");
  9857. ASSERT_EQ("file1", file.name);
  9858. // 8000 chars exercises both the Content-Disposition parser and the
  9859. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9860. // Prior to the fix, std::regex_match on this header would cause O(N)
  9861. // stack recursion in libstdc++, leading to SIGSEGV.
  9862. std::string expected_filename(8000, 'A');
  9863. ASSERT_EQ(expected_filename, file.filename);
  9864. res.set_content("ok", "text/plain");
  9865. handled = true;
  9866. });
  9867. thread t = thread([&] { svr.listen(HOST, PORT); });
  9868. auto se = detail::scope_exit([&] {
  9869. svr.stop();
  9870. t.join();
  9871. ASSERT_FALSE(svr.is_running());
  9872. ASSERT_TRUE(handled);
  9873. });
  9874. svr.wait_until_ready();
  9875. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9876. // Regression test for GHSA-qq6v-r583-3h69
  9877. std::string long_filename(8000, 'A');
  9878. std::string body = "----------\r\n"
  9879. "Content-Disposition: form-data; name=\"file1\"; "
  9880. "filename*=\"Utf-8''" +
  9881. long_filename +
  9882. "\"\r\n"
  9883. "\r\n"
  9884. "hello\r\n"
  9885. "------------\r\n";
  9886. auto req = "POST /test HTTP/1.1\r\n"
  9887. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9888. "Content-Length: " +
  9889. std::to_string(body.size()) + "\r\n\r\n" + body;
  9890. ASSERT_TRUE(send_request(1, req));
  9891. }
  9892. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9893. auto handled = false;
  9894. Server svr;
  9895. svr.Post("/test", [&](const Request &req, Response &) {
  9896. ASSERT_EQ(2u, req.form.fields.size());
  9897. const auto &text1 = req.form.get_field("text1");
  9898. ASSERT_EQ("text1", text1);
  9899. const auto &text2 = req.form.get_field("text2");
  9900. ASSERT_EQ("text2", text2);
  9901. handled = true;
  9902. });
  9903. thread t = thread([&] { svr.listen(HOST, PORT); });
  9904. auto se = detail::scope_exit([&] {
  9905. svr.stop();
  9906. t.join();
  9907. ASSERT_FALSE(svr.is_running());
  9908. ASSERT_TRUE(handled);
  9909. });
  9910. svr.wait_until_ready();
  9911. auto req = "POST /test HTTP/1.1\r\n"
  9912. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9913. "Content-Length: 146\r\n"
  9914. "\r\n----------\r\n"
  9915. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9916. "\r\n"
  9917. "text1"
  9918. "\r\n----------\r\n"
  9919. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9920. "\r\n"
  9921. "text2"
  9922. "\r\n------------";
  9923. std::string response;
  9924. ASSERT_TRUE(send_request(1, req, &response));
  9925. ASSERT_EQ("200", response.substr(9, 3));
  9926. }
  9927. TEST(MultipartFormDataTest, ContentLength) {
  9928. auto handled = false;
  9929. Server svr;
  9930. svr.Post("/test", [&](const Request &req, Response &) {
  9931. ASSERT_EQ(2u, req.form.fields.size());
  9932. const auto &text1 = req.form.get_field("text1");
  9933. ASSERT_EQ("text1", text1);
  9934. const auto &text2 = req.form.get_field("text2");
  9935. ASSERT_EQ("text2", text2);
  9936. handled = true;
  9937. });
  9938. thread t = thread([&] { svr.listen(HOST, PORT); });
  9939. auto se = detail::scope_exit([&] {
  9940. svr.stop();
  9941. t.join();
  9942. ASSERT_FALSE(svr.is_running());
  9943. ASSERT_TRUE(handled);
  9944. });
  9945. svr.wait_until_ready();
  9946. auto req = "POST /test HTTP/1.1\r\n"
  9947. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9948. "Content-Length: 167\r\n"
  9949. "\r\n----------\r\n"
  9950. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9951. "Content-Length: 5\r\n"
  9952. "\r\n"
  9953. "text1"
  9954. "\r\n----------\r\n"
  9955. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9956. "\r\n"
  9957. "text2"
  9958. "\r\n------------\r\n";
  9959. std::string response;
  9960. ASSERT_TRUE(send_request(1, req, &response));
  9961. ASSERT_EQ("200", response.substr(9, 3));
  9962. }
  9963. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9964. auto handled = false;
  9965. Server svr;
  9966. svr.Post("/test", [&](const Request &req, Response &) {
  9967. ASSERT_EQ(2u, req.form.fields.size());
  9968. const auto &text1 = req.form.get_field("text1");
  9969. ASSERT_EQ("text1", text1);
  9970. // TODO: Add header access for text fields if needed
  9971. const auto &text2 = req.form.get_field("text2");
  9972. ASSERT_EQ("text2", text2);
  9973. // TODO: Header access for text fields needs to be implemented
  9974. // auto &headers = it->second.headers;
  9975. // ASSERT_EQ(3U, headers.size());
  9976. // auto custom_header = headers.find("x-whatever");
  9977. // ASSERT_TRUE(custom_header != headers.end());
  9978. // ASSERT_NE("customvalue", custom_header->second);
  9979. // ASSERT_EQ("CustomValue", custom_header->second);
  9980. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9981. handled = true;
  9982. });
  9983. thread t = thread([&] { svr.listen(HOST, PORT); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. t.join();
  9987. ASSERT_FALSE(svr.is_running());
  9988. ASSERT_TRUE(handled);
  9989. });
  9990. svr.wait_until_ready();
  9991. auto req = "POST /test HTTP/1.1\r\n"
  9992. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9993. "Content-Length: 232\r\n"
  9994. "\r\n----------\r\n"
  9995. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9996. "Content-Length: 5\r\n"
  9997. "X-Test: 1\r\n"
  9998. "\r\n"
  9999. "text1"
  10000. "\r\n----------\r\n"
  10001. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10002. "Content-Type: text/plain\r\n"
  10003. "X-Whatever: CustomValue\r\n"
  10004. "\r\n"
  10005. "text2"
  10006. "\r\n------------\r\n"
  10007. "That should be disregarded. Not even read";
  10008. std::string response;
  10009. ASSERT_TRUE(send_request(1, req, &response));
  10010. ASSERT_EQ("200", response.substr(9, 3));
  10011. }
  10012. TEST(MultipartFormDataTest, LargeHeader) {
  10013. auto handled = false;
  10014. Server svr;
  10015. svr.Post("/test", [&](const Request &req, Response &) {
  10016. ASSERT_EQ(1u, req.form.fields.size());
  10017. const auto &text = req.form.get_field("name1");
  10018. ASSERT_EQ("text1", text);
  10019. handled = true;
  10020. });
  10021. thread t = thread([&] { svr.listen(HOST, PORT); });
  10022. auto se = detail::scope_exit([&] {
  10023. svr.stop();
  10024. t.join();
  10025. ASSERT_FALSE(svr.is_running());
  10026. ASSERT_TRUE(handled);
  10027. });
  10028. svr.wait_until_ready();
  10029. auto boundary = std::string("cpp-httplib-multipart-data");
  10030. std::string content = "--" + boundary +
  10031. "\r\n"
  10032. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10033. "\r\n"
  10034. "text1\r\n"
  10035. "--" +
  10036. boundary + "--\r\n";
  10037. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10038. "Content-Type: multipart/form-data;boundary=" +
  10039. boundary +
  10040. "\r\n"
  10041. "Content-Length: " +
  10042. std::to_string(content.size()) +
  10043. "\r\n"
  10044. "Dummy-Header: ";
  10045. std::string header_suffix = "\r\n"
  10046. "\r\n";
  10047. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10048. size_t header_dummy_size =
  10049. read_buff_size -
  10050. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10051. auto header_dummy = std::string(header_dummy_size, '@');
  10052. auto req = header_prefix + header_dummy + header_suffix + content;
  10053. std::string response;
  10054. ASSERT_TRUE(send_request(1, req, &response));
  10055. ASSERT_EQ("200", response.substr(9, 3));
  10056. }
  10057. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10058. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10059. // (not chunked Transfer-Encoding) after the streaming refactor.
  10060. auto handled = false;
  10061. Server svr;
  10062. svr.Post("/upload", [&](const Request &req, Response &res) {
  10063. auto cl_it = req.headers.find("Content-Length");
  10064. EXPECT_TRUE(cl_it != req.headers.end());
  10065. auto te_it = req.headers.find("Transfer-Encoding");
  10066. EXPECT_TRUE(te_it == req.headers.end());
  10067. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10068. res.set_content("ok", "text/plain");
  10069. handled = true;
  10070. });
  10071. auto port = svr.bind_to_any_port(HOST);
  10072. auto t = thread([&] { svr.listen_after_bind(); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. t.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. ASSERT_TRUE(handled);
  10078. });
  10079. svr.wait_until_ready();
  10080. UploadFormDataItems items = {
  10081. {"field1", "hello", "", "text/plain"},
  10082. {"file1", "world", "test.txt", "application/octet-stream"},
  10083. };
  10084. Client cli(HOST, port);
  10085. auto res = cli.Post("/upload", {}, items);
  10086. ASSERT_TRUE(res);
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. }
  10089. TEST(MultipartFormDataTest, MakeFileProvider) {
  10090. // Verify make_file_provider sends a file's contents correctly.
  10091. const std::string file_content(4096, 'Z');
  10092. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10093. {
  10094. std::ofstream ofs(tmp_path, std::ios::binary);
  10095. ofs.write(file_content.data(),
  10096. static_cast<std::streamsize>(file_content.size()));
  10097. }
  10098. auto handled = false;
  10099. Server svr;
  10100. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10101. const ContentReader &content_reader) {
  10102. ASSERT_TRUE(req.is_multipart_form_data());
  10103. std::vector<FormData> items;
  10104. content_reader(
  10105. [&](const FormData &file) {
  10106. items.push_back(file);
  10107. return true;
  10108. },
  10109. [&](const char *data, size_t data_length) {
  10110. items.back().content.append(data, data_length);
  10111. return true;
  10112. });
  10113. ASSERT_EQ(1u, items.size());
  10114. EXPECT_EQ("myfile", items[0].name);
  10115. EXPECT_EQ("data.bin", items[0].filename);
  10116. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10117. EXPECT_EQ(file_content, items[0].content);
  10118. handled = true;
  10119. });
  10120. auto port = svr.bind_to_any_port(HOST);
  10121. auto t = thread([&] { svr.listen_after_bind(); });
  10122. auto se = detail::scope_exit([&] {
  10123. svr.stop();
  10124. t.join();
  10125. ASSERT_FALSE(svr.is_running());
  10126. ASSERT_TRUE(handled);
  10127. std::remove(tmp_path.c_str());
  10128. });
  10129. svr.wait_until_ready();
  10130. FormDataProviderItems providers;
  10131. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10132. "application/octet-stream"));
  10133. Client cli(HOST, port);
  10134. auto res = cli.Post("/upload", {}, {}, providers);
  10135. ASSERT_TRUE(res);
  10136. EXPECT_EQ(StatusCode::OK_200, res->status);
  10137. }
  10138. TEST(MakeFileBodyTest, Basic) {
  10139. const std::string file_content(4096, 'Z');
  10140. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10141. {
  10142. std::ofstream ofs(tmp_path, std::ios::binary);
  10143. ofs.write(file_content.data(),
  10144. static_cast<std::streamsize>(file_content.size()));
  10145. }
  10146. auto handled = false;
  10147. Server svr;
  10148. svr.Post("/upload", [&](const Request &req, Response &res) {
  10149. EXPECT_EQ(file_content, req.body);
  10150. handled = true;
  10151. res.status = StatusCode::OK_200;
  10152. });
  10153. auto port = svr.bind_to_any_port(HOST);
  10154. auto t = thread([&] { svr.listen_after_bind(); });
  10155. auto se = detail::scope_exit([&] {
  10156. svr.stop();
  10157. t.join();
  10158. ASSERT_FALSE(svr.is_running());
  10159. ASSERT_TRUE(handled);
  10160. std::remove(tmp_path.c_str());
  10161. });
  10162. svr.wait_until_ready();
  10163. auto fb = make_file_body(tmp_path);
  10164. ASSERT_GT(fb.first, 0u);
  10165. Client cli(HOST, port);
  10166. auto res =
  10167. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10168. ASSERT_TRUE(res);
  10169. EXPECT_EQ(StatusCode::OK_200, res->status);
  10170. }
  10171. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10172. static constexpr unsigned int number_of_tasks{1000000};
  10173. std::atomic_uint count{0};
  10174. std::unique_ptr<TaskQueue> task_queue{
  10175. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10176. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10177. auto queued = task_queue->enqueue(
  10178. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10179. EXPECT_TRUE(queued);
  10180. }
  10181. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10182. task_queue->shutdown();
  10183. #else
  10184. EXPECT_NO_THROW(task_queue->shutdown());
  10185. #endif
  10186. EXPECT_EQ(number_of_tasks, count.load());
  10187. }
  10188. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10189. static constexpr unsigned int number_of_tasks{1000000};
  10190. static constexpr unsigned int qlimit{2};
  10191. unsigned int queued_count{0};
  10192. std::atomic_uint count{0};
  10193. std::unique_ptr<TaskQueue> task_queue{
  10194. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10195. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10196. if (task_queue->enqueue(
  10197. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10198. queued_count++;
  10199. }
  10200. }
  10201. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10202. task_queue->shutdown();
  10203. #else
  10204. EXPECT_NO_THROW(task_queue->shutdown());
  10205. #endif
  10206. EXPECT_EQ(queued_count, count.load());
  10207. EXPECT_TRUE(queued_count <= number_of_tasks);
  10208. EXPECT_TRUE(queued_count >= qlimit);
  10209. }
  10210. TEST(TaskQueueTest, MaxQueuedRequests) {
  10211. static constexpr unsigned int qlimit{3};
  10212. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10213. std::condition_variable sem_cv;
  10214. std::mutex sem_mtx;
  10215. int credits = 0;
  10216. bool queued;
  10217. /* Fill up the queue with tasks that will block until we give them credits to
  10218. * complete. */
  10219. for (unsigned int n = 0; n <= qlimit;) {
  10220. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10221. std::unique_lock<std::mutex> lock(sem_mtx);
  10222. while (credits <= 0) {
  10223. sem_cv.wait(lock);
  10224. }
  10225. /* Consume the credit and signal the test code if they are all gone. */
  10226. if (--credits == 0) { sem_cv.notify_one(); }
  10227. });
  10228. if (n < qlimit) {
  10229. /* The first qlimit enqueues must succeed. */
  10230. EXPECT_TRUE(queued);
  10231. } else {
  10232. /* The last one will succeed only when the worker thread
  10233. * starts and dequeues the first blocking task. Although
  10234. * not necessary for the correctness of this test, we sleep for
  10235. * a short while to avoid busy waiting. */
  10236. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10237. }
  10238. if (queued) { n++; }
  10239. }
  10240. /* Further enqueues must fail since the queue is full. */
  10241. for (auto i = 0; i < 4; i++) {
  10242. queued = task_queue->enqueue([] {});
  10243. EXPECT_FALSE(queued);
  10244. }
  10245. /* Give the credits to allow the previous tasks to complete. */
  10246. {
  10247. std::unique_lock<std::mutex> lock(sem_mtx);
  10248. credits += qlimit + 1;
  10249. }
  10250. sem_cv.notify_all();
  10251. /* Wait for all the credits to be consumed. */
  10252. {
  10253. std::unique_lock<std::mutex> lock(sem_mtx);
  10254. while (credits > 0) {
  10255. sem_cv.wait(lock);
  10256. }
  10257. }
  10258. /* Check that we are able again to enqueue at least qlimit tasks. */
  10259. for (unsigned int i = 0; i < qlimit; i++) {
  10260. queued = task_queue->enqueue([] {});
  10261. EXPECT_TRUE(queued);
  10262. }
  10263. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10264. task_queue->shutdown();
  10265. #else
  10266. EXPECT_NO_THROW(task_queue->shutdown());
  10267. #endif
  10268. }
  10269. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10270. Server svr;
  10271. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10272. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10273. });
  10274. svr.Get("/hello", [](const Request &req, Response &res) {
  10275. res.set_content(req.get_param_value("key"), "text/plain");
  10276. });
  10277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10278. auto se = detail::scope_exit([&] {
  10279. svr.stop();
  10280. thread.join();
  10281. ASSERT_FALSE(svr.is_running());
  10282. });
  10283. svr.wait_until_ready();
  10284. {
  10285. Client cli(HOST, PORT);
  10286. cli.set_follow_location(true);
  10287. auto res = cli.Get("/");
  10288. ASSERT_TRUE(res);
  10289. EXPECT_EQ(StatusCode::OK_200, res->status);
  10290. EXPECT_EQ("val&key2=val2", res->body);
  10291. }
  10292. }
  10293. #endif
  10294. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10295. Server svr;
  10296. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10297. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10298. });
  10299. svr.Get("/hello", [](const Request &req, Response &res) {
  10300. res.set_content(req.get_param_value("key"), "text/plain");
  10301. });
  10302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. thread.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. {
  10310. Client cli(HOST, PORT);
  10311. cli.set_follow_location(true);
  10312. auto res = cli.Get("/");
  10313. ASSERT_TRUE(res);
  10314. EXPECT_EQ(StatusCode::OK_200, res->status);
  10315. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10316. }
  10317. }
  10318. #ifdef CPPHTTPLIB_SSL_ENABLED
  10319. TEST(RedirectTest, Issue2185_Online) {
  10320. SSLClient client("github.com");
  10321. client.set_follow_location(true);
  10322. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10323. "Coollab-Windows.zip");
  10324. ASSERT_TRUE(res);
  10325. EXPECT_EQ(StatusCode::OK_200, res->status);
  10326. EXPECT_EQ(9920427U, res->body.size());
  10327. }
  10328. #endif
  10329. TEST(VulnerabilityTest, CRLFInjection) {
  10330. Server svr;
  10331. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10332. res.set_content("Hello 1", "text/plain");
  10333. });
  10334. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10335. res.set_content("Hello 2", "text/plain");
  10336. });
  10337. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10338. res.set_content("Hello 3", "text/plain");
  10339. });
  10340. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10341. res.set_content("Hello 4", "text/plain");
  10342. });
  10343. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10344. for (const auto &x : req.headers) {
  10345. auto key = x.first;
  10346. EXPECT_STRNE("evil", key.c_str());
  10347. }
  10348. });
  10349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10350. auto se = detail::scope_exit([&] {
  10351. svr.stop();
  10352. thread.join();
  10353. ASSERT_FALSE(svr.is_running());
  10354. });
  10355. svr.wait_until_ready();
  10356. {
  10357. Client cli(HOST, PORT);
  10358. cli.Post("/test1", "A=B",
  10359. "application/x-www-form-urlencoded\r\nevil: hello1");
  10360. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10361. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10362. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10363. }
  10364. }
  10365. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10366. auto server_thread = std::thread([] {
  10367. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10368. default_socket_options(srv);
  10369. sockaddr_in addr{};
  10370. addr.sin_family = AF_INET;
  10371. addr.sin_port = htons(PORT + 1);
  10372. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10373. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10374. ::listen(srv, 1);
  10375. sockaddr_in cli_addr{};
  10376. socklen_t cli_len = sizeof(cli_addr);
  10377. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10378. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10379. std::string buf_all;
  10380. char buf[2048];
  10381. ssize_t n;
  10382. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10383. buf_all.append(buf, static_cast<size_t>(n));
  10384. size_t pos;
  10385. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10386. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10387. auto e = request_block.find("\r\n");
  10388. if (e != std::string::npos) {
  10389. auto request_line = request_block.substr(0, e);
  10390. std::string msg =
  10391. "CRLF injection detected in request line: '" + request_line + "'";
  10392. EXPECT_FALSE(true) << msg;
  10393. }
  10394. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10395. ::send(cli,
  10396. #ifdef _WIN32
  10397. static_cast<const char *>(resp.c_str()),
  10398. static_cast<int>(resp.size()),
  10399. #else
  10400. resp.c_str(), resp.size(),
  10401. #endif
  10402. 0);
  10403. buf_all.erase(0, pos + 4);
  10404. }
  10405. }
  10406. detail::close_socket(cli);
  10407. detail::close_socket(srv);
  10408. });
  10409. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10410. auto cli = Client("127.0.0.1", PORT + 1);
  10411. auto headers = Headers{
  10412. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10413. {"Connection", "keep-alive"}};
  10414. auto res = cli.Get("/hi", headers);
  10415. EXPECT_FALSE(res);
  10416. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10417. server_thread.join();
  10418. }
  10419. TEST(PathParamsTest, StaticMatch) {
  10420. const auto pattern = "/users/all";
  10421. detail::PathParamsMatcher matcher(pattern);
  10422. Request request;
  10423. request.path = "/users/all";
  10424. ASSERT_TRUE(matcher.match(request));
  10425. std::unordered_map<std::string, std::string> expected_params = {};
  10426. EXPECT_EQ(request.path_params, expected_params);
  10427. }
  10428. TEST(PathParamsTest, StaticMismatch) {
  10429. const auto pattern = "/users/all";
  10430. detail::PathParamsMatcher matcher(pattern);
  10431. Request request;
  10432. request.path = "/users/1";
  10433. ASSERT_FALSE(matcher.match(request));
  10434. }
  10435. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10436. const auto pattern = "/users/:id/subscriptions";
  10437. detail::PathParamsMatcher matcher(pattern);
  10438. Request request;
  10439. request.path = "/users/42/subscriptions";
  10440. ASSERT_TRUE(matcher.match(request));
  10441. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10442. EXPECT_EQ(request.path_params, expected_params);
  10443. }
  10444. TEST(PathParamsTest, SingleParamInTheEnd) {
  10445. const auto pattern = "/users/:id";
  10446. detail::PathParamsMatcher matcher(pattern);
  10447. Request request;
  10448. request.path = "/users/24";
  10449. ASSERT_TRUE(matcher.match(request));
  10450. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10451. EXPECT_EQ(request.path_params, expected_params);
  10452. }
  10453. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10454. const auto pattern = "/users/:id/";
  10455. detail::PathParamsMatcher matcher(pattern);
  10456. Request request;
  10457. request.path = "/users/42/";
  10458. ASSERT_TRUE(matcher.match(request));
  10459. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10460. EXPECT_EQ(request.path_params, expected_params);
  10461. }
  10462. TEST(PathParamsTest, EmptyParam) {
  10463. const auto pattern = "/users/:id/";
  10464. detail::PathParamsMatcher matcher(pattern);
  10465. Request request;
  10466. request.path = "/users//";
  10467. ASSERT_TRUE(matcher.match(request));
  10468. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10469. EXPECT_EQ(request.path_params, expected_params);
  10470. }
  10471. TEST(PathParamsTest, FragmentMismatch) {
  10472. const auto pattern = "/users/:id/";
  10473. detail::PathParamsMatcher matcher(pattern);
  10474. Request request;
  10475. request.path = "/admins/24/";
  10476. ASSERT_FALSE(matcher.match(request));
  10477. }
  10478. TEST(PathParamsTest, ExtraFragments) {
  10479. const auto pattern = "/users/:id";
  10480. detail::PathParamsMatcher matcher(pattern);
  10481. Request request;
  10482. request.path = "/users/42/subscriptions";
  10483. ASSERT_FALSE(matcher.match(request));
  10484. }
  10485. TEST(PathParamsTest, MissingTrailingParam) {
  10486. const auto pattern = "/users/:id";
  10487. detail::PathParamsMatcher matcher(pattern);
  10488. Request request;
  10489. request.path = "/users";
  10490. ASSERT_FALSE(matcher.match(request));
  10491. }
  10492. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10493. const auto pattern = "/users/:id/subscriptions";
  10494. detail::PathParamsMatcher matcher(pattern);
  10495. Request request;
  10496. request.path = "/users/subscriptions";
  10497. ASSERT_FALSE(matcher.match(request));
  10498. }
  10499. TEST(PathParamsTest, MultipleParams) {
  10500. const auto pattern = "/users/:userid/subscriptions/:subid";
  10501. detail::PathParamsMatcher matcher(pattern);
  10502. Request request;
  10503. request.path = "/users/42/subscriptions/2";
  10504. ASSERT_TRUE(matcher.match(request));
  10505. std::unordered_map<std::string, std::string> expected_params = {
  10506. {"userid", "42"}, {"subid", "2"}};
  10507. EXPECT_EQ(request.path_params, expected_params);
  10508. }
  10509. TEST(PathParamsTest, SequenceOfParams) {
  10510. const auto pattern = "/values/:x/:y/:z";
  10511. detail::PathParamsMatcher matcher(pattern);
  10512. Request request;
  10513. request.path = "/values/1/2/3";
  10514. ASSERT_TRUE(matcher.match(request));
  10515. std::unordered_map<std::string, std::string> expected_params = {
  10516. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10517. EXPECT_EQ(request.path_params, expected_params);
  10518. }
  10519. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10520. const auto pattern = "/prefix:suffix";
  10521. detail::PathParamsMatcher matcher(pattern);
  10522. Request request;
  10523. request.path = "/prefix:suffix";
  10524. ASSERT_TRUE(matcher.match(request));
  10525. const std::unordered_map<std::string, std::string> expected_params = {};
  10526. EXPECT_EQ(request.path_params, expected_params);
  10527. }
  10528. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10529. // If ipv6 regex working, regex match codepath is taken.
  10530. // else port will default to 80 in Client impl
  10531. int clientImplMagicPort = 80;
  10532. int port = 4321;
  10533. // above ports must be different to avoid false negative
  10534. EXPECT_NE(clientImplMagicPort, port);
  10535. std::string ipV6TestURL = "http://[ff06::c3]";
  10536. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10537. CLIENT_PRIVATE_KEY_FILE);
  10538. EXPECT_EQ(cli.port(), port);
  10539. }
  10540. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10541. auto file_path = "./www/dir/index.html";
  10542. auto dir_path = "./www/dir";
  10543. detail::FileStat stat_file(file_path);
  10544. EXPECT_TRUE(stat_file.is_file());
  10545. EXPECT_FALSE(stat_file.is_dir());
  10546. detail::FileStat stat_dir(dir_path);
  10547. EXPECT_FALSE(stat_dir.is_file());
  10548. EXPECT_TRUE(stat_dir.is_dir());
  10549. }
  10550. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10551. // IPv4 with default HTTP port (80)
  10552. EXPECT_EQ("example.com",
  10553. detail::make_host_and_port_string("example.com", 80, false));
  10554. // IPv4 with default HTTPS port (443)
  10555. EXPECT_EQ("example.com",
  10556. detail::make_host_and_port_string("example.com", 443, true));
  10557. // IPv4 with non-default HTTP port
  10558. EXPECT_EQ("example.com:8080",
  10559. detail::make_host_and_port_string("example.com", 8080, false));
  10560. // IPv4 with non-default HTTPS port
  10561. EXPECT_EQ("example.com:8443",
  10562. detail::make_host_and_port_string("example.com", 8443, true));
  10563. // IPv6 with default HTTP port (80)
  10564. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10565. // IPv6 with default HTTPS port (443)
  10566. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10567. // IPv6 with non-default HTTP port
  10568. EXPECT_EQ("[::1]:8080",
  10569. detail::make_host_and_port_string("::1", 8080, false));
  10570. // IPv6 with non-default HTTPS port
  10571. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10572. // IPv6 full address with default port
  10573. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10574. detail::make_host_and_port_string(
  10575. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10576. // IPv6 full address with non-default port
  10577. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10578. detail::make_host_and_port_string(
  10579. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10580. // IPv6 localhost with non-default port
  10581. EXPECT_EQ("[::1]:3000",
  10582. detail::make_host_and_port_string("::1", 3000, false));
  10583. // IPv6 with zone ID (link-local address) with default port
  10584. EXPECT_EQ("[fe80::1%eth0]",
  10585. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10586. // IPv6 with zone ID (link-local address) with non-default port
  10587. EXPECT_EQ("[fe80::1%eth0]:8080",
  10588. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10589. // Edge case: Port 443 with is_ssl=false (should add port)
  10590. EXPECT_EQ("example.com:443",
  10591. detail::make_host_and_port_string("example.com", 443, false));
  10592. // Edge case: Port 80 with is_ssl=true (should add port)
  10593. EXPECT_EQ("example.com:80",
  10594. detail::make_host_and_port_string("example.com", 80, true));
  10595. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10596. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10597. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10598. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10599. // Security fix: Already bracketed IPv6 should not get double brackets
  10600. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10601. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10602. EXPECT_EQ("[::1]:8080",
  10603. detail::make_host_and_port_string("[::1]", 8080, false));
  10604. EXPECT_EQ("[2001:db8::1]:8080",
  10605. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10606. EXPECT_EQ("[fe80::1%eth0]",
  10607. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10608. EXPECT_EQ("[fe80::1%eth0]:8080",
  10609. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10610. // Edge case: Empty host (should return as-is)
  10611. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10612. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10613. // This is a known limitation but shouldn't crash
  10614. EXPECT_EQ("[host:name]",
  10615. detail::make_host_and_port_string("host:name", 80, false));
  10616. // Port number edge cases (no validation, but should not crash)
  10617. EXPECT_EQ("example.com:0",
  10618. detail::make_host_and_port_string("example.com", 0, false));
  10619. EXPECT_EQ("example.com:-1",
  10620. detail::make_host_and_port_string("example.com", -1, false));
  10621. EXPECT_EQ("example.com:65535",
  10622. detail::make_host_and_port_string("example.com", 65535, false));
  10623. EXPECT_EQ("example.com:65536",
  10624. detail::make_host_and_port_string("example.com", 65536, false));
  10625. }
  10626. #ifdef CPPHTTPLIB_SSL_ENABLED
  10627. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10628. httplib::SSLClient cli("roblox.com", 443);
  10629. cli.set_follow_location(true);
  10630. auto res = cli.Get("/");
  10631. ASSERT_TRUE(res);
  10632. EXPECT_EQ(StatusCode::OK_200, res->status);
  10633. }
  10634. #endif
  10635. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10636. Server svr;
  10637. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10638. EXPECT_EQ(res.status, 400);
  10639. });
  10640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10641. auto se = detail::scope_exit([&] {
  10642. svr.stop();
  10643. thread.join();
  10644. ASSERT_FALSE(svr.is_running());
  10645. });
  10646. svr.wait_until_ready();
  10647. Client cli(HOST, PORT);
  10648. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10649. }
  10650. TEST(InvalidHeaderCharsTest, is_field_name) {
  10651. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10652. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10653. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10654. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10655. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10656. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10657. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10658. EXPECT_FALSE(detail::fields::is_field_name(""));
  10659. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10660. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10661. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10662. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10663. }
  10664. TEST(InvalidHeaderCharsTest, is_field_value) {
  10665. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10666. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10667. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10668. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10669. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10670. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10671. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10672. EXPECT_TRUE(detail::fields::is_field_value(""));
  10673. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10674. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10675. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10676. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10677. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10678. }
  10679. TEST(InvalidHeaderCharsTest, OnServer) {
  10680. Server svr;
  10681. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10682. std::string header = "Not Set";
  10683. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10684. res.set_header(header, "value");
  10685. res.set_content("Page Content Page Content", "text/plain");
  10686. });
  10687. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10688. std::string header = "Not Set";
  10689. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10690. res.set_header("X-Test", header);
  10691. res.set_content("Page Content Page Content", "text/plain");
  10692. });
  10693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10694. auto se = detail::scope_exit([&] {
  10695. svr.stop();
  10696. thread.join();
  10697. ASSERT_FALSE(svr.is_running());
  10698. });
  10699. svr.wait_until_ready();
  10700. Client cli(HOST, PORT);
  10701. {
  10702. auto res = cli.Get(
  10703. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10704. ASSERT_TRUE(res);
  10705. EXPECT_EQ("Page Content Page Content", res->body);
  10706. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10707. }
  10708. {
  10709. auto res = cli.Get(
  10710. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10711. ASSERT_TRUE(res);
  10712. EXPECT_EQ("Page Content Page Content", res->body);
  10713. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10714. }
  10715. }
  10716. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10717. auto handled = false;
  10718. Server svr;
  10719. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10720. thread t = thread([&] { svr.listen(HOST, PORT); });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. t.join();
  10724. ASSERT_FALSE(svr.is_running());
  10725. ASSERT_FALSE(handled);
  10726. });
  10727. svr.wait_until_ready();
  10728. auto req = "POST /test HTTP/1.1\r\n"
  10729. "Content-Length: x\r\n"
  10730. "\r\n";
  10731. std::string response;
  10732. ASSERT_TRUE(send_request(1, req, &response));
  10733. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10734. response.substr(0, response.find("\r\n")));
  10735. }
  10736. #ifndef _WIN32
  10737. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10738. static constexpr char reject[] = "Unauthorized";
  10739. static constexpr char accept[] = "Upload accepted";
  10740. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10741. Server svr;
  10742. svr.set_expect_100_continue_handler(
  10743. [](const Request & /*req*/, Response &res) {
  10744. res.status = StatusCode::Unauthorized_401;
  10745. res.set_content(reject, "text/plain");
  10746. return res.status;
  10747. });
  10748. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10749. res.set_content(accept, "text/plain");
  10750. });
  10751. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10752. auto se = detail::scope_exit([&] {
  10753. svr.stop();
  10754. thread.join();
  10755. ASSERT_FALSE(svr.is_running());
  10756. });
  10757. svr.wait_until_ready();
  10758. {
  10759. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10760. curl_easy_init(), &curl_easy_cleanup};
  10761. ASSERT_NE(curl, nullptr);
  10762. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10763. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10764. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10765. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10766. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10767. &curl_slist_free_all};
  10768. ASSERT_NE(list, nullptr);
  10769. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10770. struct read_data {
  10771. size_t read_size;
  10772. size_t total_size;
  10773. } data = {0, total_size};
  10774. using read_callback_t =
  10775. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10776. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10777. void *userdata) -> size_t {
  10778. read_data *data = (read_data *)userdata;
  10779. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10780. std::fill_n(ptr, size * nmemb, 'A');
  10781. data->read_size += size * nmemb;
  10782. return size * nmemb;
  10783. };
  10784. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10785. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10786. std::vector<char> buffer;
  10787. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10788. using write_callback_t =
  10789. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10790. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10791. void *userdata) -> size_t {
  10792. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10793. buffer->reserve(buffer->size() + size * nmemb + 1);
  10794. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10795. return size * nmemb;
  10796. };
  10797. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10798. {
  10799. const auto res = curl_easy_perform(curl.get());
  10800. ASSERT_EQ(res, CURLE_OK);
  10801. }
  10802. {
  10803. auto response_code = long{};
  10804. const auto res =
  10805. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10806. ASSERT_EQ(res, CURLE_OK);
  10807. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10808. }
  10809. {
  10810. auto dl = curl_off_t{};
  10811. const auto res =
  10812. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10813. ASSERT_EQ(res, CURLE_OK);
  10814. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10815. }
  10816. {
  10817. buffer.push_back('\0');
  10818. ASSERT_STRCASEEQ(buffer.data(), reject);
  10819. }
  10820. }
  10821. }
  10822. #endif
  10823. template <typename S, typename C>
  10824. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10825. svr.Get("/stream", [&](const Request &, Response &res) {
  10826. auto data = new std::string("01234567890123456789");
  10827. res.set_content_provider(
  10828. data->size(), "text/plain",
  10829. [&, data](size_t offset, size_t length, DataSink &sink) {
  10830. const size_t DATA_CHUNK_SIZE = 4;
  10831. const auto &d = *data;
  10832. std::this_thread::sleep_for(std::chrono::seconds(1));
  10833. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10834. return true;
  10835. },
  10836. [data](bool success) {
  10837. EXPECT_FALSE(success);
  10838. delete data;
  10839. });
  10840. });
  10841. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10842. auto i = new size_t(0);
  10843. res.set_content_provider(
  10844. "text/plain",
  10845. [i](size_t, DataSink &sink) {
  10846. if (*i < 5) {
  10847. std::this_thread::sleep_for(std::chrono::seconds(1));
  10848. sink.write("abcd", 4);
  10849. (*i)++;
  10850. } else {
  10851. sink.done();
  10852. }
  10853. return true;
  10854. },
  10855. [i](bool success) {
  10856. EXPECT_FALSE(success);
  10857. delete i;
  10858. });
  10859. });
  10860. svr.Get("/chunked", [&](const Request &, Response &res) {
  10861. auto i = new size_t(0);
  10862. res.set_chunked_content_provider(
  10863. "text/plain",
  10864. [i](size_t, DataSink &sink) {
  10865. if (*i < 5) {
  10866. std::this_thread::sleep_for(std::chrono::seconds(1));
  10867. sink.os << "abcd";
  10868. (*i)++;
  10869. } else {
  10870. sink.done();
  10871. }
  10872. return true;
  10873. },
  10874. [i](bool success) {
  10875. EXPECT_FALSE(success);
  10876. delete i;
  10877. });
  10878. });
  10879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10880. auto se = detail::scope_exit([&] {
  10881. svr.stop();
  10882. listen_thread.join();
  10883. ASSERT_FALSE(svr.is_running());
  10884. });
  10885. svr.wait_until_ready();
  10886. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10887. {
  10888. auto start = std::chrono::steady_clock::now();
  10889. auto res = cli.Get("/stream");
  10890. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10891. std::chrono::steady_clock::now() - start)
  10892. .count();
  10893. ASSERT_FALSE(res);
  10894. EXPECT_EQ(Error::Read, res.error());
  10895. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10896. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10897. }
  10898. {
  10899. auto start = std::chrono::steady_clock::now();
  10900. auto res = cli.Get("/stream_without_length");
  10901. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10902. std::chrono::steady_clock::now() - start)
  10903. .count();
  10904. ASSERT_FALSE(res);
  10905. EXPECT_EQ(Error::Read, res.error());
  10906. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10907. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10908. }
  10909. {
  10910. auto start = std::chrono::steady_clock::now();
  10911. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10912. EXPECT_EQ("abcd", string(data, data_length));
  10913. return true;
  10914. });
  10915. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10916. std::chrono::steady_clock::now() - start)
  10917. .count();
  10918. ASSERT_FALSE(res);
  10919. EXPECT_EQ(Error::Read, res.error());
  10920. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10921. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10922. }
  10923. }
  10924. TEST(MaxTimeoutTest, ContentStream) {
  10925. time_t timeout = 2000;
  10926. time_t threshold = 200;
  10927. Server svr;
  10928. Client cli("localhost", PORT);
  10929. max_timeout_test(svr, cli, timeout, threshold);
  10930. }
  10931. #ifdef CPPHTTPLIB_SSL_ENABLED
  10932. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10933. time_t timeout = 2000;
  10934. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10936. SSLClient cli("localhost", PORT);
  10937. cli.enable_server_certificate_verification(false);
  10938. max_timeout_test(svr, cli, timeout, threshold);
  10939. }
  10940. #endif
  10941. class EventDispatcher {
  10942. public:
  10943. EventDispatcher() {}
  10944. bool wait_event(DataSink *sink) {
  10945. unique_lock<mutex> lk(m_);
  10946. int id = id_;
  10947. // Wait with timeout to prevent hanging if client disconnects
  10948. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10949. [&] { return cid_ == id; })) {
  10950. return false; // Timeout occurred
  10951. }
  10952. sink->write(message_.data(), message_.size());
  10953. return true;
  10954. }
  10955. void send_event(const string &message) {
  10956. lock_guard<mutex> lk(m_);
  10957. cid_ = id_++;
  10958. message_ = message;
  10959. cv_.notify_all();
  10960. }
  10961. private:
  10962. mutex m_;
  10963. condition_variable cv_;
  10964. atomic_int id_{0};
  10965. atomic_int cid_{-1};
  10966. string message_;
  10967. };
  10968. TEST(ClientInThreadTest, Issue2068) {
  10969. EventDispatcher ed;
  10970. Server svr;
  10971. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10972. res.set_chunked_content_provider("text/event-stream",
  10973. [&](size_t /*offset*/, DataSink &sink) {
  10974. return ed.wait_event(&sink);
  10975. });
  10976. });
  10977. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10978. svr.wait_until_ready();
  10979. thread event_thread([&] {
  10980. int id = 0;
  10981. while (svr.is_running()) {
  10982. this_thread::sleep_for(chrono::milliseconds(500));
  10983. std::stringstream ss;
  10984. ss << "data: " << id << "\n\n";
  10985. ed.send_event(ss.str());
  10986. id++;
  10987. }
  10988. });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. event_thread.join();
  10993. ASSERT_FALSE(svr.is_running());
  10994. });
  10995. {
  10996. auto client = detail::make_unique<Client>(HOST, PORT);
  10997. client->set_read_timeout(std::chrono::minutes(10));
  10998. std::atomic<bool> stop{false};
  10999. std::thread t([&] {
  11000. client->Get("/event1",
  11001. [&](const char *, size_t) -> bool { return !stop; });
  11002. });
  11003. std::this_thread::sleep_for(std::chrono::seconds(2));
  11004. stop = true;
  11005. client->stop();
  11006. t.join();
  11007. // Reset client after thread has finished
  11008. client.reset();
  11009. }
  11010. }
  11011. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11012. auto handled = false;
  11013. Server svr;
  11014. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11015. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11016. auto se = detail::scope_exit([&] {
  11017. svr.stop();
  11018. t.join();
  11019. ASSERT_FALSE(svr.is_running());
  11020. ASSERT_FALSE(handled);
  11021. });
  11022. svr.wait_until_ready();
  11023. // Two Content-Length headers with different values — must be rejected
  11024. auto req = "POST /test HTTP/1.1\r\n"
  11025. "Content-Length: 5\r\n"
  11026. "Content-Length: 10\r\n"
  11027. "\r\n"
  11028. "hello";
  11029. std::string response;
  11030. ASSERT_TRUE(send_request(1, req, &response));
  11031. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11032. response.substr(0, response.find("\r\n")));
  11033. }
  11034. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11035. auto handled = false;
  11036. Server svr;
  11037. svr.Post("/test", [&](const Request &, Response &res) {
  11038. handled = true;
  11039. res.set_content("ok", "text/plain");
  11040. });
  11041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11042. auto se = detail::scope_exit([&] {
  11043. svr.stop();
  11044. t.join();
  11045. ASSERT_FALSE(svr.is_running());
  11046. ASSERT_TRUE(handled);
  11047. });
  11048. svr.wait_until_ready();
  11049. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11050. auto req = "POST /test HTTP/1.1\r\n"
  11051. "Content-Length: 5\r\n"
  11052. "Content-Length: 5\r\n"
  11053. "\r\n"
  11054. "hello";
  11055. std::string response;
  11056. ASSERT_TRUE(send_request(1, req, &response));
  11057. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11058. }
  11059. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11060. Server svr;
  11061. svr.Get("/", [](const Request &req, Response &res) {
  11062. EXPECT_EQ(2U, req.trailers.size());
  11063. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11064. // Denied
  11065. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11066. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11067. // Accepted
  11068. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11069. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11070. EXPECT_TRUE(req.has_trailer("X-World"));
  11071. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11072. res.set_content("ok", "text/plain");
  11073. });
  11074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11075. auto se = detail::scope_exit([&] {
  11076. svr.stop();
  11077. t.join();
  11078. ASSERT_FALSE(svr.is_running());
  11079. });
  11080. svr.wait_until_ready();
  11081. const std::string req = "GET / HTTP/1.1\r\n"
  11082. "Transfer-Encoding: chunked\r\n"
  11083. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11084. "\r\n"
  11085. "0\r\n"
  11086. "Content-Length: 10\r\n"
  11087. "Host: internal.local\r\n"
  11088. "Content-Type: malicious/content\r\n"
  11089. "Cookie: any\r\n"
  11090. "Set-Cookie: any\r\n"
  11091. "X-Forwarded-For: attacker.com\r\n"
  11092. "X-Real-Ip: 1.1.1.1\r\n"
  11093. "X-Hello: hello\r\n"
  11094. "X-World: world\r\n"
  11095. "\r\n";
  11096. std::string res;
  11097. ASSERT_TRUE(send_request(1, req, &res));
  11098. }
  11099. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11100. Server svr;
  11101. std::string observed_remote_addr;
  11102. std::string observed_xff;
  11103. svr.Get("/ip", [&](const Request &req, Response &res) {
  11104. observed_remote_addr = req.remote_addr;
  11105. observed_xff = req.get_header_value("X-Forwarded-For");
  11106. res.set_content("ok", "text/plain");
  11107. });
  11108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. ASSERT_FALSE(svr.is_running());
  11113. });
  11114. svr.wait_until_ready();
  11115. Client cli(HOST, PORT);
  11116. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11117. ASSERT_TRUE(res);
  11118. EXPECT_EQ(StatusCode::OK_200, res->status);
  11119. EXPECT_EQ(observed_xff, "203.0.113.66");
  11120. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11121. observed_remote_addr == "127.0.0.1");
  11122. }
  11123. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11124. Server svr;
  11125. svr.set_trusted_proxies({"203.0.113.66"});
  11126. std::string observed_remote_addr;
  11127. std::string observed_xff;
  11128. svr.Get("/ip", [&](const Request &req, Response &res) {
  11129. observed_remote_addr = req.remote_addr;
  11130. observed_xff = req.get_header_value("X-Forwarded-For");
  11131. res.set_content("ok", "text/plain");
  11132. });
  11133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11134. auto se = detail::scope_exit([&] {
  11135. svr.stop();
  11136. t.join();
  11137. ASSERT_FALSE(svr.is_running());
  11138. });
  11139. svr.wait_until_ready();
  11140. Client cli(HOST, PORT);
  11141. auto res = cli.Get("/ip");
  11142. ASSERT_TRUE(res);
  11143. EXPECT_EQ(StatusCode::OK_200, res->status);
  11144. EXPECT_EQ(observed_xff, "");
  11145. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11146. observed_remote_addr == "127.0.0.1");
  11147. }
  11148. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11149. Server svr;
  11150. svr.set_trusted_proxies({"203.0.113.66"});
  11151. std::string observed_remote_addr;
  11152. std::string observed_xff;
  11153. svr.Get("/ip", [&](const Request &req, Response &res) {
  11154. observed_remote_addr = req.remote_addr;
  11155. observed_xff = req.get_header_value("X-Forwarded-For");
  11156. res.set_content("ok", "text/plain");
  11157. });
  11158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. Client cli(HOST, PORT);
  11166. auto res =
  11167. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11168. ASSERT_TRUE(res);
  11169. EXPECT_EQ(StatusCode::OK_200, res->status);
  11170. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11172. }
  11173. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11174. Server svr;
  11175. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11176. std::string observed_remote_addr;
  11177. std::string observed_xff;
  11178. svr.Get("/ip", [&](const Request &req, Response &res) {
  11179. observed_remote_addr = req.remote_addr;
  11180. observed_xff = req.get_header_value("X-Forwarded-For");
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11184. auto se = detail::scope_exit([&] {
  11185. svr.stop();
  11186. t.join();
  11187. ASSERT_FALSE(svr.is_running());
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. auto res = cli.Get(
  11192. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11193. ASSERT_TRUE(res);
  11194. EXPECT_EQ(StatusCode::OK_200, res->status);
  11195. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11196. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11197. }
  11198. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11199. Server svr;
  11200. svr.set_trusted_proxies({"192.0.2.45"});
  11201. std::string observed_remote_addr;
  11202. std::string observed_xff;
  11203. svr.Get("/ip", [&](const Request &req, Response &res) {
  11204. observed_remote_addr = req.remote_addr;
  11205. observed_xff = req.get_header_value("X-Forwarded-For");
  11206. res.set_content("ok", "text/plain");
  11207. });
  11208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11209. auto se = detail::scope_exit([&] {
  11210. svr.stop();
  11211. t.join();
  11212. ASSERT_FALSE(svr.is_running());
  11213. });
  11214. svr.wait_until_ready();
  11215. Client cli(HOST, PORT);
  11216. auto res =
  11217. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11218. ASSERT_TRUE(res);
  11219. EXPECT_EQ(StatusCode::OK_200, res->status);
  11220. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11221. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11222. }
  11223. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11224. Server svr;
  11225. svr.set_trusted_proxies({"192.0.2.45"});
  11226. std::string observed_remote_addr;
  11227. std::string observed_xff;
  11228. svr.Get("/ip", [&](const Request &req, Response &res) {
  11229. observed_remote_addr = req.remote_addr;
  11230. observed_xff = req.get_header_value("X-Forwarded-For");
  11231. res.set_content("ok", "text/plain");
  11232. });
  11233. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11234. auto se = detail::scope_exit([&] {
  11235. svr.stop();
  11236. t.join();
  11237. ASSERT_FALSE(svr.is_running());
  11238. });
  11239. svr.wait_until_ready();
  11240. Client cli(HOST, PORT);
  11241. auto res = cli.Get(
  11242. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11243. ASSERT_TRUE(res);
  11244. EXPECT_EQ(StatusCode::OK_200, res->status);
  11245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11247. }
  11248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11249. Server svr;
  11250. svr.set_trusted_proxies({"192.0.2.45"});
  11251. std::string observed_remote_addr;
  11252. std::string observed_xff;
  11253. svr.Get("/ip", [&](const Request &req, Response &res) {
  11254. observed_remote_addr = req.remote_addr;
  11255. observed_xff = req.get_header_value("X-Forwarded-For");
  11256. res.set_content("ok", "text/plain");
  11257. });
  11258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11259. auto se = detail::scope_exit([&] {
  11260. svr.stop();
  11261. t.join();
  11262. ASSERT_FALSE(svr.is_running());
  11263. });
  11264. svr.wait_until_ready();
  11265. std::string raw_req =
  11266. "GET /ip HTTP/1.1\r\n"
  11267. "Host: localhost\r\n"
  11268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11269. "Connection: close\r\n"
  11270. "\r\n";
  11271. std::string out;
  11272. ASSERT_TRUE(send_request(5, raw_req, &out));
  11273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11274. // Header parser trims surrounding whitespace of the header value
  11275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11277. }
  11278. #ifndef _WIN32
  11279. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11280. Server svr;
  11281. svr.Post("/post", [&](const Request &req, Response &res) {
  11282. res.set_content(req.body, "text/plain");
  11283. });
  11284. svr.Put("/put", [&](const Request &req, Response &res) {
  11285. res.set_content(req.body, "text/plain");
  11286. });
  11287. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11288. res.set_content(req.body, "text/plain");
  11289. });
  11290. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11291. res.set_content(req.body, "text/plain");
  11292. });
  11293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11294. auto se = detail::scope_exit([&] {
  11295. svr.stop();
  11296. t.join();
  11297. ASSERT_FALSE(svr.is_running());
  11298. });
  11299. svr.wait_until_ready();
  11300. std::string resp;
  11301. // POST without Content-Length
  11302. ASSERT_TRUE(send_request(5,
  11303. "POST /post HTTP/1.1\r\n"
  11304. "Host: localhost\r\n"
  11305. "Connection: close\r\n"
  11306. "\r\n",
  11307. &resp));
  11308. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11309. // PUT without Content-Length
  11310. resp.clear();
  11311. ASSERT_TRUE(send_request(5,
  11312. "PUT /put HTTP/1.1\r\n"
  11313. "Host: localhost\r\n"
  11314. "Connection: close\r\n"
  11315. "\r\n",
  11316. &resp));
  11317. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11318. // PATCH without Content-Length
  11319. resp.clear();
  11320. ASSERT_TRUE(send_request(5,
  11321. "PATCH /patch HTTP/1.1\r\n"
  11322. "Host: localhost\r\n"
  11323. "Connection: close\r\n"
  11324. "\r\n",
  11325. &resp));
  11326. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11327. // DELETE without Content-Length
  11328. resp.clear();
  11329. ASSERT_TRUE(send_request(5,
  11330. "DELETE /delete HTTP/1.1\r\n"
  11331. "Host: localhost\r\n"
  11332. "Connection: close\r\n"
  11333. "\r\n",
  11334. &resp));
  11335. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11336. }
  11337. #endif
  11338. //==============================================================================
  11339. // open_stream() Tests
  11340. //==============================================================================
  11341. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11342. std::string result;
  11343. char buf[8192];
  11344. ssize_t n;
  11345. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11346. result.append(buf, static_cast<size_t>(n));
  11347. }
  11348. return result;
  11349. }
  11350. // Mock stream for unit tests
  11351. class MockStream : public Stream {
  11352. public:
  11353. std::string data;
  11354. size_t pos = 0;
  11355. ssize_t error_after = -1; // -1 = no error
  11356. explicit MockStream(const std::string &d, ssize_t err = -1)
  11357. : data(d), error_after(err) {}
  11358. bool is_readable() const override { return true; }
  11359. bool wait_readable() const override { return true; }
  11360. bool wait_writable() const override { return true; }
  11361. ssize_t read(char *ptr, size_t size) override {
  11362. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11363. if (pos >= data.size()) return 0;
  11364. size_t limit =
  11365. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11366. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11367. std::memcpy(ptr, data.data() + pos, to_read);
  11368. pos += to_read;
  11369. return static_cast<ssize_t>(to_read);
  11370. }
  11371. ssize_t write(const char *, size_t) override { return -1; }
  11372. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11373. ip = "127.0.0.1";
  11374. port = 0;
  11375. }
  11376. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11377. ip = "127.0.0.1";
  11378. port = 0;
  11379. }
  11380. socket_t socket() const override { return INVALID_SOCKET; }
  11381. time_t duration() const override { return 0; }
  11382. };
  11383. TEST(StreamHandleTest, Basic) {
  11384. ClientImpl::StreamHandle handle;
  11385. EXPECT_FALSE(handle.is_valid());
  11386. handle.response = detail::make_unique<Response>();
  11387. handle.error = Error::Connection;
  11388. EXPECT_FALSE(handle.is_valid());
  11389. handle.error = Error::Success;
  11390. EXPECT_TRUE(handle.is_valid());
  11391. }
  11392. TEST(BodyReaderTest, Basic) {
  11393. MockStream stream("Hello, World!");
  11394. detail::BodyReader reader;
  11395. reader.stream = &stream;
  11396. reader.content_length = 13;
  11397. char buf[32];
  11398. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11399. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11400. EXPECT_TRUE(reader.eof);
  11401. }
  11402. TEST(BodyReaderTest, NoStream) {
  11403. detail::BodyReader reader;
  11404. char buf[32];
  11405. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11406. EXPECT_EQ(Error::Connection, reader.last_error);
  11407. }
  11408. TEST(BodyReaderTest, Error) {
  11409. MockStream stream("Hello, World!", 5);
  11410. detail::BodyReader reader;
  11411. reader.stream = &stream;
  11412. reader.content_length = 13;
  11413. char buf[32];
  11414. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11415. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11416. EXPECT_EQ(Error::Read, reader.last_error);
  11417. }
  11418. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11419. // Mock-based StreamHandle tests relying on private internals are removed.
  11420. class OpenStreamTest : public ::testing::Test {
  11421. protected:
  11422. void SetUp() override {
  11423. svr_.Get("/hello", [](const Request &, Response &res) {
  11424. res.set_content("Hello World!", "text/plain");
  11425. });
  11426. svr_.Get("/large", [](const Request &, Response &res) {
  11427. res.set_content(std::string(10000, 'X'), "text/plain");
  11428. });
  11429. svr_.Get("/chunked", [](const Request &, Response &res) {
  11430. res.set_chunked_content_provider("text/plain",
  11431. [](size_t offset, DataSink &sink) {
  11432. if (offset < 15) {
  11433. sink.write("chunk", 5);
  11434. return true;
  11435. }
  11436. sink.done();
  11437. return true;
  11438. });
  11439. });
  11440. svr_.Get("/compressible", [](const Request &, Response &res) {
  11441. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11442. DataSink &sink) {
  11443. if (offset < 100 * 1024) {
  11444. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11445. sink.write(chunk.data(), chunk.size());
  11446. return true;
  11447. }
  11448. sink.done();
  11449. return true;
  11450. });
  11451. });
  11452. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11453. [](const Request & /*req*/, Response &res) {
  11454. auto i = new int(0);
  11455. res.set_header("Trailer", "Content-Length, X-Allowed");
  11456. res.set_chunked_content_provider(
  11457. "text/plain",
  11458. [i](size_t /*offset*/, DataSink &sink) {
  11459. switch (*i) {
  11460. case 0: sink.os << "123"; break;
  11461. case 1: sink.os << "456"; break;
  11462. case 2: sink.os << "789"; break;
  11463. case 3: {
  11464. sink.done_with_trailer(
  11465. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11466. } break;
  11467. }
  11468. (*i)++;
  11469. return true;
  11470. },
  11471. [i](bool success) {
  11472. EXPECT_TRUE(success);
  11473. delete i;
  11474. });
  11475. });
  11476. // Echo headers endpoint for header-related tests
  11477. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11478. std::string body;
  11479. for (const auto &h : req.headers) {
  11480. body.append(h.first);
  11481. body.push_back(':');
  11482. body.append(h.second);
  11483. body.push_back('\n');
  11484. }
  11485. res.set_content(body, "text/plain");
  11486. });
  11487. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11488. std::string body;
  11489. for (const auto &h : req.headers) {
  11490. body.append(h.first);
  11491. body.push_back(':');
  11492. body.append(h.second);
  11493. body.push_back('\n');
  11494. }
  11495. res.set_content(body, "text/plain");
  11496. });
  11497. port_ = svr_.bind_to_any_port("127.0.0.1");
  11498. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11499. svr_.wait_until_ready();
  11500. }
  11501. void TearDown() override {
  11502. svr_.stop();
  11503. if (thread_.joinable()) thread_.join();
  11504. }
  11505. Server svr_;
  11506. std::thread thread_;
  11507. int port_ = 0;
  11508. };
  11509. TEST_F(OpenStreamTest, Basic) {
  11510. Client cli("127.0.0.1", port_);
  11511. auto handle = cli.open_stream("GET", "/hello");
  11512. EXPECT_TRUE(handle.is_valid());
  11513. EXPECT_EQ("Hello World!", read_all(handle));
  11514. }
  11515. TEST_F(OpenStreamTest, SmallBuffer) {
  11516. Client cli("127.0.0.1", port_);
  11517. auto handle = cli.open_stream("GET", "/hello");
  11518. std::string result;
  11519. char buf[4];
  11520. ssize_t n;
  11521. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11522. result.append(buf, static_cast<size_t>(n));
  11523. EXPECT_EQ("Hello World!", result);
  11524. }
  11525. TEST_F(OpenStreamTest, DefaultHeaders) {
  11526. Client cli("127.0.0.1", port_);
  11527. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11528. {
  11529. auto handle = cli.open_stream("GET", "/echo-headers");
  11530. ASSERT_TRUE(handle.is_valid());
  11531. auto body = read_all(handle);
  11532. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11533. std::string::npos);
  11534. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11535. std::string::npos);
  11536. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11537. }
  11538. // open_stream POST with body and no explicit content_type should NOT add
  11539. // text/plain Content-Type (behavior differs from non-streaming path), but
  11540. // should include Content-Length
  11541. {
  11542. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11543. ASSERT_TRUE(handle.is_valid());
  11544. auto body = read_all(handle);
  11545. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11546. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11547. }
  11548. // open_stream POST with explicit Content-Type should preserve it
  11549. {
  11550. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11551. {{"Content-Type", "application/custom"}},
  11552. "{}", "application/custom");
  11553. ASSERT_TRUE(handle.is_valid());
  11554. auto body = read_all(handle);
  11555. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11556. }
  11557. // User-specified User-Agent must not be overwritten for stream API
  11558. {
  11559. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11560. {{"User-Agent", "MyAgent/1.2"}});
  11561. ASSERT_TRUE(handle.is_valid());
  11562. auto body = read_all(handle);
  11563. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11564. }
  11565. }
  11566. TEST_F(OpenStreamTest, Large) {
  11567. Client cli("127.0.0.1", port_);
  11568. auto handle = cli.open_stream("GET", "/large");
  11569. EXPECT_EQ(10000u, read_all(handle).size());
  11570. }
  11571. TEST_F(OpenStreamTest, ConnectionError) {
  11572. Client cli("127.0.0.1", 9999);
  11573. auto handle = cli.open_stream("GET", "/hello");
  11574. EXPECT_FALSE(handle.is_valid());
  11575. }
  11576. TEST_F(OpenStreamTest, Chunked) {
  11577. Client cli("127.0.0.1", port_);
  11578. auto handle = cli.open_stream("GET", "/chunked");
  11579. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11580. "Transfer-Encoding") == "chunked");
  11581. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11582. }
  11583. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11584. Client cli("127.0.0.1", port_);
  11585. auto handle =
  11586. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11587. ASSERT_TRUE(handle.is_valid());
  11588. // Consume body to allow trailers to be received/parsed
  11589. auto body = read_all(handle);
  11590. // Explicitly parse trailers (ensure trailers are available for assertion)
  11591. handle.parse_trailers_if_needed();
  11592. EXPECT_EQ(std::string("123456789"), body);
  11593. // The response should include a Trailer header declaring both names
  11594. ASSERT_TRUE(handle.response);
  11595. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11596. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11597. handle.response->get_header_value("Trailer"));
  11598. // Prohibited trailer must not be present
  11599. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11600. // Allowed trailer should be present
  11601. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11602. EXPECT_EQ(std::string("yes"),
  11603. handle.response->get_trailer_value("X-Allowed"));
  11604. // Verify trailers are NOT present as regular headers
  11605. EXPECT_EQ(std::string(""),
  11606. handle.response->get_header_value("Content-Length"));
  11607. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11608. }
  11609. static std::thread serve_single_response(std::promise<int> &port_promise,
  11610. const std::string &response) {
  11611. return std::thread([&port_promise, response] {
  11612. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11613. default_socket_options(srv);
  11614. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11615. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11616. sockaddr_in addr{};
  11617. addr.sin_family = AF_INET;
  11618. addr.sin_port = htons(0); // Let OS assign a free port
  11619. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11620. int opt = 1;
  11621. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11622. #ifdef _WIN32
  11623. reinterpret_cast<const char *>(&opt),
  11624. #else
  11625. &opt,
  11626. #endif
  11627. sizeof(opt));
  11628. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11629. ::listen(srv, 1) != 0) {
  11630. port_promise.set_value(-1);
  11631. detail::close_socket(srv);
  11632. return;
  11633. }
  11634. socklen_t addr_len = sizeof(addr);
  11635. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11636. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11637. sockaddr_in cli_addr{};
  11638. socklen_t cli_len = sizeof(cli_addr);
  11639. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11640. if (cli != INVALID_SOCKET) {
  11641. char buf[4096];
  11642. ::recv(cli, buf, sizeof(buf), 0);
  11643. ::send(cli,
  11644. #ifdef _WIN32
  11645. static_cast<const char *>(response.c_str()),
  11646. static_cast<int>(response.size()),
  11647. #else
  11648. response.c_str(), response.size(),
  11649. #endif
  11650. 0);
  11651. detail::close_socket(cli);
  11652. }
  11653. detail::close_socket(srv);
  11654. });
  11655. }
  11656. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11657. #ifndef _WIN32
  11658. signal(SIGPIPE, SIG_IGN);
  11659. #endif
  11660. std::promise<int> port_promise;
  11661. auto port_future = port_promise.get_future();
  11662. auto server_thread =
  11663. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11664. "Content-Type: text/plain\r\n"
  11665. "Content-Length: not-a-number\r\n"
  11666. "Connection: close\r\n"
  11667. "\r\n"
  11668. "hello");
  11669. auto port = port_future.get();
  11670. ASSERT_GT(port, 0);
  11671. Client cli("127.0.0.1", port);
  11672. auto handle = cli.open_stream("GET", "/");
  11673. EXPECT_FALSE(handle.is_valid());
  11674. server_thread.join();
  11675. }
  11676. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11677. #ifndef _WIN32
  11678. signal(SIGPIPE, SIG_IGN);
  11679. #endif
  11680. std::promise<int> port_promise;
  11681. auto port_future = port_promise.get_future();
  11682. auto server_thread = serve_single_response(
  11683. port_promise, "HTTP/1.1 200 OK\r\n"
  11684. "Content-Type: text/plain\r\n"
  11685. "Content-Length: 99999999999999999999999999\r\n"
  11686. "Connection: close\r\n"
  11687. "\r\n"
  11688. "hello");
  11689. auto port = port_future.get();
  11690. ASSERT_GT(port, 0);
  11691. // Before the fix, std::stoull would throw std::out_of_range here and
  11692. // crash the process. After the fix, strtoull silently clamps to
  11693. // ULLONG_MAX so the stream opens without crashing. The important thing
  11694. // is that the process does NOT terminate.
  11695. Client cli("127.0.0.1", port);
  11696. auto handle = cli.open_stream("GET", "/");
  11697. EXPECT_TRUE(handle.is_valid());
  11698. server_thread.join();
  11699. }
  11700. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11701. TEST_F(OpenStreamTest, Gzip) {
  11702. Client cli("127.0.0.1", port_);
  11703. auto handle = cli.open_stream("GET", "/compressible", {},
  11704. {{"Accept-Encoding", "gzip"}});
  11705. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11706. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11707. }
  11708. #endif
  11709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11710. TEST_F(OpenStreamTest, Brotli) {
  11711. Client cli("127.0.0.1", port_);
  11712. auto handle =
  11713. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11714. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11715. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11716. }
  11717. #endif
  11718. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11719. TEST_F(OpenStreamTest, Zstd) {
  11720. Client cli("127.0.0.1", port_);
  11721. auto handle = cli.open_stream("GET", "/compressible", {},
  11722. {{"Accept-Encoding", "zstd"}});
  11723. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11724. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11725. }
  11726. #endif
  11727. #ifdef CPPHTTPLIB_SSL_ENABLED
  11728. class SSLOpenStreamTest : public ::testing::Test {
  11729. protected:
  11730. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11731. void SetUp() override {
  11732. svr_.Get("/hello", [](const Request &, Response &res) {
  11733. res.set_content("Hello SSL World!", "text/plain");
  11734. });
  11735. svr_.Get("/chunked", [](const Request &, Response &res) {
  11736. res.set_chunked_content_provider("text/plain",
  11737. [](size_t offset, DataSink &sink) {
  11738. if (offset < 15) {
  11739. sink.write("chunk", 5);
  11740. return true;
  11741. }
  11742. sink.done();
  11743. return true;
  11744. });
  11745. });
  11746. svr_.Post("/echo", [](const Request &req, Response &res) {
  11747. res.set_content(req.body, req.get_header_value("Content-Type"));
  11748. });
  11749. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11750. std::string body = req.body;
  11751. res.set_chunked_content_provider(
  11752. "text/plain", [body](size_t offset, DataSink &sink) {
  11753. if (offset < body.size()) {
  11754. sink.write(body.data() + offset, body.size() - offset);
  11755. }
  11756. sink.done();
  11757. return true;
  11758. });
  11759. });
  11760. port_ = svr_.bind_to_any_port("127.0.0.1");
  11761. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11762. svr_.wait_until_ready();
  11763. }
  11764. void TearDown() override {
  11765. svr_.stop();
  11766. if (thread_.joinable()) thread_.join();
  11767. }
  11768. SSLServer svr_;
  11769. std::thread thread_;
  11770. int port_ = 0;
  11771. };
  11772. TEST_F(SSLOpenStreamTest, Basic) {
  11773. SSLClient cli("127.0.0.1", port_);
  11774. cli.enable_server_certificate_verification(false);
  11775. auto handle = cli.open_stream("GET", "/hello");
  11776. ASSERT_TRUE(handle.is_valid());
  11777. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11778. }
  11779. TEST_F(SSLOpenStreamTest, Chunked) {
  11780. SSLClient cli("127.0.0.1", port_);
  11781. cli.enable_server_certificate_verification(false);
  11782. auto handle = cli.open_stream("GET", "/chunked");
  11783. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11784. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11785. "Transfer-Encoding") == "chunked");
  11786. auto body = read_all(handle);
  11787. EXPECT_EQ("chunkchunkchunk", body);
  11788. }
  11789. TEST_F(SSLOpenStreamTest, Post) {
  11790. SSLClient cli("127.0.0.1", port_);
  11791. cli.enable_server_certificate_verification(false);
  11792. auto handle =
  11793. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11794. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11795. EXPECT_EQ(200, handle.response->status);
  11796. auto body = read_all(handle);
  11797. EXPECT_EQ("Hello SSL POST", body);
  11798. }
  11799. TEST_F(SSLOpenStreamTest, PostChunked) {
  11800. SSLClient cli("127.0.0.1", port_);
  11801. cli.enable_server_certificate_verification(false);
  11802. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11803. "Chunked SSL Data", "text/plain");
  11804. ASSERT_TRUE(handle.is_valid());
  11805. EXPECT_EQ(200, handle.response->status);
  11806. auto body = read_all(handle);
  11807. EXPECT_EQ("Chunked SSL Data", body);
  11808. }
  11809. #endif // CPPHTTPLIB_SSL_ENABLED
  11810. //==============================================================================
  11811. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11812. // results for various scenarios.
  11813. //==============================================================================
  11814. TEST(ParityTest, GetVsOpenStream) {
  11815. Server svr;
  11816. const std::string path = "/parity";
  11817. const std::string content = "Parity test content: hello world";
  11818. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11819. res.set_content(content, "text/plain");
  11820. });
  11821. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11822. auto se = detail::scope_exit([&] {
  11823. svr.stop();
  11824. t.join();
  11825. ASSERT_FALSE(svr.is_running());
  11826. });
  11827. svr.wait_until_ready();
  11828. Client cli(HOST, PORT);
  11829. // Non-stream path
  11830. auto r1 = cli.Get(path);
  11831. ASSERT_TRUE(r1);
  11832. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11833. // Stream path
  11834. auto h = cli.open_stream("GET", path);
  11835. ASSERT_TRUE(h.is_valid());
  11836. EXPECT_EQ(r1->body, read_all(h));
  11837. }
  11838. // Helper to compress data with provided compressor type T
  11839. template <typename Compressor>
  11840. static std::string compress_payload_for_parity(const std::string &in) {
  11841. std::string out;
  11842. Compressor compressor;
  11843. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11844. [&](const char *data, size_t n) {
  11845. out.append(data, n);
  11846. return true;
  11847. });
  11848. EXPECT_TRUE(ok);
  11849. return out;
  11850. }
  11851. // Helper function for compression parity tests
  11852. template <typename Compressor>
  11853. static void test_compression_parity(const std::string &original,
  11854. const std::string &path,
  11855. const std::string &encoding) {
  11856. const std::string compressed =
  11857. compress_payload_for_parity<Compressor>(original);
  11858. Server svr;
  11859. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11860. res.set_content(compressed, "application/octet-stream");
  11861. res.set_header("Content-Encoding", encoding);
  11862. });
  11863. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11864. auto se = detail::scope_exit([&] {
  11865. svr.stop();
  11866. t.join();
  11867. ASSERT_FALSE(svr.is_running());
  11868. });
  11869. svr.wait_until_ready();
  11870. Client cli(HOST, PORT);
  11871. // Non-streaming
  11872. {
  11873. auto res = cli.Get(path);
  11874. ASSERT_TRUE(res);
  11875. EXPECT_EQ(StatusCode::OK_200, res->status);
  11876. EXPECT_EQ(original, res->body);
  11877. }
  11878. // Streaming
  11879. {
  11880. auto h = cli.open_stream("GET", path);
  11881. ASSERT_TRUE(h.is_valid());
  11882. EXPECT_EQ(original, read_all(h));
  11883. }
  11884. }
  11885. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11886. TEST(ParityTest, Gzip) {
  11887. test_compression_parity<detail::gzip_compressor>(
  11888. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11889. }
  11890. #endif
  11891. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11892. TEST(ParityTest, Brotli) {
  11893. test_compression_parity<detail::brotli_compressor>(
  11894. "Hello, brotli parity test payload", "/parity-br", "br");
  11895. }
  11896. #endif
  11897. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11898. TEST(ParityTest, Zstd) {
  11899. test_compression_parity<detail::zstd_compressor>(
  11900. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11901. }
  11902. #endif
  11903. //==============================================================================
  11904. // New Stream API Tests
  11905. //==============================================================================
  11906. inline std::string read_body(httplib::stream::Result &result) {
  11907. std::string body;
  11908. while (result.next()) {
  11909. body.append(result.data(), result.size());
  11910. }
  11911. return body;
  11912. }
  11913. TEST(ClientConnectionTest, Basic) {
  11914. httplib::ClientConnection conn;
  11915. EXPECT_FALSE(conn.is_open());
  11916. conn.sock = 1;
  11917. EXPECT_TRUE(conn.is_open());
  11918. httplib::ClientConnection conn2(std::move(conn));
  11919. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11920. conn2.sock = INVALID_SOCKET;
  11921. }
  11922. // Unified test server for all stream::* tests
  11923. class StreamApiTest : public ::testing::Test {
  11924. protected:
  11925. void SetUp() override {
  11926. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11927. res.set_content("Hello World!", "text/plain");
  11928. });
  11929. svr_.Get("/echo-params",
  11930. [](const httplib::Request &req, httplib::Response &res) {
  11931. std::string r;
  11932. for (const auto &p : req.params) {
  11933. if (!r.empty()) r += "&";
  11934. r += p.first + "=" + p.second;
  11935. }
  11936. res.set_content(r, "text/plain");
  11937. });
  11938. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11939. res.set_content(req.body, req.get_header_value("Content-Type"));
  11940. });
  11941. svr_.Post("/echo-headers",
  11942. [](const httplib::Request &req, httplib::Response &res) {
  11943. std::string r;
  11944. for (const auto &h : req.headers)
  11945. r += h.first + ": " + h.second + "\n";
  11946. res.set_content(r, "text/plain");
  11947. });
  11948. svr_.Post("/echo-params",
  11949. [](const httplib::Request &req, httplib::Response &res) {
  11950. std::string r = "params:";
  11951. for (const auto &p : req.params)
  11952. r += p.first + "=" + p.second + ";";
  11953. res.set_content(r + " body:" + req.body, "text/plain");
  11954. });
  11955. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11956. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11957. });
  11958. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11959. res.set_content("PUT:" + req.body, "text/plain");
  11960. });
  11961. svr_.Patch("/echo",
  11962. [](const httplib::Request &req, httplib::Response &res) {
  11963. res.set_content("PATCH:" + req.body, "text/plain");
  11964. });
  11965. svr_.Delete(
  11966. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11967. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11968. "text/plain");
  11969. });
  11970. svr_.Get("/head-test",
  11971. [](const httplib::Request &, httplib::Response &res) {
  11972. res.set_content("body for HEAD", "text/plain");
  11973. });
  11974. svr_.Options("/options",
  11975. [](const httplib::Request &, httplib::Response &res) {
  11976. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11977. });
  11978. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11979. svr_.wait_until_ready();
  11980. }
  11981. void TearDown() override {
  11982. svr_.stop();
  11983. if (thread_.joinable()) thread_.join();
  11984. }
  11985. httplib::Server svr_;
  11986. std::thread thread_;
  11987. };
  11988. // stream::Get tests
  11989. TEST_F(StreamApiTest, GetBasic) {
  11990. httplib::Client cli(HOST, PORT);
  11991. auto result = httplib::stream::Get(cli, "/hello");
  11992. ASSERT_TRUE(result.is_valid());
  11993. EXPECT_EQ(200, result.status());
  11994. EXPECT_EQ("Hello World!", read_body(result));
  11995. }
  11996. TEST_F(StreamApiTest, GetWithParams) {
  11997. httplib::Client cli(HOST, PORT);
  11998. httplib::Params params{{"foo", "bar"}};
  11999. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12000. ASSERT_TRUE(result.is_valid());
  12001. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12002. }
  12003. TEST_F(StreamApiTest, GetConnectionError) {
  12004. httplib::Client cli(HOST, 9999);
  12005. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12006. }
  12007. TEST_F(StreamApiTest, Get404) {
  12008. httplib::Client cli(HOST, PORT);
  12009. auto result = httplib::stream::Get(cli, "/nonexistent");
  12010. EXPECT_TRUE(result.is_valid());
  12011. EXPECT_EQ(404, result.status());
  12012. }
  12013. // stream::Post tests
  12014. TEST_F(StreamApiTest, PostBasic) {
  12015. httplib::Client cli(HOST, PORT);
  12016. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12017. "application/json");
  12018. ASSERT_TRUE(result.is_valid());
  12019. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12020. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12021. }
  12022. TEST_F(StreamApiTest, PostWithHeaders) {
  12023. httplib::Client cli(HOST, PORT);
  12024. httplib::Headers headers{{"X-Custom", "value"}};
  12025. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12026. "text/plain");
  12027. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12028. }
  12029. TEST_F(StreamApiTest, PostWithParams) {
  12030. httplib::Client cli(HOST, PORT);
  12031. httplib::Params params{{"k", "v"}};
  12032. auto result =
  12033. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12034. auto body = read_body(result);
  12035. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12036. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12037. }
  12038. TEST_F(StreamApiTest, PostLarge) {
  12039. httplib::Client cli(HOST, PORT);
  12040. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12041. size_t total = 0;
  12042. while (result.next()) {
  12043. total += result.size();
  12044. }
  12045. EXPECT_EQ(100u * 1024u, total);
  12046. }
  12047. // stream::Put/Patch tests
  12048. TEST_F(StreamApiTest, PutAndPatch) {
  12049. httplib::Client cli(HOST, PORT);
  12050. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12051. EXPECT_EQ("PUT:test", read_body(put));
  12052. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12053. EXPECT_EQ("PATCH:test", read_body(patch));
  12054. }
  12055. // stream::Delete tests
  12056. TEST_F(StreamApiTest, Delete) {
  12057. httplib::Client cli(HOST, PORT);
  12058. auto del1 = httplib::stream::Delete(cli, "/resource");
  12059. EXPECT_EQ("Deleted", read_body(del1));
  12060. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12061. EXPECT_EQ("Deleted:data", read_body(del2));
  12062. }
  12063. // stream::Head/Options tests
  12064. TEST_F(StreamApiTest, HeadAndOptions) {
  12065. httplib::Client cli(HOST, PORT);
  12066. auto head = httplib::stream::Head(cli, "/head-test");
  12067. EXPECT_TRUE(head.is_valid());
  12068. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12069. auto opts = httplib::stream::Options(cli, "/options");
  12070. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12071. }
  12072. // SSL stream::* tests
  12073. #ifdef CPPHTTPLIB_SSL_ENABLED
  12074. class SSLStreamApiTest : public ::testing::Test {
  12075. protected:
  12076. void SetUp() override {
  12077. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12078. res.set_content("Hello SSL!", "text/plain");
  12079. });
  12080. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12081. res.set_content(req.body, "text/plain");
  12082. });
  12083. port_ = svr_.bind_to_any_port("127.0.0.1");
  12084. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12085. svr_.wait_until_ready();
  12086. }
  12087. void TearDown() override {
  12088. svr_.stop();
  12089. if (thread_.joinable()) thread_.join();
  12090. }
  12091. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12092. std::thread thread_;
  12093. int port_ = 0;
  12094. };
  12095. TEST_F(SSLStreamApiTest, GetAndPost) {
  12096. httplib::SSLClient cli("127.0.0.1", port_);
  12097. cli.enable_server_certificate_verification(false);
  12098. auto get = httplib::stream::Get(cli, "/hello");
  12099. EXPECT_EQ("Hello SSL!", read_body(get));
  12100. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12101. EXPECT_EQ("test", read_body(post));
  12102. }
  12103. #endif
  12104. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12105. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12106. // BodyReader
  12107. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12108. // Test that read timeout during streaming is detected
  12109. // Use a large content-length response where server delays mid-stream
  12110. Server svr;
  12111. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12112. // Send a large response with delay in the middle
  12113. res.set_content_provider(
  12114. 1000, // content_length
  12115. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12116. if (offset < 100) {
  12117. // Send first 100 bytes immediately
  12118. std::string data(100, 'A');
  12119. sink.write(data.c_str(), data.size());
  12120. return true;
  12121. }
  12122. // Then delay longer than client timeout
  12123. std::this_thread::sleep_for(std::chrono::seconds(3));
  12124. std::string data(900, 'B');
  12125. sink.write(data.c_str(), data.size());
  12126. return true;
  12127. });
  12128. });
  12129. auto port = 8091;
  12130. std::thread t([&]() { svr.listen("localhost", port); });
  12131. svr.wait_until_ready();
  12132. Client cli("localhost", port);
  12133. cli.set_read_timeout(1, 0); // 1 second timeout
  12134. auto handle = cli.open_stream("GET", "/slow-stream");
  12135. ASSERT_TRUE(handle.is_valid());
  12136. char buf[256];
  12137. ssize_t total = 0;
  12138. ssize_t n;
  12139. bool got_error = false;
  12140. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12141. total += n;
  12142. }
  12143. if (n < 0) {
  12144. got_error = true;
  12145. // Should be timeout or read error
  12146. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12147. handle.get_read_error() == Error::Read)
  12148. << "Actual error: " << to_string(handle.get_read_error());
  12149. }
  12150. // Either we got an error, or we got less data than expected
  12151. EXPECT_TRUE(got_error || total < 1000)
  12152. << "Expected timeout but got all " << total << " bytes";
  12153. svr.stop();
  12154. t.join();
  12155. }
  12156. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12157. // Test connection closed detection via BodyReader
  12158. Server svr;
  12159. std::atomic<bool> close_now{false};
  12160. svr.Get("/will-close", [&](const Request &, Response &res) {
  12161. res.set_content_provider(
  12162. 10000, // Large content_length that we won't fully send
  12163. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12164. if (offset < 100) {
  12165. std::string data(100, 'X');
  12166. sink.write(data.c_str(), data.size());
  12167. return true;
  12168. }
  12169. // Wait for signal then abort
  12170. while (!close_now) {
  12171. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12172. }
  12173. return false; // Abort - server will close connection
  12174. });
  12175. });
  12176. auto port = 8092;
  12177. std::thread t([&]() { svr.listen("localhost", port); });
  12178. svr.wait_until_ready();
  12179. Client cli("localhost", port);
  12180. auto handle = cli.open_stream("GET", "/will-close");
  12181. ASSERT_TRUE(handle.is_valid());
  12182. char buf[256];
  12183. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12184. EXPECT_GT(n, 0) << "First read should succeed";
  12185. // Signal server to close
  12186. close_now = true;
  12187. // Keep reading until error or EOF
  12188. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12189. // Keep reading
  12190. }
  12191. // Should get an error since content_length wasn't satisfied
  12192. if (n < 0) {
  12193. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12194. handle.get_read_error() == Error::Read)
  12195. << "Actual error: " << to_string(handle.get_read_error());
  12196. }
  12197. svr.stop();
  12198. t.join();
  12199. }
  12200. #ifdef CPPHTTPLIB_SSL_ENABLED
  12201. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12202. // Test that read timeout during SSL streaming is detected
  12203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12204. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12205. res.set_content_provider(
  12206. 1000, "text/plain",
  12207. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12208. if (offset < 100) {
  12209. std::string data(100, 'A');
  12210. sink.write(data.c_str(), data.size());
  12211. return true;
  12212. }
  12213. std::this_thread::sleep_for(std::chrono::seconds(3));
  12214. std::string data(900, 'B');
  12215. sink.write(data.c_str(), data.size());
  12216. return true;
  12217. });
  12218. });
  12219. auto port = 8093;
  12220. std::thread t([&]() { svr.listen("localhost", port); });
  12221. svr.wait_until_ready();
  12222. SSLClient cli("localhost", port);
  12223. cli.enable_server_certificate_verification(false);
  12224. cli.set_read_timeout(1, 0); // 1 second timeout
  12225. auto handle = cli.open_stream("GET", "/slow-stream");
  12226. ASSERT_TRUE(handle.is_valid());
  12227. char buf[256];
  12228. ssize_t total = 0;
  12229. ssize_t n;
  12230. bool got_error = false;
  12231. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12232. total += n;
  12233. }
  12234. if (n < 0) {
  12235. got_error = true;
  12236. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12237. handle.get_read_error() == Error::Read)
  12238. << "Actual error: " << to_string(handle.get_read_error());
  12239. }
  12240. EXPECT_TRUE(got_error || total < 1000)
  12241. << "Expected timeout but got all " << total << " bytes";
  12242. svr.stop();
  12243. t.join();
  12244. }
  12245. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12246. // Test SSL connection closed detection
  12247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12248. std::atomic<bool> close_now{false};
  12249. svr.Get("/will-close", [&](const Request &, Response &res) {
  12250. res.set_content_provider(
  12251. 10000, "text/plain",
  12252. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12253. if (offset < 100) {
  12254. std::string data(100, 'X');
  12255. sink.write(data.c_str(), data.size());
  12256. return true;
  12257. }
  12258. while (!close_now) {
  12259. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12260. }
  12261. return false;
  12262. });
  12263. });
  12264. auto port = 8094;
  12265. std::thread t([&]() { svr.listen("localhost", port); });
  12266. svr.wait_until_ready();
  12267. SSLClient cli("localhost", port);
  12268. cli.enable_server_certificate_verification(false);
  12269. auto handle = cli.open_stream("GET", "/will-close");
  12270. ASSERT_TRUE(handle.is_valid());
  12271. char buf[256];
  12272. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12273. EXPECT_GT(n, 0);
  12274. // Signal server to close
  12275. close_now = true;
  12276. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12277. // Keep reading
  12278. }
  12279. if (n < 0) {
  12280. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12281. handle.get_read_error() == Error::Read)
  12282. << "Actual error: " << to_string(handle.get_read_error());
  12283. }
  12284. svr.stop();
  12285. t.join();
  12286. }
  12287. #endif
  12288. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12289. using namespace httplib;
  12290. // Create a test file
  12291. const char *fname = "etag_testfile.txt";
  12292. const char *content = "etag-content";
  12293. {
  12294. std::ofstream ofs(fname);
  12295. ofs << content;
  12296. ASSERT_TRUE(ofs.good());
  12297. }
  12298. Server svr;
  12299. svr.set_mount_point("/static", ".");
  12300. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12301. svr.wait_until_ready();
  12302. Client cli(HOST, PORT);
  12303. // First request: should get 200 with ETag header
  12304. auto res1 = cli.Get("/static/etag_testfile.txt");
  12305. ASSERT_TRUE(res1);
  12306. ASSERT_EQ(200, res1->status);
  12307. ASSERT_TRUE(res1->has_header("ETag"));
  12308. std::string etag = res1->get_header_value("ETag");
  12309. EXPECT_FALSE(etag.empty());
  12310. // Verify ETag format: W/"hex-hex"
  12311. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12312. EXPECT_EQ('W', etag[0]);
  12313. EXPECT_EQ('/', etag[1]);
  12314. EXPECT_EQ('"', etag[2]);
  12315. EXPECT_EQ('"', etag.back());
  12316. // Exact match: expect 304 Not Modified
  12317. Headers h2 = {{"If-None-Match", etag}};
  12318. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12319. ASSERT_TRUE(res2);
  12320. EXPECT_EQ(304, res2->status);
  12321. // Wildcard match: expect 304 Not Modified
  12322. Headers h3 = {{"If-None-Match", "*"}};
  12323. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12324. ASSERT_TRUE(res3);
  12325. EXPECT_EQ(304, res3->status);
  12326. // Non-matching ETag: expect 200
  12327. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12328. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12329. ASSERT_TRUE(res4);
  12330. EXPECT_EQ(200, res4->status);
  12331. // Multiple ETags with one matching: expect 304
  12332. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12333. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12334. ASSERT_TRUE(res5);
  12335. EXPECT_EQ(304, res5->status);
  12336. svr.stop();
  12337. t.join();
  12338. std::remove(fname);
  12339. }
  12340. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12341. using namespace httplib;
  12342. Server svr;
  12343. svr.set_mount_point("/static", ".");
  12344. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12345. svr.wait_until_ready();
  12346. Client cli(HOST, PORT);
  12347. // Send If-None-Match: * to a non-existent file
  12348. Headers h = {{"If-None-Match", "*"}};
  12349. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12350. ASSERT_TRUE(res);
  12351. EXPECT_EQ(404, res->status);
  12352. svr.stop();
  12353. t.join();
  12354. }
  12355. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12356. using namespace httplib;
  12357. // Create a test file
  12358. const char *fname = "etag_boundary_testfile.txt";
  12359. const char *content = "boundary-test";
  12360. {
  12361. std::ofstream ofs(fname);
  12362. ofs << content;
  12363. ASSERT_TRUE(ofs.good());
  12364. }
  12365. Server svr;
  12366. svr.set_mount_point("/static", ".");
  12367. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12368. svr.wait_until_ready();
  12369. Client cli(HOST, PORT);
  12370. // Get the actual ETag
  12371. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12372. ASSERT_TRUE(res1);
  12373. ASSERT_EQ(200, res1->status);
  12374. ASSERT_TRUE(res1->has_header("ETag"));
  12375. std::string etag = res1->get_header_value("ETag");
  12376. // Test 1: Very long ETag value (longer than actual ETag)
  12377. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12378. Headers h1 = {{"If-None-Match", "W/"
  12379. "\"very-long-etag-value-that-is-much-longer-"
  12380. "than-the-actual-etag-value\""}};
  12381. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12382. ASSERT_TRUE(res2);
  12383. EXPECT_EQ(200, res2->status); // Should not match
  12384. // Test 2: Long string followed by wildcard
  12385. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12386. // string)
  12387. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12388. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12389. ASSERT_TRUE(res3);
  12390. EXPECT_EQ(304, res3->status); // Should match on "*"
  12391. // Test 3: Wildcard followed by long string
  12392. // Should match on "*" immediately and return 304
  12393. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12394. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12395. ASSERT_TRUE(res4);
  12396. EXPECT_EQ(304, res4->status); // Should match on "*"
  12397. // Test 4: Multiple long non-matching values
  12398. // Should NOT match and return 200 (test that all comparisons are safe)
  12399. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12400. "W/\"second-long-non-matching-value\", "
  12401. "W/\"third-long-non-matching-value\""}};
  12402. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12403. ASSERT_TRUE(res5);
  12404. EXPECT_EQ(200, res5->status); // Should not match
  12405. // Test 5: Single character that is not "*" (edge case)
  12406. Headers h5 = {{"If-None-Match", "X"}};
  12407. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12408. ASSERT_TRUE(res6);
  12409. EXPECT_EQ(200, res6->status); // Should not match
  12410. svr.stop();
  12411. t.join();
  12412. std::remove(fname);
  12413. }
  12414. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12415. using namespace httplib;
  12416. // Create a test file
  12417. const char *fname = "ims_testfile.txt";
  12418. const char *content = "if-modified-since-test";
  12419. {
  12420. std::ofstream ofs(fname);
  12421. ofs << content;
  12422. ASSERT_TRUE(ofs.good());
  12423. }
  12424. Server svr;
  12425. svr.set_mount_point("/static", ".");
  12426. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12427. svr.wait_until_ready();
  12428. Client cli(HOST, PORT);
  12429. // First request: should get 200 with Last-Modified header
  12430. auto res1 = cli.Get("/static/ims_testfile.txt");
  12431. ASSERT_TRUE(res1);
  12432. ASSERT_EQ(200, res1->status);
  12433. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12434. std::string last_modified = res1->get_header_value("Last-Modified");
  12435. EXPECT_FALSE(last_modified.empty());
  12436. // If-Modified-Since with same time: expect 304
  12437. Headers h2 = {{"If-Modified-Since", last_modified}};
  12438. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12439. ASSERT_TRUE(res2);
  12440. EXPECT_EQ(304, res2->status);
  12441. // If-Modified-Since with future time: expect 304
  12442. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12443. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12444. ASSERT_TRUE(res3);
  12445. EXPECT_EQ(304, res3->status);
  12446. // If-Modified-Since with past time: expect 200
  12447. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12448. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12449. ASSERT_TRUE(res4);
  12450. EXPECT_EQ(200, res4->status);
  12451. // If-None-Match takes precedence over If-Modified-Since
  12452. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12453. ASSERT_TRUE(res1->has_header("ETag"));
  12454. std::string etag = res1->get_header_value("ETag");
  12455. Headers h5 = {{"If-None-Match", etag},
  12456. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12457. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12458. ASSERT_TRUE(res5);
  12459. EXPECT_EQ(304, res5->status);
  12460. svr.stop();
  12461. t.join();
  12462. std::remove(fname);
  12463. }
  12464. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12465. using namespace httplib;
  12466. Server svr;
  12467. // Endpoint that returns compressible content
  12468. svr.Get("/compressible", [](const Request &, Response &res) {
  12469. // Return a large enough body to trigger compression
  12470. std::string body(1000, 'a');
  12471. res.set_content(body, "text/plain");
  12472. });
  12473. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12474. svr.wait_until_ready();
  12475. Client cli(HOST, PORT);
  12476. // Request with gzip support: should get Vary header when compressed
  12477. cli.set_compress(true);
  12478. auto res1 = cli.Get("/compressible");
  12479. ASSERT_TRUE(res1);
  12480. EXPECT_EQ(200, res1->status);
  12481. // If Content-Encoding is set, Vary should also be set
  12482. if (res1->has_header("Content-Encoding")) {
  12483. EXPECT_TRUE(res1->has_header("Vary"));
  12484. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12485. }
  12486. // Request without Accept-Encoding header: should not have compression
  12487. Headers h_no_compress;
  12488. auto res2 = cli.Get("/compressible", h_no_compress);
  12489. ASSERT_TRUE(res2);
  12490. EXPECT_EQ(200, res2->status);
  12491. // Verify Vary header is present when compression is applied
  12492. // (the exact behavior depends on server configuration)
  12493. svr.stop();
  12494. t.join();
  12495. }
  12496. TEST(ETagTest, IfRangeWithETag) {
  12497. using namespace httplib;
  12498. // Create a test file with known content
  12499. const char *fname = "if_range_testfile.txt";
  12500. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12501. {
  12502. std::ofstream ofs(fname);
  12503. ofs << content;
  12504. ASSERT_TRUE(ofs.good());
  12505. }
  12506. Server svr;
  12507. svr.set_mount_point("/static", ".");
  12508. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12509. svr.wait_until_ready();
  12510. Client cli(HOST, PORT);
  12511. // First request: get ETag
  12512. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12513. ASSERT_TRUE(res1);
  12514. ASSERT_EQ(200, res1->status);
  12515. ASSERT_TRUE(res1->has_header("ETag"));
  12516. std::string etag = res1->get_header_value("ETag");
  12517. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12518. // Since our server generates weak ETags (W/"..."), If-Range with our
  12519. // ETag should NOT result in partial content - it should return full content.
  12520. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12521. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12522. ASSERT_TRUE(res2);
  12523. // Weak ETag in If-Range -> full content (200), not partial (206)
  12524. EXPECT_EQ(200, res2->status);
  12525. EXPECT_EQ(content, res2->body);
  12526. EXPECT_FALSE(res2->has_header("Content-Range"));
  12527. // Range request with non-matching If-Range (ETag): should get 200 (full
  12528. // content)
  12529. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12530. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12531. ASSERT_TRUE(res3);
  12532. EXPECT_EQ(200, res3->status);
  12533. EXPECT_EQ(content, res3->body);
  12534. EXPECT_FALSE(res3->has_header("Content-Range"));
  12535. // Range request with strong ETag (hypothetical - our server doesn't generate
  12536. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12537. // should return full content)
  12538. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12539. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12540. ASSERT_TRUE(res4);
  12541. EXPECT_EQ(200, res4->status);
  12542. EXPECT_EQ(content, res4->body);
  12543. EXPECT_FALSE(res4->has_header("Content-Range"));
  12544. svr.stop();
  12545. t.join();
  12546. std::remove(fname);
  12547. }
  12548. TEST(ETagTest, IfRangeWithDate) {
  12549. using namespace httplib;
  12550. // Create a test file
  12551. const char *fname = "if_range_date_testfile.txt";
  12552. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12553. {
  12554. std::ofstream ofs(fname);
  12555. ofs << content;
  12556. ASSERT_TRUE(ofs.good());
  12557. }
  12558. Server svr;
  12559. svr.set_mount_point("/static", ".");
  12560. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12561. svr.wait_until_ready();
  12562. Client cli(HOST, PORT);
  12563. // First request: get Last-Modified
  12564. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12565. ASSERT_TRUE(res1);
  12566. ASSERT_EQ(200, res1->status);
  12567. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12568. std::string last_modified = res1->get_header_value("Last-Modified");
  12569. // Range request with matching If-Range (date): should get 206
  12570. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12571. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12572. ASSERT_TRUE(res2);
  12573. EXPECT_EQ(206, res2->status);
  12574. EXPECT_EQ("FGHIJ", res2->body);
  12575. // Range request with old If-Range date: should get 200 (full content)
  12576. Headers h3 = {{"Range", "bytes=5-9"},
  12577. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12578. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12579. ASSERT_TRUE(res3);
  12580. EXPECT_EQ(200, res3->status);
  12581. EXPECT_EQ(content, res3->body);
  12582. // Range request with future If-Range date: should get 206
  12583. Headers h4 = {{"Range", "bytes=0-4"},
  12584. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12585. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12586. ASSERT_TRUE(res4);
  12587. EXPECT_EQ(206, res4->status);
  12588. EXPECT_EQ("ABCDE", res4->body);
  12589. svr.stop();
  12590. t.join();
  12591. std::remove(fname);
  12592. }
  12593. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12594. using namespace httplib;
  12595. const char *fname = "etag_malformed.txt";
  12596. const char *content = "malformed-etag";
  12597. {
  12598. std::ofstream ofs(fname);
  12599. ofs << content;
  12600. ASSERT_TRUE(ofs.good());
  12601. }
  12602. Server svr;
  12603. svr.set_mount_point("/static", ".");
  12604. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12605. svr.wait_until_ready();
  12606. Client cli(HOST, PORT);
  12607. // baseline: should get 200 and an ETag
  12608. auto res1 = cli.Get("/static/etag_malformed.txt");
  12609. ASSERT_TRUE(res1);
  12610. ASSERT_EQ(200, res1->status);
  12611. ASSERT_TRUE(res1->has_header("ETag"));
  12612. // Malformed ETag value (missing quotes) should be treated as non-matching
  12613. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12614. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12615. ASSERT_TRUE(res_bad);
  12616. EXPECT_EQ(200, res_bad->status);
  12617. // Whitespace-only header value should be considered invalid / non-matching
  12618. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12619. "Host: localhost\r\n"
  12620. "If-None-Match: \r\n"
  12621. "Connection: close\r\n"
  12622. "\r\n";
  12623. std::string out;
  12624. ASSERT_TRUE(send_request(5, raw_req, &out));
  12625. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12626. svr.stop();
  12627. t.join();
  12628. std::remove(fname);
  12629. }
  12630. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12631. using namespace httplib;
  12632. const char *fname = "ims_invalid_format.txt";
  12633. const char *content = "ims-bad-format";
  12634. {
  12635. std::ofstream ofs(fname);
  12636. ofs << content;
  12637. ASSERT_TRUE(ofs.good());
  12638. }
  12639. Server svr;
  12640. svr.set_mount_point("/static", ".");
  12641. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12642. svr.wait_until_ready();
  12643. Client cli(HOST, PORT);
  12644. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12645. ASSERT_TRUE(res1);
  12646. ASSERT_EQ(200, res1->status);
  12647. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12648. // If-Modified-Since with invalid format should not result in 304
  12649. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12650. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12651. ASSERT_TRUE(res_bad);
  12652. EXPECT_EQ(200, res_bad->status);
  12653. // If-Range with invalid date format should be treated as mismatch -> full
  12654. // content (200)
  12655. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12656. {"If-Range", "invalid-date"}};
  12657. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12658. ASSERT_TRUE(res_ifrange);
  12659. EXPECT_EQ(200, res_ifrange->status);
  12660. svr.stop();
  12661. t.join();
  12662. std::remove(fname);
  12663. }
  12664. TEST(ETagTest, IfRangeWithMalformedETag) {
  12665. using namespace httplib;
  12666. const char *fname = "ifrange_malformed.txt";
  12667. const std::string content = "0123456789";
  12668. {
  12669. std::ofstream ofs(fname);
  12670. ofs << content;
  12671. ASSERT_TRUE(ofs.good());
  12672. }
  12673. Server svr;
  12674. svr.set_mount_point("/static", ".");
  12675. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12676. svr.wait_until_ready();
  12677. Client cli(HOST, PORT);
  12678. // First request: get ETag
  12679. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12680. ASSERT_TRUE(res1);
  12681. ASSERT_EQ(200, res1->status);
  12682. ASSERT_TRUE(res1->has_header("ETag"));
  12683. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12684. // full content (200)
  12685. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12686. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12687. ASSERT_TRUE(res2);
  12688. EXPECT_EQ(200, res2->status);
  12689. EXPECT_EQ(content, res2->body);
  12690. svr.stop();
  12691. t.join();
  12692. std::remove(fname);
  12693. }
  12694. TEST(ETagTest, ExtremeLargeDateValues) {
  12695. using namespace httplib;
  12696. const char *fname = "ims_extreme_date.txt";
  12697. const char *content = "ims-extreme-date";
  12698. {
  12699. std::ofstream ofs(fname);
  12700. ofs << content;
  12701. ASSERT_TRUE(ofs.good());
  12702. }
  12703. Server svr;
  12704. svr.set_mount_point("/static", ".");
  12705. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12706. svr.wait_until_ready();
  12707. Client cli(HOST, PORT);
  12708. auto res1 = cli.Get(std::string("/static/") + fname);
  12709. ASSERT_TRUE(res1);
  12710. ASSERT_EQ(200, res1->status);
  12711. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12712. // Extremely large year that may overflow date parsing routines.
  12713. Headers h_large_date = {
  12714. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12715. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12716. ASSERT_TRUE(res_bad);
  12717. // Expect server to treat this as invalid/mismatch and return full content
  12718. EXPECT_EQ(200, res_bad->status);
  12719. // If-Range with extremely large date should be treated as mismatch -> full
  12720. // content (200)
  12721. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12722. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12723. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12724. ASSERT_TRUE(res_ifrange);
  12725. EXPECT_EQ(200, res_ifrange->status);
  12726. svr.stop();
  12727. t.join();
  12728. std::remove(fname);
  12729. }
  12730. TEST(ETagTest, NegativeFileModificationTime) {
  12731. using namespace httplib;
  12732. const char *fname = "ims_negative_mtime.txt";
  12733. const std::string content = "negative-mtime";
  12734. {
  12735. std::ofstream ofs(fname);
  12736. ofs << content;
  12737. ASSERT_TRUE(ofs.good());
  12738. }
  12739. // Try to set file mtime to a negative value. This may fail on some
  12740. // platforms/filesystems; if it fails, the test will still verify server
  12741. // behaves safely by performing a regular conditional request.
  12742. #if defined(__APPLE__) || defined(__linux__)
  12743. bool set_negative = false;
  12744. do {
  12745. struct timeval times[2];
  12746. // access time: now
  12747. times[0].tv_sec = time(nullptr);
  12748. times[0].tv_usec = 0;
  12749. // modification time: negative (e.g., -1)
  12750. times[1].tv_sec = -1;
  12751. times[1].tv_usec = 0;
  12752. if (utimes(fname, times) == 0) { set_negative = true; }
  12753. } while (0);
  12754. #else
  12755. bool set_negative = false;
  12756. #endif
  12757. Server svr;
  12758. svr.set_mount_point("/static", ".");
  12759. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12760. svr.wait_until_ready();
  12761. Client cli(HOST, PORT);
  12762. auto res1 = cli.Get(std::string("/static/") + fname);
  12763. ASSERT_TRUE(res1);
  12764. ASSERT_EQ(200, res1->status);
  12765. bool has_last_modified = res1->has_header("Last-Modified");
  12766. std::string last_modified;
  12767. if (has_last_modified) {
  12768. last_modified = res1->get_header_value("Last-Modified");
  12769. }
  12770. if (set_negative) {
  12771. // If we successfully set a negative mtime, ensure server returns a
  12772. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12773. // with an old date and ensure server handles it without crash.
  12774. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12775. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12776. ASSERT_TRUE(res2);
  12777. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12778. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12779. } else {
  12780. // Could not set negative mtime on this platform; fall back to verifying
  12781. // that normal invalid/malformed dates are treated safely (non-304).
  12782. Headers h_bad_date = {
  12783. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12784. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12785. ASSERT_TRUE(res_bad);
  12786. EXPECT_EQ(200, res_bad->status);
  12787. }
  12788. svr.stop();
  12789. t.join();
  12790. std::remove(fname);
  12791. }
  12792. //==============================================================================
  12793. // SSE Parsing Tests
  12794. //==============================================================================
  12795. class SSEParsingTest : public ::testing::Test {
  12796. protected:
  12797. // Test helper that mimics SSE parsing behavior
  12798. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12799. int &retry_ms) {
  12800. // Blank line signals end of event
  12801. if (line.empty() || line == "\r") { return true; }
  12802. // Lines starting with ':' are comments (ignored)
  12803. if (!line.empty() && line[0] == ':') { return false; }
  12804. // Find the colon separator
  12805. auto colon_pos = line.find(':');
  12806. if (colon_pos == std::string::npos) {
  12807. // Line with no colon is treated as field name with empty value
  12808. return false;
  12809. }
  12810. std::string field = line.substr(0, colon_pos);
  12811. std::string value;
  12812. // Value starts after colon, skip optional single space
  12813. if (colon_pos + 1 < line.size()) {
  12814. size_t value_start = colon_pos + 1;
  12815. if (line[value_start] == ' ') { value_start++; }
  12816. value = line.substr(value_start);
  12817. // Remove trailing \r if present
  12818. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12819. }
  12820. // Handle known fields
  12821. if (field == "event") {
  12822. msg.event = value;
  12823. } else if (field == "data") {
  12824. // Multiple data lines are concatenated with newlines
  12825. if (!msg.data.empty()) { msg.data += "\n"; }
  12826. msg.data += value;
  12827. } else if (field == "id") {
  12828. // Empty id is valid (clears the last event ID)
  12829. msg.id = value;
  12830. } else if (field == "retry") {
  12831. // Parse retry interval in milliseconds
  12832. {
  12833. int v = 0;
  12834. auto res =
  12835. detail::from_chars(value.data(), value.data() + value.size(), v);
  12836. if (res.ec == std::errc{}) { retry_ms = v; }
  12837. }
  12838. }
  12839. // Unknown fields are ignored per SSE spec
  12840. return false;
  12841. }
  12842. };
  12843. // Test: Single-line data
  12844. TEST_F(SSEParsingTest, SingleLineData) {
  12845. sse::SSEMessage msg;
  12846. int retry_ms = 3000;
  12847. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12848. EXPECT_EQ(msg.data, "hello");
  12849. EXPECT_EQ(msg.event, "message");
  12850. // Blank line ends event
  12851. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12852. }
  12853. // Test: Multi-line data
  12854. TEST_F(SSEParsingTest, MultiLineData) {
  12855. sse::SSEMessage msg;
  12856. int retry_ms = 3000;
  12857. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12858. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12859. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12860. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12861. }
  12862. // Test: Custom event types
  12863. TEST_F(SSEParsingTest, CustomEventType) {
  12864. sse::SSEMessage msg;
  12865. int retry_ms = 3000;
  12866. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12867. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12868. EXPECT_EQ(msg.event, "update");
  12869. EXPECT_EQ(msg.data, "payload");
  12870. }
  12871. // Test: Event ID handling
  12872. TEST_F(SSEParsingTest, EventIdHandling) {
  12873. sse::SSEMessage msg;
  12874. int retry_ms = 3000;
  12875. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12876. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12877. EXPECT_EQ(msg.id, "12345");
  12878. }
  12879. // Test: Empty event ID (clears last event ID)
  12880. TEST_F(SSEParsingTest, EmptyEventId) {
  12881. sse::SSEMessage msg;
  12882. msg.id = "previous";
  12883. int retry_ms = 3000;
  12884. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12885. EXPECT_EQ(msg.id, "");
  12886. }
  12887. // Test: Retry field parsing
  12888. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12889. sse::SSEMessage msg;
  12890. int retry_ms = 3000;
  12891. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12892. EXPECT_EQ(retry_ms, 5000);
  12893. }
  12894. // Test: Invalid retry value
  12895. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12896. sse::SSEMessage msg;
  12897. int retry_ms = 3000;
  12898. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12899. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12900. }
  12901. // Test: Comments (lines starting with :)
  12902. TEST_F(SSEParsingTest, CommentsIgnored) {
  12903. sse::SSEMessage msg;
  12904. int retry_ms = 3000;
  12905. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12906. EXPECT_EQ(msg.data, "");
  12907. EXPECT_EQ(msg.event, "message");
  12908. }
  12909. // Test: Colon in value
  12910. TEST_F(SSEParsingTest, ColonInValue) {
  12911. sse::SSEMessage msg;
  12912. int retry_ms = 3000;
  12913. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12914. EXPECT_EQ(msg.data, "hello:world:test");
  12915. }
  12916. // Test: Line with no colon (field name only)
  12917. TEST_F(SSEParsingTest, FieldNameOnly) {
  12918. sse::SSEMessage msg;
  12919. int retry_ms = 3000;
  12920. // According to SSE spec, this is treated as field name with empty value
  12921. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12922. // Since we don't recognize "data" without colon, data should be empty
  12923. EXPECT_EQ(msg.data, "");
  12924. }
  12925. // Test: Trailing \r handling
  12926. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12927. sse::SSEMessage msg;
  12928. int retry_ms = 3000;
  12929. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12930. EXPECT_EQ(msg.data, "hello");
  12931. }
  12932. // Test: Unknown fields ignored
  12933. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12934. sse::SSEMessage msg;
  12935. int retry_ms = 3000;
  12936. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12937. EXPECT_EQ(msg.data, "");
  12938. EXPECT_EQ(msg.event, "message");
  12939. }
  12940. // Test: Space after colon is optional
  12941. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12942. sse::SSEMessage msg1, msg2;
  12943. int retry_ms = 3000;
  12944. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12945. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12946. EXPECT_EQ(msg1.data, "hello");
  12947. EXPECT_EQ(msg2.data, "hello");
  12948. }
  12949. // Test: SSEMessage clear
  12950. TEST_F(SSEParsingTest, MessageClear) {
  12951. sse::SSEMessage msg;
  12952. msg.event = "custom";
  12953. msg.data = "some data";
  12954. msg.id = "123";
  12955. msg.clear();
  12956. EXPECT_EQ(msg.event, "message");
  12957. EXPECT_EQ(msg.data, "");
  12958. EXPECT_EQ(msg.id, "");
  12959. }
  12960. // Test: Complete event parsing
  12961. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12962. sse::SSEMessage msg;
  12963. int retry_ms = 3000;
  12964. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12965. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12966. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12967. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12968. // Blank line ends event
  12969. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12970. EXPECT_EQ(msg.event, "notification");
  12971. EXPECT_EQ(msg.id, "evt-42");
  12972. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12973. EXPECT_EQ(retry_ms, 1000);
  12974. }
  12975. //==============================================================================
  12976. // Integration Tests with Server
  12977. //==============================================================================
  12978. class SSEIntegrationTest : public ::testing::Test {
  12979. protected:
  12980. void SetUp() override {
  12981. stop_server_.store(false);
  12982. events_.clear();
  12983. server_ = httplib::detail::make_unique<Server>();
  12984. setup_server();
  12985. start_server();
  12986. }
  12987. void TearDown() override {
  12988. stop_server_.store(true);
  12989. event_cv_.notify_all();
  12990. server_->stop();
  12991. if (server_thread_.joinable()) { server_thread_.join(); }
  12992. }
  12993. void setup_server() {
  12994. // Simple SSE endpoint
  12995. server_->Get("/events", [this](const Request &req, Response &res) {
  12996. auto last_id = req.get_header_value("Last-Event-ID");
  12997. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12998. res.set_chunked_content_provider(
  12999. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13000. std::unique_lock<std::mutex> lock(event_mutex_);
  13001. if (event_cv_.wait_for(
  13002. lock, std::chrono::milliseconds(200), [this] {
  13003. return !events_.empty() || stop_server_.load();
  13004. })) {
  13005. if (stop_server_.load()) { return false; }
  13006. if (!events_.empty()) {
  13007. std::string event = events_.front();
  13008. events_.erase(events_.begin());
  13009. sink.write(event.data(), event.size());
  13010. return true;
  13011. }
  13012. }
  13013. return !stop_server_.load();
  13014. });
  13015. });
  13016. // Endpoint that returns error
  13017. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13018. res.status = 500;
  13019. res.set_content("Internal Server Error", "text/plain");
  13020. });
  13021. // Endpoint for custom event types
  13022. server_->Get("/custom-events", [](const Request &, Response &res) {
  13023. res.set_chunked_content_provider(
  13024. "text/event-stream", [](size_t offset, DataSink &sink) {
  13025. if (offset == 0) {
  13026. std::string event = "event: update\ndata: updated\n\n"
  13027. "event: delete\ndata: deleted\n\n";
  13028. sink.write(event.data(), event.size());
  13029. }
  13030. return false; // End stream after sending
  13031. });
  13032. });
  13033. }
  13034. void start_server() {
  13035. port_ = server_->bind_to_any_port(HOST);
  13036. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13037. // Wait for server to start
  13038. while (!server_->is_running()) {
  13039. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13040. }
  13041. }
  13042. int get_port() const { return port_; }
  13043. void send_event(const std::string &event) {
  13044. std::lock_guard<std::mutex> lock(event_mutex_);
  13045. events_.push_back(event);
  13046. event_cv_.notify_all();
  13047. }
  13048. std::unique_ptr<Server> server_;
  13049. std::thread server_thread_;
  13050. std::mutex event_mutex_;
  13051. std::condition_variable event_cv_;
  13052. std::vector<std::string> events_;
  13053. std::atomic<bool> stop_server_{false};
  13054. std::string last_received_event_id_;
  13055. int port_ = 0;
  13056. };
  13057. // Test: Successful connection and on_open callback
  13058. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13059. // Add a simple endpoint that sends one event and closes
  13060. server_->Get("/simple-event", [](const Request &, Response &res) {
  13061. res.set_chunked_content_provider(
  13062. "text/event-stream", [](size_t offset, DataSink &sink) {
  13063. if (offset == 0) {
  13064. std::string event = "data: hello\n\n";
  13065. sink.write(event.data(), event.size());
  13066. }
  13067. return false; // Close stream after sending
  13068. });
  13069. });
  13070. Client client("localhost", get_port());
  13071. sse::SSEClient sse(client, "/simple-event");
  13072. std::atomic<bool> open_called{false};
  13073. std::atomic<bool> message_received{false};
  13074. sse.on_open([&open_called]() { open_called.store(true); });
  13075. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13076. if (msg.data == "hello") { message_received.store(true); }
  13077. });
  13078. sse.set_reconnect_interval(100);
  13079. sse.set_max_reconnect_attempts(1);
  13080. // Start async
  13081. sse.start_async();
  13082. // Wait for message to be processed
  13083. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13084. sse.stop();
  13085. EXPECT_TRUE(open_called.load());
  13086. EXPECT_TRUE(message_received.load());
  13087. }
  13088. // Test: on_message callback
  13089. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13090. // Endpoint that sends multiple events then closes
  13091. server_->Get("/multi-event", [](const Request &, Response &res) {
  13092. res.set_chunked_content_provider(
  13093. "text/event-stream", [](size_t offset, DataSink &sink) {
  13094. if (offset == 0) {
  13095. std::string events = "data: message1\n\ndata: message2\n\n";
  13096. sink.write(events.data(), events.size());
  13097. }
  13098. return false;
  13099. });
  13100. });
  13101. Client client("localhost", get_port());
  13102. sse::SSEClient sse(client, "/multi-event");
  13103. std::vector<std::string> received_messages;
  13104. std::mutex messages_mutex;
  13105. sse.on_message([&](const sse::SSEMessage &msg) {
  13106. std::lock_guard<std::mutex> lock(messages_mutex);
  13107. received_messages.push_back(msg.data);
  13108. });
  13109. sse.set_reconnect_interval(100);
  13110. sse.set_max_reconnect_attempts(1);
  13111. sse.start_async();
  13112. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13113. sse.stop();
  13114. std::lock_guard<std::mutex> lock(messages_mutex);
  13115. EXPECT_GE(received_messages.size(), 2u);
  13116. if (received_messages.size() >= 2) {
  13117. EXPECT_EQ(received_messages[0], "message1");
  13118. EXPECT_EQ(received_messages[1], "message2");
  13119. }
  13120. }
  13121. // Test: on_event for specific types
  13122. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13123. Client client("localhost", get_port());
  13124. sse::SSEClient sse(client, "/custom-events");
  13125. std::atomic<bool> update_received{false};
  13126. std::atomic<bool> delete_received{false};
  13127. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13128. if (msg.data == "updated") { update_received.store(true); }
  13129. });
  13130. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13131. if (msg.data == "deleted") { delete_received.store(true); }
  13132. });
  13133. sse.set_max_reconnect_attempts(1);
  13134. sse.start_async();
  13135. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13136. sse.stop();
  13137. EXPECT_TRUE(update_received.load());
  13138. EXPECT_TRUE(delete_received.load());
  13139. }
  13140. // Test: on_error callback on connection failure
  13141. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13142. // Connect to a non-existent port
  13143. Client client("localhost", 59999);
  13144. sse::SSEClient sse(client, "/events");
  13145. std::atomic<bool> error_called{false};
  13146. Error received_error = Error::Success;
  13147. sse.on_error([&](Error err) {
  13148. error_called.store(true);
  13149. received_error = err;
  13150. });
  13151. sse.set_reconnect_interval(50);
  13152. sse.set_max_reconnect_attempts(1);
  13153. sse.start_async();
  13154. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13155. sse.stop();
  13156. EXPECT_TRUE(error_called.load());
  13157. EXPECT_NE(received_error, Error::Success);
  13158. }
  13159. // Test: Last-Event-ID header sent on reconnect
  13160. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13161. // Endpoint that sends event with ID
  13162. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13163. res.set_chunked_content_provider(
  13164. "text/event-stream", [](size_t offset, DataSink &sink) {
  13165. if (offset == 0) {
  13166. std::string event = "id: evt-123\ndata: test\n\n";
  13167. sink.write(event.data(), event.size());
  13168. }
  13169. return false;
  13170. });
  13171. });
  13172. Client client("localhost", get_port());
  13173. sse::SSEClient sse(client, "/event-with-id");
  13174. std::atomic<bool> id_received{false};
  13175. sse.on_message([&](const sse::SSEMessage &msg) {
  13176. if (!msg.id.empty()) { id_received.store(true); }
  13177. });
  13178. sse.set_reconnect_interval(100);
  13179. sse.set_max_reconnect_attempts(1);
  13180. sse.start_async();
  13181. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13182. sse.stop();
  13183. EXPECT_TRUE(id_received.load());
  13184. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13185. }
  13186. // Test: Manual stop
  13187. TEST_F(SSEIntegrationTest, ManualStop) {
  13188. // Endpoint that sends one event and stays open briefly
  13189. std::atomic<bool> handler_running{true};
  13190. server_->Get("/stay-open", [&handler_running](const Request &,
  13191. Response &res) {
  13192. res.set_chunked_content_provider(
  13193. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13194. if (offset == 0) {
  13195. std::string event = "data: connected\n\n";
  13196. sink.write(event.data(), event.size());
  13197. }
  13198. // Keep connection open while handler_running is true
  13199. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13200. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13201. }
  13202. return false;
  13203. });
  13204. });
  13205. Client client("localhost", get_port());
  13206. sse::SSEClient sse(client, "/stay-open");
  13207. std::atomic<bool> connected{false};
  13208. sse.on_open([&connected]() { connected.store(true); });
  13209. sse.set_reconnect_interval(100);
  13210. sse.set_max_reconnect_attempts(1);
  13211. sse.start_async();
  13212. // Wait for connection to establish
  13213. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13214. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13215. }
  13216. EXPECT_TRUE(connected.load());
  13217. EXPECT_TRUE(sse.is_connected());
  13218. // Signal handler to stop
  13219. handler_running.store(false);
  13220. // Stop SSE client
  13221. sse.stop();
  13222. EXPECT_FALSE(sse.is_connected());
  13223. }
  13224. // Test: SSEClient with custom headers
  13225. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13226. // Setup a server endpoint that checks for custom header
  13227. std::atomic<bool> header_received{false};
  13228. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13229. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13230. header_received.store(true);
  13231. }
  13232. res.set_chunked_content_provider("text/event-stream",
  13233. [](size_t, DataSink &) { return false; });
  13234. });
  13235. Client client("localhost", get_port());
  13236. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13237. sse::SSEClient sse(client, "/header-check", headers);
  13238. sse.set_max_reconnect_attempts(1);
  13239. sse.start_async();
  13240. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13241. sse.stop();
  13242. EXPECT_TRUE(header_received.load());
  13243. }
  13244. // Test: Reconnect interval configuration
  13245. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13246. Client client("localhost", get_port());
  13247. sse::SSEClient sse(client, "/events");
  13248. auto &result = sse.set_reconnect_interval(500);
  13249. // Builder pattern should return reference to self
  13250. EXPECT_EQ(&result, &sse);
  13251. }
  13252. // Test: Max reconnect attempts
  13253. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13254. // Connect to non-existent port to force reconnects
  13255. Client client("localhost", 59998);
  13256. sse::SSEClient sse(client, "/events");
  13257. std::atomic<int> error_count{0};
  13258. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13259. sse.set_reconnect_interval(50);
  13260. sse.set_max_reconnect_attempts(2);
  13261. auto start = std::chrono::steady_clock::now();
  13262. sse.start(); // Blocking call
  13263. auto end = std::chrono::steady_clock::now();
  13264. // Should have stopped after 2 failed attempts
  13265. EXPECT_GE(error_count.load(), 2);
  13266. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13267. auto duration =
  13268. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13269. #ifdef _WIN32
  13270. // Windows is much slower for socket connection failures
  13271. EXPECT_LT(duration.count(), 7000);
  13272. #else
  13273. EXPECT_LT(duration.count(), 1000);
  13274. #endif
  13275. }
  13276. // Test: Multi-line data in integration
  13277. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13278. // Endpoint with multi-line data
  13279. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13280. res.set_chunked_content_provider(
  13281. "text/event-stream", [](size_t offset, DataSink &sink) {
  13282. if (offset == 0) {
  13283. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13284. sink.write(event.data(), event.size());
  13285. }
  13286. return false;
  13287. });
  13288. });
  13289. Client client("localhost", get_port());
  13290. sse::SSEClient sse(client, "/multiline-data");
  13291. std::string received_data;
  13292. std::mutex data_mutex;
  13293. sse.on_message([&](const sse::SSEMessage &msg) {
  13294. std::lock_guard<std::mutex> lock(data_mutex);
  13295. received_data = msg.data;
  13296. });
  13297. sse.set_reconnect_interval(100);
  13298. sse.set_max_reconnect_attempts(1);
  13299. sse.start_async();
  13300. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13301. sse.stop();
  13302. std::lock_guard<std::mutex> lock(data_mutex);
  13303. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13304. }
  13305. // Test: Auto-reconnect after server disconnection
  13306. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13307. std::atomic<int> connection_count{0};
  13308. std::atomic<int> message_count{0};
  13309. // Endpoint that sends one event and closes, forcing reconnect
  13310. server_->Get("/reconnect-test",
  13311. [&connection_count](const Request &, Response &res) {
  13312. connection_count.fetch_add(1);
  13313. res.set_chunked_content_provider(
  13314. "text/event-stream", [](size_t offset, DataSink &sink) {
  13315. if (offset == 0) {
  13316. std::string event = "data: hello\n\n";
  13317. sink.write(event.data(), event.size());
  13318. }
  13319. return false; // Close connection after sending
  13320. });
  13321. });
  13322. Client client("localhost", get_port());
  13323. sse::SSEClient sse(client, "/reconnect-test");
  13324. sse.on_message([&message_count](const sse::SSEMessage &) {
  13325. message_count.fetch_add(1);
  13326. });
  13327. sse.set_reconnect_interval(100);
  13328. sse.set_max_reconnect_attempts(3);
  13329. sse.start_async();
  13330. // Wait long enough for multiple reconnects
  13331. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13332. sse.stop();
  13333. // Should have connected multiple times (initial + reconnects)
  13334. EXPECT_GE(connection_count.load(), 2);
  13335. // Should have received messages from multiple connections
  13336. EXPECT_GE(message_count.load(), 2);
  13337. }
  13338. // Test: Last-Event-ID sent on reconnect
  13339. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13340. std::atomic<int> connection_count{0};
  13341. std::vector<std::string> received_last_event_ids;
  13342. std::mutex id_mutex;
  13343. // Endpoint that checks Last-Event-ID header and sends event with ID
  13344. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13345. int conn = connection_count.fetch_add(1);
  13346. // Capture the Last-Event-ID header from each connection
  13347. {
  13348. std::lock_guard<std::mutex> lock(id_mutex);
  13349. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13350. }
  13351. res.set_chunked_content_provider(
  13352. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13353. if (offset == 0) {
  13354. std::string event =
  13355. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13356. sink.write(event.data(), event.size());
  13357. }
  13358. return false;
  13359. });
  13360. });
  13361. Client client("localhost", get_port());
  13362. sse::SSEClient sse(client, "/reconnect-with-id");
  13363. sse.set_reconnect_interval(100);
  13364. sse.set_max_reconnect_attempts(3);
  13365. sse.start_async();
  13366. // Wait for at least 2 connections
  13367. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13368. sse.stop();
  13369. // Verify behavior
  13370. std::lock_guard<std::mutex> lock(id_mutex);
  13371. EXPECT_GE(received_last_event_ids.size(), 2u);
  13372. // First connection should have no Last-Event-ID
  13373. if (!received_last_event_ids.empty()) {
  13374. EXPECT_EQ(received_last_event_ids[0], "");
  13375. }
  13376. // Second connection should have Last-Event-ID from first connection
  13377. if (received_last_event_ids.size() >= 2) {
  13378. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13379. }
  13380. }
  13381. // Test: set_headers updates headers used on reconnect
  13382. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13383. std::vector<std::string> received_tokens;
  13384. std::mutex token_mutex;
  13385. // Endpoint that captures Authorization header
  13386. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13387. {
  13388. std::lock_guard<std::mutex> lock(token_mutex);
  13389. received_tokens.push_back(req.get_header_value("Authorization"));
  13390. }
  13391. res.set_chunked_content_provider(
  13392. "text/event-stream", [](size_t offset, DataSink &sink) {
  13393. if (offset == 0) {
  13394. std::string event = "data: hello\n\n";
  13395. sink.write(event.data(), event.size());
  13396. }
  13397. return false; // Close connection to trigger reconnect
  13398. });
  13399. });
  13400. Client client("localhost", get_port());
  13401. Headers headers = {{"Authorization", "Bearer old-token"}};
  13402. sse::SSEClient sse(client, "/auth-check", headers);
  13403. // Update headers on each successful connection
  13404. sse.on_open(
  13405. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13406. sse.set_reconnect_interval(100);
  13407. sse.set_max_reconnect_attempts(3);
  13408. sse.start_async();
  13409. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13410. sse.stop();
  13411. std::lock_guard<std::mutex> lock(token_mutex);
  13412. ASSERT_GE(received_tokens.size(), 2u);
  13413. // First connection uses original header
  13414. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13415. // Second connection uses updated header from set_headers
  13416. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13417. }
  13418. // Test: 401 allows reconnection (so on_error can refresh headers)
  13419. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13420. std::atomic<int> connection_count{0};
  13421. // Endpoint: returns 401 on first attempt, 200 on second
  13422. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13423. int conn = connection_count.fetch_add(1);
  13424. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13425. res.status = StatusCode::Unauthorized_401;
  13426. res.set_content("Unauthorized", "text/plain");
  13427. return;
  13428. }
  13429. res.set_chunked_content_provider(
  13430. "text/event-stream", [](size_t offset, DataSink &sink) {
  13431. if (offset == 0) {
  13432. std::string event = "data: authenticated\n\n";
  13433. sink.write(event.data(), event.size());
  13434. }
  13435. return false;
  13436. });
  13437. });
  13438. Client client("localhost", get_port());
  13439. Headers headers = {{"Authorization", "Bearer expired"}};
  13440. sse::SSEClient sse(client, "/auth-retry", headers);
  13441. std::atomic<bool> message_received{false};
  13442. // Refresh token on error
  13443. sse.on_error(
  13444. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13445. sse.on_message([&](const sse::SSEMessage &msg) {
  13446. if (msg.data == "authenticated") { message_received.store(true); }
  13447. });
  13448. sse.set_reconnect_interval(100);
  13449. sse.set_max_reconnect_attempts(3);
  13450. sse.start_async();
  13451. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13452. sse.stop();
  13453. // Should have reconnected after 401 and succeeded with new token
  13454. EXPECT_GE(connection_count.load(), 2);
  13455. EXPECT_TRUE(message_received.load());
  13456. }
  13457. TEST(Issue2318Test, EmptyHostString) {
  13458. {
  13459. httplib::Client cli_empty("", PORT);
  13460. auto res = cli_empty.Get("/");
  13461. ASSERT_FALSE(res);
  13462. EXPECT_EQ(httplib::Error::Connection, res.error());
  13463. }
  13464. {
  13465. httplib::Client cli(" ", PORT);
  13466. auto res = cli.Get("/");
  13467. ASSERT_FALSE(res);
  13468. EXPECT_EQ(httplib::Error::Connection, res.error());
  13469. }
  13470. }
  13471. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13472. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13473. Server svr;
  13474. // Set a small payload limit (1KB)
  13475. svr.set_payload_max_length(1024);
  13476. svr.Post("/test", [&](const Request &req, Response &res) {
  13477. res.set_content("Body size: " + std::to_string(req.body.size()),
  13478. "text/plain");
  13479. });
  13480. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13481. auto se = detail::scope_exit([&] {
  13482. svr.stop();
  13483. listen_thread.join();
  13484. });
  13485. svr.wait_until_ready();
  13486. // Create data that compresses well but exceeds limit when decompressed
  13487. // 8KB of repeated null bytes compresses to a very small size
  13488. std::string original_data(8 * 1024, '\0');
  13489. // Compress the data using gzip
  13490. std::string compressed_data;
  13491. detail::gzip_compressor compressor;
  13492. compressor.compress(original_data.data(), original_data.size(), true,
  13493. [&](const char *data, size_t size) {
  13494. compressed_data.append(data, size);
  13495. return true;
  13496. });
  13497. // Verify compression worked (compressed should be much smaller)
  13498. ASSERT_LT(compressed_data.size(), original_data.size());
  13499. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13500. // Send compressed data with Content-Encoding: gzip
  13501. Client cli(HOST, PORT);
  13502. Headers headers = {{"Content-Encoding", "gzip"}};
  13503. auto res =
  13504. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13505. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13506. ASSERT_TRUE(res);
  13507. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13508. }
  13509. #endif
  13510. // ============================================================================
  13511. // OpenSSL-Specific Tests
  13512. // ============================================================================
  13513. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13514. X509 *readCertificate(const std::string &strFileName) {
  13515. std::ifstream inStream(strFileName);
  13516. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13517. std::istreambuf_iterator<char>());
  13518. if (strCertPEM.empty()) return (nullptr);
  13519. BIO *pbCert = BIO_new(BIO_s_mem());
  13520. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13521. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13522. BIO_free(pbCert);
  13523. return (pCert);
  13524. }
  13525. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13526. std::ifstream inStream(strFileName);
  13527. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13528. std::istreambuf_iterator<char>());
  13529. if (strPrivateKeyPEM.empty()) return (nullptr);
  13530. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13531. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13532. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13533. BIO_free(pbPrivKey);
  13534. return (pPrivateKey);
  13535. }
  13536. TEST(BindServerTest, UpdateCerts) {
  13537. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13538. int port = svr.bind_to_any_port("0.0.0.0");
  13539. ASSERT_TRUE(svr.is_valid());
  13540. ASSERT_TRUE(port > 0);
  13541. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13542. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13543. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13544. ASSERT_TRUE(cert != nullptr);
  13545. ASSERT_TRUE(ca_cert != nullptr);
  13546. ASSERT_TRUE(key != nullptr);
  13547. X509_STORE *cert_store = X509_STORE_new();
  13548. X509_STORE_add_cert(cert_store, ca_cert);
  13549. // svr.update_certs(cert, key, cert_store); // deprecated
  13550. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13551. CLIENT_CA_CERT_FILE);
  13552. ASSERT_TRUE(svr.is_valid());
  13553. svr.stop();
  13554. X509_STORE_free(cert_store);
  13555. X509_free(cert);
  13556. X509_free(ca_cert);
  13557. EVP_PKEY_free(key);
  13558. }
  13559. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13560. // client CA list correctly for TLS handshake
  13561. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13562. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13563. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13564. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13565. ASSERT_TRUE(cert != nullptr);
  13566. ASSERT_TRUE(ca_cert != nullptr);
  13567. ASSERT_TRUE(key != nullptr);
  13568. X509_STORE *cert_store = X509_STORE_new();
  13569. X509_STORE_add_cert(cert_store, ca_cert);
  13570. // Use X509-based constructor (deprecated but should still work correctly)
  13571. #pragma GCC diagnostic push
  13572. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13573. SSLServer svr(cert, key, cert_store);
  13574. #pragma GCC diagnostic pop
  13575. ASSERT_TRUE(svr.is_valid());
  13576. // Verify that client CA list is set in SSL_CTX
  13577. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13578. ASSERT_TRUE(ssl_ctx != nullptr);
  13579. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13580. ASSERT_TRUE(ca_list != nullptr);
  13581. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13582. X509_free(cert);
  13583. X509_free(ca_cert);
  13584. EVP_PKEY_free(key);
  13585. }
  13586. // Test that update_certs() updates client CA list correctly
  13587. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13588. // Start with file-based constructor
  13589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13590. ASSERT_TRUE(svr.is_valid());
  13591. // Initially no client CA list should be set
  13592. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13593. ASSERT_TRUE(ssl_ctx != nullptr);
  13594. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13595. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13596. EXPECT_EQ(0, count_before);
  13597. // Now update with client CA (PEM string)
  13598. std::string cert_pem, key_pem, ca_pem;
  13599. read_file(SERVER_CERT_FILE, cert_pem);
  13600. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13601. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13602. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13603. ASSERT_TRUE(svr.is_valid());
  13604. // Now client CA list should be set
  13605. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13606. ASSERT_TRUE(ca_list_after != nullptr);
  13607. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13608. }
  13609. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13610. // Test that the file-path SSLServer constructor properly sets the client CA
  13611. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13613. ASSERT_TRUE(svr.is_valid());
  13614. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13615. ASSERT_TRUE(ssl_ctx != nullptr);
  13616. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13617. ASSERT_TRUE(ca_list != nullptr);
  13618. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13619. }
  13620. #endif
  13621. // ============================================================================
  13622. // MbedTLS-Specific Tests
  13623. // ============================================================================
  13624. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13625. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13626. using namespace httplib::tls;
  13627. // Track if callback was invoked
  13628. bool callback_invoked = false;
  13629. // The callback receives void* ctx which is actually MbedTlsContext*
  13630. // We can access the mbedtls_ssl_config via the context
  13631. auto setup_callback = [&callback_invoked](void *ctx) {
  13632. callback_invoked = true;
  13633. // Cast to MbedTlsContext* to access the ssl config
  13634. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13635. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13636. // Use static variables to hold certificate data (simplified for test)
  13637. static mbedtls_x509_crt own_cert;
  13638. static mbedtls_pk_context own_key;
  13639. static mbedtls_x509_crt ca_chain;
  13640. static bool initialized = false;
  13641. if (!initialized) {
  13642. mbedtls_x509_crt_init(&own_cert);
  13643. mbedtls_pk_init(&own_key);
  13644. mbedtls_x509_crt_init(&ca_chain);
  13645. // Load server certificate
  13646. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13647. return false;
  13648. }
  13649. // Load server private key
  13650. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13651. #if MBEDTLS_VERSION_MAJOR >= 3
  13652. ,
  13653. mbedtls_ctr_drbg_random, nullptr
  13654. #endif
  13655. ) != 0) {
  13656. return false;
  13657. }
  13658. // Load CA chain for client verification
  13659. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13660. return false;
  13661. }
  13662. initialized = true;
  13663. }
  13664. // Configure the SSL config
  13665. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13666. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13667. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13668. // Set minimum TLS version using mbedTLS native API
  13669. #if MBEDTLS_VERSION_MAJOR >= 3
  13670. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13671. #else
  13672. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13673. MBEDTLS_SSL_MINOR_VERSION_3);
  13674. #endif
  13675. return true;
  13676. };
  13677. SSLServer svr(setup_callback);
  13678. ASSERT_TRUE(svr.is_valid());
  13679. ASSERT_TRUE(callback_invoked);
  13680. svr.Get("/test", [&](const Request &req, Response &res) {
  13681. res.set_content("test", "text/plain");
  13682. auto cert = req.peer_cert();
  13683. ASSERT_TRUE(static_cast<bool>(cert));
  13684. auto common_name = cert.subject_cn();
  13685. EXPECT_EQ("Common Name", common_name);
  13686. });
  13687. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13688. auto se = detail::scope_exit([&] {
  13689. svr.stop();
  13690. t.join();
  13691. ASSERT_FALSE(svr.is_running());
  13692. });
  13693. svr.wait_until_ready();
  13694. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13695. cli.enable_server_certificate_verification(false);
  13696. cli.set_connection_timeout(30);
  13697. auto res = cli.Get("/test");
  13698. ASSERT_TRUE(res);
  13699. ASSERT_EQ(StatusCode::OK_200, res->status);
  13700. }
  13701. #endif
  13702. // WebSocket Tests
  13703. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13704. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13705. // defining the meaning of these bits has been negotiated.
  13706. auto make_frame = [](uint8_t first_byte) {
  13707. std::string frame;
  13708. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13709. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13710. frame += "Hello";
  13711. return frame;
  13712. };
  13713. // RSV1 set (0x40)
  13714. {
  13715. detail::BufferStream strm;
  13716. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. }
  13723. // RSV2 set (0x20)
  13724. {
  13725. detail::BufferStream strm;
  13726. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  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. // RSV3 set (0x10)
  13734. {
  13735. detail::BufferStream strm;
  13736. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13737. ws::Opcode opcode;
  13738. std::string payload;
  13739. bool fin;
  13740. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13741. false, 1024));
  13742. }
  13743. // No RSV bits set - should succeed
  13744. {
  13745. detail::BufferStream strm;
  13746. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13747. ws::Opcode opcode;
  13748. std::string payload;
  13749. bool fin;
  13750. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13751. false, 1024));
  13752. EXPECT_EQ(ws::Opcode::Text, opcode);
  13753. EXPECT_EQ("Hello", payload);
  13754. EXPECT_TRUE(fin);
  13755. }
  13756. }
  13757. TEST(WebSocketTest, ControlFrameValidation) {
  13758. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13759. // payload length <= 125.
  13760. // Ping with FIN=0 - must be rejected
  13761. {
  13762. detail::BufferStream strm;
  13763. std::string frame;
  13764. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13765. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13766. strm.write(frame.data(), frame.size());
  13767. ws::Opcode opcode;
  13768. std::string payload;
  13769. bool fin;
  13770. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13771. false, 1024));
  13772. }
  13773. // Close with FIN=0 - must be rejected
  13774. {
  13775. detail::BufferStream strm;
  13776. std::string frame;
  13777. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13778. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13779. strm.write(frame.data(), frame.size());
  13780. ws::Opcode opcode;
  13781. std::string payload;
  13782. bool fin;
  13783. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13784. false, 1024));
  13785. }
  13786. // Ping with payload_len=126 (extended length) - must be rejected
  13787. {
  13788. detail::BufferStream strm;
  13789. std::string frame;
  13790. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13791. frame += static_cast<char>(126); // payload_len=126 (>125)
  13792. frame += static_cast<char>(0x00); // extended length high byte
  13793. frame += static_cast<char>(126); // extended length low byte
  13794. frame += std::string(126, 'x');
  13795. strm.write(frame.data(), frame.size());
  13796. ws::Opcode opcode;
  13797. std::string payload;
  13798. bool fin;
  13799. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13800. false, 1024));
  13801. }
  13802. // Ping with FIN=1 and payload_len=125 - should succeed
  13803. {
  13804. detail::BufferStream strm;
  13805. std::string frame;
  13806. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13807. frame += static_cast<char>(125); // payload_len=125
  13808. frame += std::string(125, 'x');
  13809. strm.write(frame.data(), frame.size());
  13810. ws::Opcode opcode;
  13811. std::string payload;
  13812. bool fin;
  13813. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13814. false, 1024));
  13815. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13816. EXPECT_EQ(125u, payload.size());
  13817. EXPECT_TRUE(fin);
  13818. }
  13819. }
  13820. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13821. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13822. // length MUST be 0.
  13823. // MSB set - must be rejected
  13824. {
  13825. detail::BufferStream strm;
  13826. std::string frame;
  13827. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13828. frame += static_cast<char>(127); // 64-bit extended length
  13829. frame += static_cast<char>(0x80); // MSB set (invalid)
  13830. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13831. strm.write(frame.data(), frame.size());
  13832. ws::Opcode opcode;
  13833. std::string payload;
  13834. bool fin;
  13835. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13836. false, 1024));
  13837. }
  13838. // MSB clear - should pass length parsing (will be rejected by max_len,
  13839. // but that's a different check; use a small length to verify)
  13840. {
  13841. detail::BufferStream strm;
  13842. std::string frame;
  13843. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13844. frame += static_cast<char>(127); // 64-bit extended length
  13845. frame += std::string(7, '\0'); // high bytes = 0
  13846. frame += static_cast<char>(0x03); // length = 3
  13847. frame += "abc";
  13848. strm.write(frame.data(), frame.size());
  13849. ws::Opcode opcode;
  13850. std::string payload;
  13851. bool fin;
  13852. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13853. false, 1024));
  13854. EXPECT_EQ(ws::Opcode::Text, opcode);
  13855. EXPECT_EQ("abc", payload);
  13856. }
  13857. }
  13858. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13859. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13860. // Valid UTF-8
  13861. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13862. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13863. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13864. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13865. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13866. // Invalid UTF-8
  13867. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13868. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13869. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13870. EXPECT_FALSE(
  13871. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13872. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13873. }
  13874. TEST(WebSocketTest, ConnectAndDisconnect) {
  13875. Server svr;
  13876. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13877. std::string msg;
  13878. while (ws.read(msg)) {}
  13879. });
  13880. auto port = svr.bind_to_any_port(HOST);
  13881. std::thread t([&]() { svr.listen_after_bind(); });
  13882. svr.wait_until_ready();
  13883. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13884. ASSERT_TRUE(client.connect());
  13885. EXPECT_TRUE(client.is_open());
  13886. client.close();
  13887. EXPECT_FALSE(client.is_open());
  13888. svr.stop();
  13889. t.join();
  13890. }
  13891. TEST(WebSocketTest, ValidURL) {
  13892. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13893. EXPECT_TRUE(ws1.is_valid());
  13894. ws::WebSocketClient ws2("ws://example.com/path");
  13895. EXPECT_TRUE(ws2.is_valid());
  13896. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13897. EXPECT_TRUE(ws3.is_valid());
  13898. #ifdef CPPHTTPLIB_SSL_ENABLED
  13899. ws::WebSocketClient wss1("wss://example.com/path");
  13900. EXPECT_TRUE(wss1.is_valid());
  13901. ws::WebSocketClient wss2("wss://example.com:443/path");
  13902. EXPECT_TRUE(wss2.is_valid());
  13903. #endif
  13904. }
  13905. TEST(WebSocketTest, InvalidURL) {
  13906. // No scheme
  13907. ws::WebSocketClient ws1("localhost:8080/path");
  13908. EXPECT_FALSE(ws1.is_valid());
  13909. // No path
  13910. ws::WebSocketClient ws2("ws://localhost:8080");
  13911. EXPECT_FALSE(ws2.is_valid());
  13912. // Empty string
  13913. ws::WebSocketClient ws3("");
  13914. EXPECT_FALSE(ws3.is_valid());
  13915. // Missing host
  13916. ws::WebSocketClient ws4("ws://:8080/path");
  13917. EXPECT_FALSE(ws4.is_valid());
  13918. // Port number overflow — should not crash
  13919. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13920. EXPECT_FALSE(ws5.is_valid());
  13921. // Port out of range
  13922. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13923. EXPECT_FALSE(ws6.is_valid());
  13924. }
  13925. TEST(WebSocketTest, UnsupportedScheme) {
  13926. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13927. ws::WebSocketClient ws1("http://localhost:8080/path");
  13928. EXPECT_FALSE(ws1.is_valid());
  13929. ws::WebSocketClient ws2("https://localhost:8080/path");
  13930. EXPECT_FALSE(ws2.is_valid());
  13931. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13932. EXPECT_FALSE(ws3.is_valid());
  13933. #else
  13934. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13935. std::invalid_argument);
  13936. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13937. std::invalid_argument);
  13938. #endif
  13939. }
  13940. TEST(WebSocketTest, ConnectWhenInvalid) {
  13941. ws::WebSocketClient ws("not a valid url");
  13942. EXPECT_FALSE(ws.is_valid());
  13943. EXPECT_FALSE(ws.connect());
  13944. }
  13945. TEST(WebSocketTest, DefaultPort) {
  13946. ws::WebSocketClient ws1("ws://example.com/path");
  13947. EXPECT_TRUE(ws1.is_valid());
  13948. // ws:// defaults to port 80 (verified by successful parse)
  13949. #ifdef CPPHTTPLIB_SSL_ENABLED
  13950. ws::WebSocketClient ws2("wss://example.com/path");
  13951. EXPECT_TRUE(ws2.is_valid());
  13952. // wss:// defaults to port 443 (verified by successful parse)
  13953. #endif
  13954. }
  13955. TEST(WebSocketTest, IPv6LiteralAddress) {
  13956. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13957. EXPECT_TRUE(ws1.is_valid());
  13958. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13959. EXPECT_TRUE(ws2.is_valid());
  13960. }
  13961. TEST(WebSocketTest, ComplexPath) {
  13962. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13963. EXPECT_TRUE(ws1.is_valid());
  13964. ws::WebSocketClient ws2("ws://localhost:8080/");
  13965. EXPECT_TRUE(ws2.is_valid());
  13966. }
  13967. class WebSocketIntegrationTest : public ::testing::Test {
  13968. protected:
  13969. void SetUp() override {
  13970. server_ = httplib::detail::make_unique<Server>();
  13971. setup_server();
  13972. start_server();
  13973. }
  13974. void TearDown() override {
  13975. server_->stop();
  13976. if (server_thread_.joinable()) { server_thread_.join(); }
  13977. }
  13978. void setup_server() {
  13979. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13980. std::string msg;
  13981. ws::ReadResult ret;
  13982. while ((ret = ws.read(msg))) {
  13983. if (ret == ws::Binary) {
  13984. ws.send(msg.data(), msg.size());
  13985. } else {
  13986. ws.send(msg);
  13987. }
  13988. }
  13989. });
  13990. server_->WebSocket("/ws-echo-string",
  13991. [](const Request &, ws::WebSocket &ws) {
  13992. std::string msg;
  13993. while (ws.read(msg)) {
  13994. ws.send("echo: " + msg);
  13995. }
  13996. });
  13997. server_->WebSocket(
  13998. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13999. // Echo back request metadata
  14000. ws.send("path:" + req.path);
  14001. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14002. std::string msg;
  14003. while (ws.read(msg)) {}
  14004. });
  14005. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14006. std::string msg;
  14007. ws.read(msg); // wait for a message
  14008. ws.close();
  14009. });
  14010. server_->WebSocket("/ws-close-status",
  14011. [](const Request &, ws::WebSocket &ws) {
  14012. std::string msg;
  14013. ws.read(msg); // wait for a message
  14014. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14015. });
  14016. server_->WebSocket(
  14017. "/ws-subprotocol",
  14018. [](const Request &, ws::WebSocket &ws) {
  14019. std::string msg;
  14020. while (ws.read(msg)) {
  14021. ws.send(msg);
  14022. }
  14023. },
  14024. [](const std::vector<std::string> &protocols) -> std::string {
  14025. for (const auto &p : protocols) {
  14026. if (p == "graphql-ws") { return p; }
  14027. }
  14028. return "";
  14029. });
  14030. }
  14031. void start_server() {
  14032. port_ = server_->bind_to_any_port(HOST);
  14033. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14034. server_->wait_until_ready();
  14035. }
  14036. std::unique_ptr<Server> server_;
  14037. std::thread server_thread_;
  14038. int port_ = 0;
  14039. };
  14040. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14041. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14042. "/ws-echo");
  14043. ASSERT_TRUE(client.connect());
  14044. ASSERT_TRUE(client.is_open());
  14045. ASSERT_TRUE(client.send("Hello WebSocket"));
  14046. std::string msg;
  14047. EXPECT_EQ(ws::Text, client.read(msg));
  14048. EXPECT_EQ("Hello WebSocket", msg);
  14049. client.close();
  14050. }
  14051. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14053. "/ws-echo");
  14054. ASSERT_TRUE(client.connect());
  14055. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14056. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14057. std::string msg;
  14058. EXPECT_EQ(ws::Binary, client.read(msg));
  14059. EXPECT_EQ(binary_data, msg);
  14060. client.close();
  14061. }
  14062. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14064. "/ws-echo");
  14065. ASSERT_TRUE(client.connect());
  14066. for (int i = 0; i < 10; i++) {
  14067. auto text = "message " + std::to_string(i);
  14068. ASSERT_TRUE(client.send(text));
  14069. std::string msg;
  14070. ASSERT_TRUE(client.read(msg));
  14071. EXPECT_EQ(text, msg);
  14072. }
  14073. client.close();
  14074. }
  14075. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14076. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14077. "/ws-close");
  14078. ASSERT_TRUE(client.connect());
  14079. // Send a message to trigger the server to close
  14080. ASSERT_TRUE(client.send("trigger close"));
  14081. // The server will close, so read should return false
  14082. std::string msg;
  14083. EXPECT_FALSE(client.read(msg));
  14084. EXPECT_FALSE(client.is_open());
  14085. }
  14086. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14087. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14088. "/ws-echo");
  14089. ASSERT_TRUE(client.connect());
  14090. // 128KB message
  14091. std::string large_data(128 * 1024, 'X');
  14092. ASSERT_TRUE(client.send(large_data));
  14093. std::string msg;
  14094. ASSERT_TRUE(client.read(msg));
  14095. EXPECT_EQ(large_data, msg);
  14096. client.close();
  14097. }
  14098. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14100. "/ws-echo");
  14101. ASSERT_TRUE(client.connect());
  14102. const int num_threads = 4;
  14103. std::vector<std::thread> threads;
  14104. std::atomic<int> send_count{0};
  14105. for (int t = 0; t < num_threads; t++) {
  14106. threads.emplace_back([&client, &send_count, t]() {
  14107. for (int i = 0; i < 5; i++) {
  14108. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14109. if (client.send(text)) { send_count++; }
  14110. }
  14111. });
  14112. }
  14113. for (auto &th : threads) {
  14114. th.join();
  14115. }
  14116. int received = 0;
  14117. std::string msg;
  14118. while (received < send_count.load()) {
  14119. if (!client.read(msg)) { break; }
  14120. received++;
  14121. }
  14122. EXPECT_EQ(send_count.load(), received);
  14123. client.close();
  14124. }
  14125. TEST_F(WebSocketIntegrationTest, ReadString) {
  14126. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14127. "/ws-echo-string");
  14128. ASSERT_TRUE(client.connect());
  14129. ASSERT_TRUE(client.send("hello"));
  14130. std::string msg;
  14131. ASSERT_TRUE(client.read(msg));
  14132. EXPECT_EQ("echo: hello", msg);
  14133. ASSERT_TRUE(client.send("world"));
  14134. ASSERT_TRUE(client.read(msg));
  14135. EXPECT_EQ("echo: world", msg);
  14136. client.close();
  14137. }
  14138. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14139. Headers headers = {{"X-Test-Header", "test-value"}};
  14140. ws::WebSocketClient client(
  14141. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14142. ASSERT_TRUE(client.connect());
  14143. std::string msg;
  14144. ASSERT_TRUE(client.read(msg));
  14145. EXPECT_EQ("path:/ws-request-info", msg);
  14146. ASSERT_TRUE(client.read(msg));
  14147. EXPECT_EQ("header:test-value", msg);
  14148. client.close();
  14149. }
  14150. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14152. "/ws-echo");
  14153. client.set_read_timeout(1, 0); // 1 second
  14154. ASSERT_TRUE(client.connect());
  14155. // Don't send anything — server echo handler waits for a message,
  14156. // so read() should time out and return false.
  14157. std::string msg;
  14158. EXPECT_FALSE(client.read(msg));
  14159. }
  14160. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14161. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14162. "/ws-echo");
  14163. client.set_read_timeout(5, 0);
  14164. ASSERT_TRUE(client.connect());
  14165. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14166. // The server should reject it and close the connection.
  14167. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14168. client.send(oversized);
  14169. // The server's read() should have failed due to payload limit,
  14170. // so our read() should return false (connection closed).
  14171. std::string msg;
  14172. EXPECT_FALSE(client.read(msg));
  14173. }
  14174. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14176. "/ws-echo");
  14177. client.set_read_timeout(10, 0);
  14178. ASSERT_TRUE(client.connect());
  14179. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14180. // This should succeed.
  14181. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14182. ASSERT_TRUE(client.send(at_limit));
  14183. std::string msg;
  14184. ASSERT_TRUE(client.read(msg));
  14185. EXPECT_EQ(at_limit.size(), msg.size());
  14186. client.close();
  14187. }
  14188. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14190. "/nonexistent");
  14191. EXPECT_FALSE(client.connect());
  14192. EXPECT_FALSE(client.is_open());
  14193. }
  14194. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14196. "/ws-echo");
  14197. ASSERT_TRUE(client.connect());
  14198. ASSERT_TRUE(client.send(""));
  14199. std::string msg;
  14200. EXPECT_EQ(ws::Text, client.read(msg));
  14201. EXPECT_EQ("", msg);
  14202. client.close();
  14203. }
  14204. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14206. "/ws-echo");
  14207. // First connection
  14208. ASSERT_TRUE(client.connect());
  14209. ASSERT_TRUE(client.send("first"));
  14210. std::string msg;
  14211. ASSERT_TRUE(client.read(msg));
  14212. EXPECT_EQ("first", msg);
  14213. client.close();
  14214. EXPECT_FALSE(client.is_open());
  14215. // Reconnect using the same client object
  14216. ASSERT_TRUE(client.connect());
  14217. ASSERT_TRUE(client.is_open());
  14218. ASSERT_TRUE(client.send("second"));
  14219. ASSERT_TRUE(client.read(msg));
  14220. EXPECT_EQ("second", msg);
  14221. client.close();
  14222. }
  14223. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14224. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14225. "/ws-close-status");
  14226. ASSERT_TRUE(client.connect());
  14227. // Trigger the server to close with GoingAway status
  14228. ASSERT_TRUE(client.send("trigger"));
  14229. // read() should return false after receiving the close frame
  14230. std::string msg;
  14231. EXPECT_FALSE(client.read(msg));
  14232. EXPECT_FALSE(client.is_open());
  14233. }
  14234. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14236. "/ws-echo");
  14237. ASSERT_TRUE(client.connect());
  14238. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14239. EXPECT_FALSE(client.is_open());
  14240. }
  14241. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14242. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14243. ws::WebSocketClient client(
  14244. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14245. ASSERT_TRUE(client.connect());
  14246. // Server should have selected graphql-ws
  14247. EXPECT_EQ("graphql-ws", client.subprotocol());
  14248. client.close();
  14249. }
  14250. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14251. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14252. ws::WebSocketClient client(
  14253. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14254. ASSERT_TRUE(client.connect());
  14255. // Server should not have selected any subprotocol
  14256. EXPECT_TRUE(client.subprotocol().empty());
  14257. client.close();
  14258. }
  14259. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14260. // Connect without requesting any subprotocol
  14261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14262. "/ws-subprotocol");
  14263. ASSERT_TRUE(client.connect());
  14264. EXPECT_TRUE(client.subprotocol().empty());
  14265. client.close();
  14266. }
  14267. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14269. "/ws-echo");
  14270. client.set_tcp_nodelay(true);
  14271. client.set_address_family(AF_INET);
  14272. client.set_connection_timeout(3, 0);
  14273. bool socket_options_called = false;
  14274. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14275. ASSERT_TRUE(client.connect());
  14276. ASSERT_TRUE(client.is_open());
  14277. EXPECT_TRUE(socket_options_called);
  14278. ASSERT_TRUE(client.send("hello"));
  14279. std::string msg;
  14280. auto result = client.read(msg);
  14281. EXPECT_EQ(result, ws::ReadResult::Text);
  14282. EXPECT_EQ(msg, "hello");
  14283. client.close();
  14284. }
  14285. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14286. Server svr;
  14287. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14288. if (!req.has_header("Authorization")) {
  14289. res.status = StatusCode::Unauthorized_401;
  14290. res.set_content("Unauthorized", "text/plain");
  14291. return Server::HandlerResponse::Handled;
  14292. }
  14293. return Server::HandlerResponse::Unhandled;
  14294. });
  14295. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14296. std::string msg;
  14297. while (ws.read(msg)) {
  14298. ws.send(msg);
  14299. }
  14300. });
  14301. auto port = svr.bind_to_any_port("localhost");
  14302. std::thread t([&]() { svr.listen_after_bind(); });
  14303. svr.wait_until_ready();
  14304. // Without Authorization header - should be rejected before upgrade
  14305. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14306. EXPECT_FALSE(client1.connect());
  14307. // With Authorization header - should succeed
  14308. Headers headers = {{"Authorization", "Bearer token123"}};
  14309. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14310. headers);
  14311. ASSERT_TRUE(client2.connect());
  14312. ASSERT_TRUE(client2.send("hello"));
  14313. std::string msg;
  14314. ASSERT_TRUE(client2.read(msg));
  14315. EXPECT_EQ("hello", msg);
  14316. client2.close();
  14317. svr.stop();
  14318. t.join();
  14319. }
  14320. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14321. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14322. protected:
  14323. void SetUp() override {
  14324. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14325. SERVER_PRIVATE_KEY_FILE);
  14326. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14327. std::string msg;
  14328. ws::ReadResult ret;
  14329. while ((ret = ws.read(msg))) {
  14330. if (ret == ws::Binary) {
  14331. ws.send(msg.data(), msg.size());
  14332. } else {
  14333. ws.send(msg);
  14334. }
  14335. }
  14336. });
  14337. port_ = server_->bind_to_any_port(HOST);
  14338. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14339. server_->wait_until_ready();
  14340. }
  14341. void TearDown() override {
  14342. server_->stop();
  14343. if (server_thread_.joinable()) { server_thread_.join(); }
  14344. }
  14345. std::unique_ptr<SSLServer> server_;
  14346. std::thread server_thread_;
  14347. int port_ = 0;
  14348. };
  14349. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14350. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14351. "/ws-echo");
  14352. client.enable_server_certificate_verification(false);
  14353. ASSERT_TRUE(client.connect());
  14354. ASSERT_TRUE(client.is_open());
  14355. ASSERT_TRUE(client.send("Hello WSS"));
  14356. std::string msg;
  14357. EXPECT_EQ(ws::Text, client.read(msg));
  14358. EXPECT_EQ("Hello WSS", msg);
  14359. client.close();
  14360. }
  14361. #endif
  14362. #if !defined(_WIN32)
  14363. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14364. auto secret_dir = std::string("./symlink_test_secret");
  14365. auto served_dir = std::string("./symlink_test_served");
  14366. auto secret_file = secret_dir + "/secret.txt";
  14367. auto symlink_path = served_dir + "/escape";
  14368. // Setup: create directories and files
  14369. mkdir(secret_dir.c_str(), 0755);
  14370. mkdir(served_dir.c_str(), 0755);
  14371. {
  14372. std::ofstream ofs(secret_file);
  14373. ofs << "SECRET_DATA";
  14374. }
  14375. // Create symlink using absolute path so it resolves correctly
  14376. char abs_secret[PATH_MAX];
  14377. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14378. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14379. auto se = detail::scope_exit([&] {
  14380. unlink(symlink_path.c_str());
  14381. unlink(secret_file.c_str());
  14382. rmdir(served_dir.c_str());
  14383. rmdir(secret_dir.c_str());
  14384. });
  14385. Server svr;
  14386. svr.set_mount_point("/", served_dir);
  14387. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14388. auto se2 = detail::scope_exit([&] {
  14389. svr.stop();
  14390. listen_thread.join();
  14391. });
  14392. svr.wait_until_ready();
  14393. Client cli("localhost", PORT);
  14394. // Symlink pointing outside base dir should be blocked
  14395. auto res = cli.Get("/escape/secret.txt");
  14396. ASSERT_TRUE(res);
  14397. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14398. }
  14399. #endif