test.cc 516 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  348. string reservedCharacters = ";,/?:@&=+$";
  349. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  350. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  351. }
  352. TEST(ClientQueryOrder, PreserveOrder) {
  353. // This test reproduces Issue #2259: client may reorder query parameters
  354. // when sending a GET request. The expected behavior is that the client
  355. // preserves the original query string order when the caller supplied it
  356. // as part of the path.
  357. Server svr;
  358. svr.Get("/", [&](const Request &req, Response &res) {
  359. // Echo back the raw target so the test can assert ordering
  360. res.set_content(req.target, "text/plain");
  361. });
  362. std::thread t{[&] { svr.listen(HOST, PORT); }};
  363. auto se = detail::scope_exit([&] {
  364. svr.stop();
  365. t.join();
  366. ASSERT_FALSE(svr.is_running());
  367. });
  368. svr.wait_until_ready();
  369. Client cli(HOST, PORT);
  370. ASSERT_TRUE(cli.is_valid());
  371. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  372. auto res = cli.Get(original);
  373. ASSERT_TRUE(res);
  374. // Expect the echoed target to exactly match the original path (order
  375. // preserved)
  376. EXPECT_EQ(res->body, original);
  377. }
  378. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  379. string chineseCharacters = U8("中国語");
  380. string russianCharacters = U8("дом");
  381. string brazilianCharacters = U8("óculos");
  382. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  383. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  384. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  385. "%D0%B4%D0%BE%D0%BC");
  386. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  387. }
  388. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$";
  394. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  395. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  396. }
  397. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  398. string chineseCharacters = U8("中国語");
  399. string russianCharacters = U8("дом");
  400. string brazilianCharacters = U8("óculos");
  401. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  402. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  403. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  404. "%D0%B4%D0%BE%D0%BC");
  405. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  406. }
  407. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  408. // Issue #2082 use case: encoding path component with ampersand
  409. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  410. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  411. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  412. }
  413. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  414. string unescapedCharacters = "-_.!~*'()";
  415. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  416. }
  417. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  418. string reservedCharacters = ";,/?:@&=+$#";
  419. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  420. }
  421. TEST(EncodeUriTest, TestUTF8Characters) {
  422. string chineseCharacters = U8("中国語");
  423. string russianCharacters = U8("дом");
  424. string brazilianCharacters = U8("óculos");
  425. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  426. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  427. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  428. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  429. }
  430. TEST(EncodeUriTest, TestCompleteUri) {
  431. string uri =
  432. "https://example.com/path/to/resource?query=value&param=test#fragment";
  433. EXPECT_EQ(
  434. httplib::encode_uri(uri),
  435. "https://example.com/path/to/resource?query=value&param=test#fragment");
  436. }
  437. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  438. string uri =
  439. "https://example.com/path with spaces/file name.html?q=hello world";
  440. EXPECT_EQ(httplib::encode_uri(uri),
  441. "https://example.com/path%20with%20spaces/"
  442. "file%20name.html?q=hello%20world");
  443. }
  444. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  445. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  446. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  447. }
  448. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  449. string unescapedCharacters = "-_.!~*'()";
  450. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  451. }
  452. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  453. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  454. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  455. string encodedBrazilian = "%C3%B3culos";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  457. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  458. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  459. }
  460. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  461. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  462. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  463. "Piri Tommy Villiers - on & on");
  464. }
  465. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  466. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  467. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  468. }
  469. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  470. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  471. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  472. }
  473. TEST(DecodeUriTest, TestUTF8Characters) {
  474. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  475. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  476. string encodedBrazilian = "%C3%B3culos";
  477. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  478. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  479. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  480. }
  481. TEST(DecodeUriTest, TestCompleteUri) {
  482. string encodedUri = "https://example.com/path%20with%20spaces/"
  483. "file%20name.html?q=hello%20world";
  484. EXPECT_EQ(
  485. httplib::decode_uri(encodedUri),
  486. "https://example.com/path with spaces/file name.html?q=hello world");
  487. }
  488. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  489. string original =
  490. "https://example.com/path with spaces/file name.html?q=hello world";
  491. string encoded = httplib::encode_uri(original);
  492. string decoded = httplib::decode_uri(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  496. string original = "Piri Tommy Villiers - on & on";
  497. string encoded = httplib::encode_uri_component(original);
  498. string decoded = httplib::decode_uri_component(encoded);
  499. EXPECT_EQ(decoded, original);
  500. }
  501. TEST(TrimTests, TrimStringTests) {
  502. EXPECT_EQ("abc", detail::trim_copy("abc"));
  503. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  504. EXPECT_TRUE(detail::trim_copy("").empty());
  505. }
  506. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  507. // Simple case without quality values
  508. std::vector<std::string> result1;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json,text/plain", result1));
  511. EXPECT_EQ(result1.size(), 3U);
  512. EXPECT_EQ(result1[0], "text/html");
  513. EXPECT_EQ(result1[1], "application/json");
  514. EXPECT_EQ(result1[2], "text/plain");
  515. // With quality values
  516. std::vector<std::string> result2;
  517. EXPECT_TRUE(detail::parse_accept_header(
  518. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  519. EXPECT_EQ(result2.size(), 3U);
  520. EXPECT_EQ(result2[0], "application/json"); // highest q value
  521. EXPECT_EQ(result2[1], "text/html");
  522. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  523. }
  524. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  525. // Mixed with and without quality values
  526. std::vector<std::string> result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  529. EXPECT_EQ(result.size(), 3U);
  530. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  531. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  532. EXPECT_EQ(result[2], "application/json"); // q=0.5
  533. }
  534. TEST(ParseAcceptHeaderTest, EdgeCases) {
  535. // Empty header
  536. std::vector<std::string> empty_result;
  537. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  538. EXPECT_TRUE(empty_result.empty());
  539. // Single type
  540. std::vector<std::string> single_result;
  541. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  542. EXPECT_EQ(single_result.size(), 1U);
  543. EXPECT_EQ(single_result[0], "application/json");
  544. // Wildcard types
  545. std::vector<std::string> wildcard_result;
  546. EXPECT_TRUE(detail::parse_accept_header(
  547. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  548. EXPECT_EQ(wildcard_result.size(), 3U);
  549. EXPECT_EQ(wildcard_result[0], "application/json");
  550. EXPECT_EQ(wildcard_result[1], "text/*");
  551. EXPECT_EQ(wildcard_result[2], "*/*");
  552. }
  553. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  554. // Common browser Accept header
  555. std::vector<std::string> browser_result;
  556. EXPECT_TRUE(
  557. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  558. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  559. browser_result));
  560. EXPECT_EQ(browser_result.size(), 6U);
  561. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  563. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  564. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  565. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  566. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  567. // API client header
  568. std::vector<std::string> api_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  571. api_result));
  572. EXPECT_EQ(api_result.size(), 3U);
  573. EXPECT_EQ(api_result[0], "application/json");
  574. EXPECT_EQ(api_result[1], "application/xml");
  575. EXPECT_EQ(api_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, SpecialCases) {
  578. // Quality value with 3 decimal places
  579. std::vector<std::string> decimal_result;
  580. EXPECT_TRUE(detail::parse_accept_header(
  581. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  582. EXPECT_EQ(decimal_result.size(), 2U);
  583. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  584. EXPECT_EQ(decimal_result[1], "text/html");
  585. // Zero quality (should still be included but with lowest priority)
  586. std::vector<std::string> zero_q_result;
  587. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  588. zero_q_result));
  589. EXPECT_EQ(zero_q_result.size(), 2U);
  590. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  591. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  592. // No spaces around commas
  593. std::vector<std::string> no_space_result;
  594. EXPECT_TRUE(detail::parse_accept_header(
  595. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  596. no_space_result));
  597. EXPECT_EQ(no_space_result.size(), 3U);
  598. EXPECT_EQ(no_space_result[0], "text/html");
  599. EXPECT_EQ(no_space_result[1], "application/json");
  600. EXPECT_EQ(no_space_result[2], "text/plain");
  601. }
  602. TEST(ParseAcceptHeaderTest, InvalidCases) {
  603. std::vector<std::string> result;
  604. // Invalid quality value (> 1.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  607. // Invalid quality value (< 0.0)
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  610. // Invalid quality value (not a number)
  611. EXPECT_FALSE(detail::parse_accept_header(
  612. "text/html;q=invalid,application/json", result));
  613. // Empty quality value
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("text/html;q=,application/json", result));
  616. // Invalid media type format (no slash and not wildcard)
  617. EXPECT_FALSE(
  618. detail::parse_accept_header("invalidtype,application/json", result));
  619. // Empty media type
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  622. // Only commas
  623. result.clear();
  624. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  625. // Valid cases should still work
  626. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*/*");
  629. EXPECT_TRUE(detail::parse_accept_header("*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "*");
  632. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  633. EXPECT_EQ(result.size(), 1U);
  634. EXPECT_EQ(result[0], "text/*");
  635. }
  636. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  637. Server svr;
  638. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  639. EXPECT_EQ(req.accept_content_types.size(), 3U);
  640. EXPECT_EQ(req.accept_content_types[0], "application/json");
  641. EXPECT_EQ(req.accept_content_types[1], "text/html");
  642. EXPECT_EQ(req.accept_content_types[2], "*/*");
  643. res.set_content("ok", "text/plain");
  644. });
  645. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  646. EXPECT_TRUE(false);
  647. res.set_content("bad request", "text/plain");
  648. });
  649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  650. auto se = detail::scope_exit([&] {
  651. svr.stop();
  652. listen_thread.join();
  653. ASSERT_FALSE(svr.is_running());
  654. });
  655. svr.wait_until_ready();
  656. Client cli("localhost", PORT);
  657. {
  658. auto res =
  659. cli.Get("/accept_ok",
  660. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::OK_200, res->status);
  663. }
  664. {
  665. auto res = cli.Get("/accept_bad_request",
  666. {{"Accept", "text/html;q=abc,application/json"}});
  667. ASSERT_TRUE(res);
  668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  669. }
  670. }
  671. TEST(DivideTest, DivideStringTests) {
  672. auto divide = [](const std::string &str, char d) {
  673. std::string lhs;
  674. std::string rhs;
  675. detail::divide(str, d,
  676. [&](const char *lhs_data, std::size_t lhs_size,
  677. const char *rhs_data, std::size_t rhs_size) {
  678. lhs.assign(lhs_data, lhs_size);
  679. rhs.assign(rhs_data, rhs_size);
  680. });
  681. return std::make_pair(std::move(lhs), std::move(rhs));
  682. };
  683. {
  684. const auto res = divide("", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "");
  687. }
  688. {
  689. const auto res = divide("=", '=');
  690. EXPECT_EQ(res.first, "");
  691. EXPECT_EQ(res.second, "");
  692. }
  693. {
  694. const auto res = divide(" ", '=');
  695. EXPECT_EQ(res.first, " ");
  696. EXPECT_EQ(res.second, "");
  697. }
  698. {
  699. const auto res = divide("a", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "");
  702. }
  703. {
  704. const auto res = divide("a=", '=');
  705. EXPECT_EQ(res.first, "a");
  706. EXPECT_EQ(res.second, "");
  707. }
  708. {
  709. const auto res = divide("=b", '=');
  710. EXPECT_EQ(res.first, "");
  711. EXPECT_EQ(res.second, "b");
  712. }
  713. {
  714. const auto res = divide("a=b", '=');
  715. EXPECT_EQ(res.first, "a");
  716. EXPECT_EQ(res.second, "b");
  717. }
  718. {
  719. const auto res = divide("a=b=", '=');
  720. EXPECT_EQ(res.first, "a");
  721. EXPECT_EQ(res.second, "b=");
  722. }
  723. {
  724. const auto res = divide("a=b=c", '=');
  725. EXPECT_EQ(res.first, "a");
  726. EXPECT_EQ(res.second, "b=c");
  727. }
  728. }
  729. TEST(SplitTest, ParseQueryString) {
  730. string s = "key1=val1&key2=val2&key3=val3";
  731. Params dic;
  732. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  733. [&](const char *b, const char *e) {
  734. string key, val;
  735. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  736. if (key.empty()) {
  737. key.assign(b2, e2);
  738. } else {
  739. val.assign(b2, e2);
  740. }
  741. });
  742. dic.emplace(key, val);
  743. });
  744. EXPECT_EQ("val1", dic.find("key1")->second);
  745. EXPECT_EQ("val2", dic.find("key2")->second);
  746. EXPECT_EQ("val3", dic.find("key3")->second);
  747. }
  748. TEST(SplitTest, ParseInvalidQueryTests) {
  749. {
  750. string s = " ";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. {
  756. string s = " = =";
  757. Params dict;
  758. detail::parse_query_text(s, dict);
  759. EXPECT_TRUE(dict.empty());
  760. }
  761. }
  762. TEST(ParseQueryTest, ParseQueryString) {
  763. {
  764. std::string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::parse_query_text(s, dic);
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. {
  772. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  773. Params dic;
  774. detail::parse_query_text(s, dic);
  775. EXPECT_EQ("", dic.find("key1")->second);
  776. EXPECT_EQ("val1", dic.find("key2")->second);
  777. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  778. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  779. }
  780. }
  781. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  782. Params dic;
  783. EXPECT_EQ(detail::params_to_query_str(dic), "");
  784. dic.emplace("key1", "val1");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  786. dic.emplace("key2", "val2");
  787. dic.emplace("key3", "val3");
  788. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  789. }
  790. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  791. string content_type = "multipart/form-data; boundary=something";
  792. string boundary;
  793. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  794. EXPECT_TRUE(ret);
  795. EXPECT_EQ(boundary, "something");
  796. }
  797. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  798. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  799. string boundary;
  800. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  803. }
  804. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  805. string content_type =
  806. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  807. string boundary;
  808. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  811. }
  812. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  813. string content_type =
  814. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  819. }
  820. TEST(GetHeaderValueTest, DefaultValue) {
  821. Headers headers = {{"Dummy", "Dummy"}};
  822. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  823. EXPECT_STREQ("text/plain", val);
  824. }
  825. TEST(GetHeaderValueTest, DefaultValueInt) {
  826. Headers headers = {{"Dummy", "Dummy"}};
  827. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  828. EXPECT_EQ(100ull, val);
  829. }
  830. TEST(GetHeaderValueTest, RegularValue) {
  831. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  833. EXPECT_STREQ("text/html", val);
  834. }
  835. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  836. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  837. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  838. EXPECT_STREQ("text/html", val);
  839. }
  840. TEST(GetHeaderValueTest, SetContent) {
  841. Response res;
  842. res.set_content("html", "text/html");
  843. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  844. res.set_content("text", "text/plain");
  845. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  846. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  847. }
  848. TEST(GetHeaderValueTest, RegularValueInt) {
  849. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  854. Headers headers = {{"Content-Length", "x"}};
  855. auto is_invalid_value = false;
  856. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  857. is_invalid_value);
  858. EXPECT_EQ(0ull, val);
  859. EXPECT_TRUE(is_invalid_value);
  860. }
  861. TEST(GetHeaderValueTest, Range) {
  862. {
  863. Headers headers = {make_range_header({{1, -1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=1-", val);
  866. }
  867. {
  868. Headers headers = {make_range_header({{-1, 1}})};
  869. auto val = detail::get_header_value(headers, "Range", 0, 0);
  870. EXPECT_STREQ("bytes=-1", val);
  871. }
  872. {
  873. Headers headers = {make_range_header({{1, 10}})};
  874. auto val = detail::get_header_value(headers, "Range", 0, 0);
  875. EXPECT_STREQ("bytes=1-10", val);
  876. }
  877. {
  878. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  879. auto val = detail::get_header_value(headers, "Range", 0, 0);
  880. EXPECT_STREQ("bytes=1-10, 100-", val);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  884. auto val = detail::get_header_value(headers, "Range", 0, 0);
  885. EXPECT_STREQ("bytes=1-10, 100-200", val);
  886. }
  887. {
  888. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  889. auto val = detail::get_header_value(headers, "Range", 0, 0);
  890. EXPECT_STREQ("bytes=0-0, -1", val);
  891. }
  892. }
  893. TEST(ParseHeaderValueTest, Range) {
  894. {
  895. Ranges ranges;
  896. auto ret = detail::parse_range_header("bytes=1-", ranges);
  897. EXPECT_TRUE(ret);
  898. EXPECT_EQ(1u, ranges.size());
  899. EXPECT_EQ(1u, ranges[0].first);
  900. EXPECT_EQ(-1, ranges[0].second);
  901. }
  902. {
  903. Ranges ranges;
  904. auto ret = detail::parse_range_header("bytes=-1", ranges);
  905. EXPECT_TRUE(ret);
  906. EXPECT_EQ(1u, ranges.size());
  907. EXPECT_EQ(-1, ranges[0].first);
  908. EXPECT_EQ(1u, ranges[0].second);
  909. }
  910. {
  911. Ranges ranges;
  912. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  913. EXPECT_TRUE(ret);
  914. EXPECT_EQ(1u, ranges.size());
  915. EXPECT_EQ(1u, ranges[0].first);
  916. EXPECT_EQ(10u, ranges[0].second);
  917. }
  918. {
  919. Ranges ranges;
  920. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  921. EXPECT_FALSE(ret);
  922. }
  923. {
  924. Ranges ranges;
  925. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  926. EXPECT_TRUE(ret);
  927. EXPECT_EQ(2u, ranges.size());
  928. EXPECT_EQ(1u, ranges[0].first);
  929. EXPECT_EQ(10u, ranges[0].second);
  930. EXPECT_EQ(100u, ranges[1].first);
  931. EXPECT_EQ(-1, ranges[1].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret =
  936. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(3u, ranges.size());
  939. EXPECT_EQ(1u, ranges[0].first);
  940. EXPECT_EQ(10u, ranges[0].second);
  941. EXPECT_EQ(100u, ranges[1].first);
  942. EXPECT_EQ(200u, ranges[1].second);
  943. EXPECT_EQ(300u, ranges[2].first);
  944. EXPECT_EQ(400u, ranges[2].second);
  945. }
  946. {
  947. Ranges ranges;
  948. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  958. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  959. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  960. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  961. EXPECT_TRUE(ranges.empty());
  962. }
  963. }
  964. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  972. #else
  973. EXPECT_TRUE(ret == detail::EncodingType::None);
  974. #endif
  975. }
  976. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  977. Request req;
  978. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  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(ParseAcceptEncoding3, AcceptEncoding) {
  993. Request req;
  994. req.set_header("Accept-Encoding",
  995. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1000. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1001. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1002. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1003. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1004. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1005. #else
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. #endif
  1008. }
  1009. TEST(BufferStreamTest, read) {
  1010. detail::BufferStream strm1;
  1011. Stream &strm = strm1;
  1012. EXPECT_EQ(5, strm.write("hello"));
  1013. char buf[512];
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('h', buf[0]);
  1016. EXPECT_EQ('e', buf[1]);
  1017. EXPECT_EQ(2, strm.read(buf, 2));
  1018. EXPECT_EQ('l', buf[0]);
  1019. EXPECT_EQ('l', buf[1]);
  1020. EXPECT_EQ(1, strm.read(buf, 1));
  1021. EXPECT_EQ('o', buf[0]);
  1022. EXPECT_EQ(0, strm.read(buf, 1));
  1023. }
  1024. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1025. auto host = "www.httpwatch.com";
  1026. auto ip = hosted_at(host);
  1027. EXPECT_EQ("23.96.13.243", ip);
  1028. std::vector<std::string> addrs;
  1029. hosted_at(host, addrs);
  1030. EXPECT_EQ(1u, addrs.size());
  1031. }
  1032. #if 0 // It depends on each test environment...
  1033. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1034. auto host = "www.youtube.com";
  1035. std::vector<std::string> addrs;
  1036. hosted_at(host, addrs);
  1037. EXPECT_EQ(20u, addrs.size());
  1038. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1039. EXPECT_TRUE(it != addrs.end());
  1040. }
  1041. #endif
  1042. class ChunkedEncodingTest : public ::testing::Test {
  1043. protected:
  1044. ChunkedEncodingTest()
  1045. : cli_(HOST, PORT)
  1046. #ifdef CPPHTTPLIB_SSL_ENABLED
  1047. ,
  1048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1049. #endif
  1050. {
  1051. cli_.set_connection_timeout(2);
  1052. #ifdef CPPHTTPLIB_SSL_ENABLED
  1053. cli_.enable_server_certificate_verification(false);
  1054. #endif
  1055. }
  1056. virtual void SetUp() {
  1057. read_file("./image.jpg", image_data_);
  1058. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1059. res.set_content("Hello World!", "text/plain");
  1060. });
  1061. svr_.Get(
  1062. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1063. res.set_chunked_content_provider(
  1064. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1065. size_t remaining = image_data_.size() - offset;
  1066. if (remaining == 0) {
  1067. sink.done();
  1068. } else {
  1069. constexpr size_t CHUNK_SIZE = 1024;
  1070. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1071. sink.write(&image_data_[offset], send_size);
  1072. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1073. }
  1074. return true;
  1075. });
  1076. });
  1077. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1078. svr_.wait_until_ready();
  1079. }
  1080. virtual void TearDown() {
  1081. svr_.stop();
  1082. if (!request_threads_.empty()) {
  1083. std::this_thread::sleep_for(std::chrono::seconds(1));
  1084. for (auto &t : request_threads_) {
  1085. t.join();
  1086. }
  1087. }
  1088. t_.join();
  1089. }
  1090. #ifdef CPPHTTPLIB_SSL_ENABLED
  1091. SSLClient cli_;
  1092. SSLServer svr_;
  1093. #else
  1094. Client cli_;
  1095. Server svr_;
  1096. #endif
  1097. thread t_;
  1098. std::vector<thread> request_threads_;
  1099. std::string image_data_;
  1100. };
  1101. TEST_F(ChunkedEncodingTest, NormalGet) {
  1102. auto res = cli_.Get("/chunked");
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, res->body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1122. std::string body;
  1123. auto res = cli_.Get(
  1124. "/chunked",
  1125. [&](const Response &response) {
  1126. EXPECT_EQ(StatusCode::OK_200, response.status);
  1127. return true;
  1128. },
  1129. [&](const char *data, size_t data_length) {
  1130. body.append(data, data_length);
  1131. return true;
  1132. });
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, body);
  1138. }
  1139. TEST(RangeTest, FromHTTPBin_Online) {
  1140. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1141. auto host = "httpcan.org";
  1142. auto path = std::string{"/range/32"};
  1143. #else
  1144. auto host = "nghttp2.org";
  1145. auto path = std::string{"/httpbin/range/32"};
  1146. #endif
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. auto port = 443;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 80;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(5);
  1155. {
  1156. auto res = cli.Get(path);
  1157. ASSERT_TRUE(res);
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1159. EXPECT_EQ(StatusCode::OK_200, res->status);
  1160. }
  1161. {
  1162. Headers headers = {make_range_header({{1, -1}})};
  1163. auto res = cli.Get(path, headers);
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1167. }
  1168. {
  1169. Headers headers = {make_range_header({{1, 10}})};
  1170. auto res = cli.Get(path, headers);
  1171. ASSERT_TRUE(res);
  1172. EXPECT_EQ("bcdefghijk", res->body);
  1173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1174. }
  1175. {
  1176. Headers headers = {make_range_header({{0, 31}})};
  1177. auto res = cli.Get(path, headers);
  1178. ASSERT_TRUE(res);
  1179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1180. EXPECT_EQ(StatusCode::OK_200, res->status);
  1181. }
  1182. {
  1183. Headers headers = {make_range_header({{0, -1}})};
  1184. auto res = cli.Get(path, headers);
  1185. ASSERT_TRUE(res);
  1186. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1187. EXPECT_EQ(StatusCode::OK_200, res->status);
  1188. }
  1189. {
  1190. Headers headers = {make_range_header({{0, 32}})};
  1191. auto res = cli.Get(path, headers);
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1194. }
  1195. }
  1196. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1197. auto host = "unresolvableaddress.local";
  1198. auto path = std::string{"/"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(1);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_FALSE(res);
  1210. }
  1211. std::this_thread::sleep_for(std::chrono::seconds(8));
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHost) {
  1214. auto host = "-abcde.com";
  1215. #ifdef CPPHTTPLIB_SSL_ENABLED
  1216. auto port = 443;
  1217. SSLClient cli(host, port);
  1218. #else
  1219. auto port = 80;
  1220. Client cli(host, port);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHost2) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. EXPECT_EQ(Error::Connection, res.error());
  1238. }
  1239. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1240. auto host = "httpcan.org/";
  1241. #ifdef CPPHTTPLIB_SSL_ENABLED
  1242. SSLClient cli(host);
  1243. #else
  1244. Client cli(host);
  1245. #endif
  1246. cli.set_connection_timeout(std::chrono::seconds(2));
  1247. auto res = cli.Get("/");
  1248. ASSERT_TRUE(!res);
  1249. stringstream s;
  1250. s << "error code: " << res.error();
  1251. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1252. }
  1253. TEST(ConnectionErrorTest, InvalidPort) {
  1254. auto host = "localhost";
  1255. auto port = 44380;
  1256. #ifdef CPPHTTPLIB_SSL_ENABLED
  1257. SSLClient cli(host, port);
  1258. #else
  1259. Client cli(host, port);
  1260. #endif
  1261. cli.set_connection_timeout(std::chrono::seconds(2));
  1262. auto res = cli.Get("/");
  1263. ASSERT_TRUE(!res);
  1264. EXPECT_TRUE(Error::Connection == res.error() ||
  1265. Error::ConnectionTimeout == res.error());
  1266. }
  1267. TEST(ConnectionErrorTest, Timeout_Online) {
  1268. auto host = "google.com";
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. auto port = 44380;
  1271. SSLClient cli(host, port);
  1272. #else
  1273. auto port = 8080;
  1274. Client cli(host, port);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. // only probe one address type so that the error reason
  1278. // correlates to the timed-out IPv4, not the unsupported
  1279. // IPv6 connection attempt
  1280. cli.set_address_family(AF_INET);
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1284. }
  1285. TEST(CancelTest, NoCancel_Online) {
  1286. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1287. auto host = "httpcan.org";
  1288. auto path = std::string{"/range/32"};
  1289. #else
  1290. auto host = "nghttp2.org";
  1291. auto path = std::string{"/httpbin/range/32"};
  1292. #endif
  1293. #ifdef CPPHTTPLIB_SSL_ENABLED
  1294. auto port = 443;
  1295. SSLClient cli(host, port);
  1296. #else
  1297. auto port = 80;
  1298. Client cli(host, port);
  1299. #endif
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1302. ASSERT_TRUE(res);
  1303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1304. EXPECT_EQ(StatusCode::OK_200, res->status);
  1305. }
  1306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1307. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1308. auto host = "httpcan.org";
  1309. auto path = std::string{"/range/32"};
  1310. #else
  1311. auto host = "nghttp2.org";
  1312. auto path = std::string{"/httpbin/range/32"};
  1313. #endif
  1314. #ifdef CPPHTTPLIB_SSL_ENABLED
  1315. auto port = 443;
  1316. SSLClient cli(host, port);
  1317. #else
  1318. auto port = 80;
  1319. Client cli(host, port);
  1320. #endif
  1321. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1322. cli.set_connection_timeout(std::chrono::seconds(5));
  1323. ASSERT_TRUE(!res);
  1324. EXPECT_EQ(Error::Canceled, res.error());
  1325. }
  1326. TEST(CancelTest, WithCancelLargePayload_Online) {
  1327. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1328. auto host = "httpcan.org";
  1329. auto path = std::string{"/range/65536"};
  1330. #else
  1331. auto host = "nghttp2.org";
  1332. auto path = std::string{"/httpbin/range/65536"};
  1333. #endif
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. auto port = 443;
  1336. SSLClient cli(host, port);
  1337. #else
  1338. auto port = 80;
  1339. Client cli(host, port);
  1340. #endif
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. uint32_t count = 0;
  1343. auto res =
  1344. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPost) {
  1349. Server svr;
  1350. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1370. Server svr;
  1371. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPost) {
  1390. Server svr;
  1391. svr.set_payload_max_length(200 * 1024 * 1024);
  1392. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(LARGE_DATA, "text/plain");
  1394. });
  1395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. thread.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, PORT);
  1403. cli.set_payload_max_length(200 * 1024 * 1024);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return false; });
  1408. ASSERT_TRUE(!res);
  1409. EXPECT_EQ(Error::Canceled, res.error());
  1410. }
  1411. TEST(CancelTest, NoCancelPut) {
  1412. Server svr;
  1413. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1414. res.set_content("Hello World!", "text/plain");
  1415. });
  1416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1417. auto se = detail::scope_exit([&] {
  1418. svr.stop();
  1419. thread.join();
  1420. ASSERT_FALSE(svr.is_running());
  1421. });
  1422. svr.wait_until_ready();
  1423. Client cli(HOST, PORT);
  1424. cli.set_connection_timeout(std::chrono::seconds(5));
  1425. auto res =
  1426. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1427. "application/json", [](uint64_t, uint64_t) { return true; });
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("Hello World!", res->body);
  1430. EXPECT_EQ(StatusCode::OK_200, res->status);
  1431. }
  1432. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content("Hello World!", "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, WithCancelLargePayloadPut) {
  1453. Server svr;
  1454. svr.set_payload_max_length(200 * 1024 * 1024);
  1455. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1456. res.set_content(LARGE_DATA, "text/plain");
  1457. });
  1458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. thread.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. Client cli(HOST, PORT);
  1466. cli.set_payload_max_length(200 * 1024 * 1024);
  1467. cli.set_connection_timeout(std::chrono::seconds(5));
  1468. auto res =
  1469. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1470. "application/json", [](uint64_t, uint64_t) { return false; });
  1471. ASSERT_TRUE(!res);
  1472. EXPECT_EQ(Error::Canceled, res.error());
  1473. }
  1474. TEST(CancelTest, NoCancelPatch) {
  1475. Server svr;
  1476. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1477. res.set_content("Hello World!", "text/plain");
  1478. });
  1479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. thread.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. Client cli(HOST, PORT);
  1487. cli.set_connection_timeout(std::chrono::seconds(5));
  1488. auto res =
  1489. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1490. "application/json", [](uint64_t, uint64_t) { return true; });
  1491. ASSERT_TRUE(res);
  1492. EXPECT_EQ("Hello World!", res->body);
  1493. EXPECT_EQ(StatusCode::OK_200, res->status);
  1494. }
  1495. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1496. Server svr;
  1497. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1498. res.set_content("Hello World!", "text/plain");
  1499. });
  1500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1501. auto se = detail::scope_exit([&] {
  1502. svr.stop();
  1503. thread.join();
  1504. ASSERT_FALSE(svr.is_running());
  1505. });
  1506. svr.wait_until_ready();
  1507. Client cli(HOST, PORT);
  1508. cli.set_connection_timeout(std::chrono::seconds(5));
  1509. auto res =
  1510. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1511. "application/json", [](uint64_t, uint64_t) { return false; });
  1512. ASSERT_TRUE(!res);
  1513. EXPECT_EQ(Error::Canceled, res.error());
  1514. }
  1515. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1516. Server svr;
  1517. svr.set_payload_max_length(200 * 1024 * 1024);
  1518. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1519. res.set_content(LARGE_DATA, "text/plain");
  1520. });
  1521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. thread.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. Client cli(HOST, PORT);
  1529. cli.set_payload_max_length(200 * 1024 * 1024);
  1530. cli.set_connection_timeout(std::chrono::seconds(5));
  1531. auto res =
  1532. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1533. "application/json", [](uint64_t, uint64_t) { return false; });
  1534. ASSERT_TRUE(!res);
  1535. EXPECT_EQ(Error::Canceled, res.error());
  1536. }
  1537. TEST(CancelTest, NoCancelDelete) {
  1538. Server svr;
  1539. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1540. res.set_content("Hello World!", "text/plain");
  1541. });
  1542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1543. auto se = detail::scope_exit([&] {
  1544. svr.stop();
  1545. thread.join();
  1546. ASSERT_FALSE(svr.is_running());
  1547. });
  1548. svr.wait_until_ready();
  1549. Client cli(HOST, PORT);
  1550. cli.set_connection_timeout(std::chrono::seconds(5));
  1551. auto res =
  1552. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1553. "application/json", [](uint64_t, uint64_t) { return true; });
  1554. ASSERT_TRUE(res);
  1555. EXPECT_EQ("Hello World!", res->body);
  1556. EXPECT_EQ(StatusCode::OK_200, res->status);
  1557. }
  1558. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1559. Server svr;
  1560. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1561. res.set_content("Hello World!", "text/plain");
  1562. });
  1563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1564. auto se = detail::scope_exit([&] {
  1565. svr.stop();
  1566. thread.join();
  1567. ASSERT_FALSE(svr.is_running());
  1568. });
  1569. svr.wait_until_ready();
  1570. Client cli(HOST, PORT);
  1571. cli.set_connection_timeout(std::chrono::seconds(5));
  1572. auto res =
  1573. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1574. "application/json", [](uint64_t, uint64_t) { return false; });
  1575. ASSERT_TRUE(!res);
  1576. EXPECT_EQ(Error::Canceled, res.error());
  1577. }
  1578. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1579. Server svr;
  1580. svr.set_payload_max_length(200 * 1024 * 1024);
  1581. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1582. res.set_content(LARGE_DATA, "text/plain");
  1583. });
  1584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. thread.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. Client cli(HOST, PORT);
  1592. cli.set_payload_max_length(200 * 1024 * 1024);
  1593. cli.set_connection_timeout(std::chrono::seconds(5));
  1594. auto res =
  1595. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1596. "application/json", [](uint64_t, uint64_t) { return false; });
  1597. ASSERT_TRUE(!res);
  1598. EXPECT_EQ(Error::Canceled, res.error());
  1599. }
  1600. static std::string remove_whitespace(const std::string &input) {
  1601. std::string output;
  1602. output.reserve(input.size());
  1603. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1604. [](unsigned char c) { return !std::isspace(c); });
  1605. return output;
  1606. }
  1607. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1609. auto host = "httpcan.org";
  1610. auto path = std::string{"/basic-auth/hello/world"};
  1611. #else
  1612. auto host = "nghttp2.org";
  1613. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1614. #endif
  1615. #ifdef CPPHTTPLIB_SSL_ENABLED
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. #else
  1619. auto port = 80;
  1620. Client cli(host, port);
  1621. #endif
  1622. {
  1623. auto res = cli.Get(path);
  1624. ASSERT_TRUE(res);
  1625. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1626. }
  1627. {
  1628. auto res =
  1629. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1632. remove_whitespace(res->body));
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. }
  1635. {
  1636. cli.set_basic_auth("hello", "world");
  1637. auto res = cli.Get(path);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1640. remove_whitespace(res->body));
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. {
  1644. cli.set_basic_auth("hello", "bad");
  1645. auto res = cli.Get(path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_basic_auth("bad", "world");
  1651. auto res = cli.Get(path);
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1654. }
  1655. }
  1656. #ifdef CPPHTTPLIB_SSL_ENABLED
  1657. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1658. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1659. auto host = "httpcan.org";
  1660. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1661. auto paths = std::vector<std::string>{
  1662. "/digest-auth/auth/hello/world/MD5",
  1663. "/digest-auth/auth/hello/world/SHA-256",
  1664. "/digest-auth/auth/hello/world/SHA-512",
  1665. };
  1666. #else
  1667. auto host = "nghttp2.org";
  1668. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1669. auto paths = std::vector<std::string>{
  1670. "/httpbin/digest-auth/auth/hello/world/MD5",
  1671. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1672. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1673. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1674. };
  1675. #endif
  1676. auto port = 443;
  1677. SSLClient cli(host, port);
  1678. {
  1679. auto res = cli.Get(unauth_path);
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1682. }
  1683. {
  1684. cli.set_digest_auth("hello", "world");
  1685. for (const auto &path : paths) {
  1686. auto res = cli.Get(path.c_str());
  1687. ASSERT_TRUE(res);
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. std::string algo(path.substr(path.rfind('/') + 1));
  1690. EXPECT_EQ(
  1691. remove_whitespace("{\"algorithm\":\"" + algo +
  1692. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1693. remove_whitespace(res->body));
  1694. #else
  1695. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1696. remove_whitespace(res->body));
  1697. #endif
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1701. cli.set_digest_auth("hello", "bad");
  1702. for (const auto &path : paths) {
  1703. auto res = cli.Get(path.c_str());
  1704. ASSERT_TRUE(res);
  1705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1706. }
  1707. #endif
  1708. }
  1709. }
  1710. #endif
  1711. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1712. auto host = "google.com";
  1713. auto another_host = "example.com";
  1714. auto wrong_ip = "0.0.0.0";
  1715. #ifdef CPPHTTPLIB_SSL_ENABLED
  1716. SSLClient cli(host);
  1717. #else
  1718. Client cli(host);
  1719. #endif
  1720. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1721. auto res = cli.Get("/");
  1722. ASSERT_TRUE(res);
  1723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1724. }
  1725. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1726. auto host = "google.com";
  1727. auto wrong_ip = "0.0.0.0";
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. SSLClient cli(host);
  1730. #else
  1731. Client cli(host);
  1732. #endif
  1733. cli.set_hostname_addr_map({{host, wrong_ip}});
  1734. auto res = cli.Get("/");
  1735. ASSERT_TRUE(!res);
  1736. EXPECT_EQ(Error::Connection, res.error());
  1737. }
  1738. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1739. auto host = "nghttp2.org";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_follow_location(true);
  1746. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1747. ASSERT_TRUE(res);
  1748. EXPECT_EQ(StatusCode::OK_200, res->status);
  1749. }
  1750. TEST(RedirectTest, Redirect_Online) {
  1751. auto host = "nghttp2.org";
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. SSLClient cli(host);
  1754. #else
  1755. Client cli(host);
  1756. #endif
  1757. cli.set_follow_location(true);
  1758. auto res = cli.Get("/httpbin/redirect/3");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. }
  1762. TEST(RelativeRedirectTest, Redirect_Online) {
  1763. auto host = "nghttp2.org";
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/httpbin/relative-redirect/3");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(TooManyRedirectTest, Redirect_Online) {
  1775. auto host = "nghttp2.org";
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli(host);
  1778. #else
  1779. Client cli(host);
  1780. #endif
  1781. cli.set_follow_location(true);
  1782. auto res = cli.Get("/httpbin/redirect/21");
  1783. ASSERT_TRUE(!res);
  1784. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1785. }
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. TEST(YahooRedirectTest, Redirect_Online) {
  1788. Client cli("yahoo.com");
  1789. auto res = cli.Get("/");
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1792. cli.set_follow_location(true);
  1793. res = cli.Get("/");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(StatusCode::OK_200, res->status);
  1796. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1797. }
  1798. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1799. #define REDIR_HOST "httpbingo.org"
  1800. #define REDIR_PATH "/redirect-to"
  1801. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1802. SSLClient cli(REDIR_HOST);
  1803. cli.set_follow_location(true);
  1804. auto res =
  1805. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. }
  1809. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1810. SSLClient cli(REDIR_HOST);
  1811. cli.set_follow_location(true);
  1812. Params params;
  1813. params.emplace("url", "http://example.com");
  1814. params.emplace("status_code", "302");
  1815. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. }
  1819. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. Params params;
  1823. params.emplace("url", "http://example.com");
  1824. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1825. ASSERT_TRUE(res);
  1826. EXPECT_EQ(StatusCode::OK_200, res->status);
  1827. }
  1828. TEST(UrlWithSpace, Redirect_Online) {
  1829. SSLClient cli("edge.forgecdn.net");
  1830. cli.set_follow_location(true);
  1831. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1835. }
  1836. #endif
  1837. #if !defined(_WIN32) && !defined(_WIN64)
  1838. TEST(ReceiveSignals, Signal) {
  1839. auto setupSignalHandlers = []() {
  1840. struct sigaction act;
  1841. sigemptyset(&act.sa_mask);
  1842. act.sa_flags = SA_SIGINFO;
  1843. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1844. switch (sig) {
  1845. case SIGINT:
  1846. default: break;
  1847. }
  1848. };
  1849. ::sigaction(SIGINT, &act, nullptr);
  1850. };
  1851. Server svr;
  1852. int port = 0;
  1853. auto thread = std::thread([&]() {
  1854. setupSignalHandlers();
  1855. port = svr.bind_to_any_port(HOST);
  1856. svr.listen_after_bind();
  1857. });
  1858. auto se = detail::scope_exit([&] {
  1859. svr.stop();
  1860. thread.join();
  1861. ASSERT_FALSE(svr.is_running());
  1862. });
  1863. svr.wait_until_ready();
  1864. ASSERT_TRUE(svr.is_running());
  1865. pthread_kill(thread.native_handle(), SIGINT);
  1866. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1867. ASSERT_TRUE(svr.is_running());
  1868. }
  1869. #endif
  1870. TEST(RedirectToDifferentPort, Redirect) {
  1871. Server svr1;
  1872. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1873. res.set_content("Hello World!", "text/plain");
  1874. });
  1875. int svr1_port = 0;
  1876. auto thread1 = std::thread([&]() {
  1877. svr1_port = svr1.bind_to_any_port(HOST);
  1878. svr1.listen_after_bind();
  1879. });
  1880. Server svr2;
  1881. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1882. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1883. });
  1884. int svr2_port = 0;
  1885. auto thread2 = std::thread([&]() {
  1886. svr2_port = svr2.bind_to_any_port(HOST);
  1887. svr2.listen_after_bind();
  1888. });
  1889. auto se = detail::scope_exit([&] {
  1890. svr2.stop();
  1891. thread2.join();
  1892. svr1.stop();
  1893. thread1.join();
  1894. ASSERT_FALSE(svr2.is_running());
  1895. ASSERT_FALSE(svr1.is_running());
  1896. });
  1897. svr1.wait_until_ready();
  1898. svr2.wait_until_ready();
  1899. Client cli("localhost", svr2_port);
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get("/2");
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. }
  1906. TEST(RedirectFromPageWithContent, Redirect) {
  1907. Server svr;
  1908. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1909. res.set_content("___", "text/plain");
  1910. res.set_redirect("/2");
  1911. });
  1912. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. th.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. {
  1923. Client cli("localhost", PORT);
  1924. cli.set_follow_location(true);
  1925. std::string body;
  1926. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1927. body.append(data, data_length);
  1928. return true;
  1929. });
  1930. ASSERT_TRUE(res);
  1931. EXPECT_EQ(StatusCode::OK_200, res->status);
  1932. EXPECT_EQ("Hello World!", body);
  1933. }
  1934. {
  1935. Client cli("localhost", PORT);
  1936. std::string body;
  1937. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(StatusCode::Found_302, res->status);
  1943. EXPECT_EQ("___", body);
  1944. }
  1945. }
  1946. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1947. Server svr;
  1948. auto port_str = std::to_string(PORT);
  1949. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1950. auto expected_host = "[::1]:" + port_str;
  1951. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("___", "text/plain");
  1953. // res.set_redirect("/2");
  1954. res.set_redirect(redirect_url);
  1955. });
  1956. svr.Get("/2", [&](const Request &req, Response &res) {
  1957. auto host_header = req.headers.find("Host");
  1958. ASSERT_TRUE(host_header != req.headers.end());
  1959. EXPECT_EQ(expected_host, host_header->second);
  1960. res.set_content("Hello World!", "text/plain");
  1961. });
  1962. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1963. auto se = detail::scope_exit([&] {
  1964. svr.stop();
  1965. th.join();
  1966. ASSERT_FALSE(svr.is_running());
  1967. });
  1968. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1969. // actually starts anything, so the condition !svr.is_running() will
  1970. // always remain true, and the loop never stops.
  1971. // This basically counts how many milliseconds have passed since the
  1972. // call to svr.listen(), and if after 5 seconds nothing started yet
  1973. // aborts the test.
  1974. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1975. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1976. ASSERT_LT(milliseconds, 5000U);
  1977. }
  1978. {
  1979. Client cli("::1", PORT);
  1980. cli.set_follow_location(true);
  1981. std::string body;
  1982. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1983. body.append(data, data_length);
  1984. return true;
  1985. });
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::OK_200, res->status);
  1988. EXPECT_EQ("Hello World!", body);
  1989. }
  1990. {
  1991. Client cli("::1", PORT);
  1992. std::string body;
  1993. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1994. body.append(data, data_length);
  1995. return true;
  1996. });
  1997. ASSERT_TRUE(res);
  1998. EXPECT_EQ(StatusCode::Found_302, res->status);
  1999. EXPECT_EQ("___", body);
  2000. }
  2001. }
  2002. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2003. Server svr;
  2004. svr.Get("/foo", [](const Request &req, Response &res) {
  2005. auto a = req.params.find("a");
  2006. if (a != req.params.end()) {
  2007. res.set_content((*a).second, "text/plain");
  2008. res.status = StatusCode::OK_200;
  2009. } else {
  2010. res.status = StatusCode::BadRequest_400;
  2011. }
  2012. });
  2013. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2014. auto se = detail::scope_exit([&] {
  2015. svr.stop();
  2016. thread.join();
  2017. ASSERT_FALSE(svr.is_running());
  2018. });
  2019. svr.wait_until_ready();
  2020. {
  2021. Client cli(HOST, PORT);
  2022. cli.set_path_encode(false);
  2023. auto res = cli.Get("/foo?a=explicitly+encoded");
  2024. ASSERT_TRUE(res);
  2025. EXPECT_EQ(StatusCode::OK_200, res->status);
  2026. // This expects it back with a space, as the `+` won't have been
  2027. // url-encoded, and server-side the params get decoded turning `+`
  2028. // into spaces.
  2029. EXPECT_EQ("explicitly encoded", res->body);
  2030. }
  2031. }
  2032. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2033. Server svr;
  2034. svr.Get("/", [](const Request &req, Response &) {
  2035. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2036. });
  2037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2038. auto se = detail::scope_exit([&] {
  2039. svr.stop();
  2040. thread.join();
  2041. ASSERT_FALSE(svr.is_running());
  2042. });
  2043. svr.wait_until_ready();
  2044. {
  2045. Client cli(HOST, PORT);
  2046. cli.set_path_encode(false);
  2047. auto res = cli.Get("/?something=%0A");
  2048. ASSERT_TRUE(res);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. }
  2052. TEST(BindServerTest, DISABLED_BindDualStack) {
  2053. Server svr;
  2054. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2055. res.set_content("Hello World!", "text/plain");
  2056. });
  2057. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2058. auto se = detail::scope_exit([&] {
  2059. svr.stop();
  2060. thread.join();
  2061. ASSERT_FALSE(svr.is_running());
  2062. });
  2063. svr.wait_until_ready();
  2064. {
  2065. Client cli("127.0.0.1", PORT);
  2066. auto res = cli.Get("/1");
  2067. ASSERT_TRUE(res);
  2068. EXPECT_EQ(StatusCode::OK_200, res->status);
  2069. EXPECT_EQ("Hello World!", res->body);
  2070. }
  2071. {
  2072. Client cli("::1", PORT);
  2073. auto res = cli.Get("/1");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. EXPECT_EQ("Hello World!", res->body);
  2077. }
  2078. }
  2079. TEST(BindServerTest, BindAndListenSeparately) {
  2080. Server svr;
  2081. int port = svr.bind_to_any_port("0.0.0.0");
  2082. ASSERT_TRUE(svr.is_valid());
  2083. ASSERT_TRUE(port > 0);
  2084. svr.stop();
  2085. }
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2089. CLIENT_CA_CERT_DIR);
  2090. int port = svr.bind_to_any_port("0.0.0.0");
  2091. ASSERT_TRUE(svr.is_valid());
  2092. ASSERT_TRUE(port > 0);
  2093. svr.stop();
  2094. }
  2095. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2096. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2097. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2098. int port = svr.bind_to_any_port("0.0.0.0");
  2099. ASSERT_TRUE(svr.is_valid());
  2100. ASSERT_TRUE(port > 0);
  2101. svr.stop();
  2102. }
  2103. TEST(BindServerTest, UpdateCertsPem) {
  2104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2105. int port = svr.bind_to_any_port("0.0.0.0");
  2106. ASSERT_TRUE(svr.is_valid());
  2107. ASSERT_TRUE(port > 0);
  2108. // Read PEM files
  2109. std::string cert_pem, key_pem, ca_pem;
  2110. read_file(SERVER_CERT_FILE, cert_pem);
  2111. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2112. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2113. // Update server certificates using PEM API
  2114. ASSERT_TRUE(
  2115. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2116. ASSERT_TRUE(svr.is_valid());
  2117. svr.stop();
  2118. }
  2119. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2120. // Start server with client CA (enables client auth)
  2121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2122. ASSERT_TRUE(svr.is_valid());
  2123. bool handler_called = false;
  2124. svr.Get("/test", [&](const Request &req, Response &res) {
  2125. handler_called = true;
  2126. // Verify client certificate is present
  2127. auto cert = req.peer_cert();
  2128. EXPECT_TRUE(static_cast<bool>(cert));
  2129. res.set_content("ok", "text/plain");
  2130. });
  2131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. t.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. // Read PEM files
  2139. std::string cert_pem, key_pem, ca_pem;
  2140. read_file(SERVER_CERT_FILE, cert_pem);
  2141. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2142. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2143. // Update server certificates and client CA using PEM API while server running
  2144. ASSERT_TRUE(
  2145. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2146. // Connect with client certificate
  2147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2148. cli.enable_server_certificate_verification(false);
  2149. cli.set_connection_timeout(30);
  2150. auto res = cli.Get("/test");
  2151. ASSERT_TRUE(res);
  2152. ASSERT_EQ(StatusCode::OK_200, res->status);
  2153. ASSERT_TRUE(handler_called);
  2154. EXPECT_EQ("ok", res->body);
  2155. }
  2156. #endif
  2157. TEST(ErrorHandlerTest, ContentLength) {
  2158. Server svr;
  2159. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2160. res.status = StatusCode::OK_200;
  2161. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2162. "text/html"); // <= Content-Length still 13
  2163. });
  2164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2165. res.set_content("Hello World!\n", "text/plain");
  2166. res.status = 524;
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. {
  2176. Client cli(HOST, PORT);
  2177. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(StatusCode::OK_200, res->status);
  2180. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2181. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2182. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2183. }
  2184. }
  2185. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2186. TEST(ExceptionTest, WithoutExceptionHandler) {
  2187. Server svr;
  2188. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception...");
  2190. });
  2191. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2192. throw std::runtime_error("exception\r\n...");
  2193. });
  2194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. listen_thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli("localhost", PORT);
  2202. {
  2203. auto res = cli.Get("/exception");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2206. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2207. }
  2208. {
  2209. auto res = cli.Get("/unknown");
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2213. }
  2214. }
  2215. TEST(ExceptionTest, WithExceptionHandler) {
  2216. Server svr;
  2217. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2218. std::exception_ptr ep) {
  2219. EXPECT_FALSE(ep == nullptr);
  2220. try {
  2221. std::rethrow_exception(ep);
  2222. } catch (std::exception &e) {
  2223. EXPECT_EQ("abc", std::string(e.what()));
  2224. } catch (...) {}
  2225. res.status = StatusCode::InternalServerError_500;
  2226. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2227. "text/html"); // <= Content-Length still 13 at this point
  2228. });
  2229. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2230. res.set_content("Hello World!\n", "text/plain");
  2231. throw std::runtime_error("abc");
  2232. });
  2233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2234. auto se = detail::scope_exit([&] {
  2235. svr.stop();
  2236. thread.join();
  2237. ASSERT_FALSE(svr.is_running());
  2238. });
  2239. svr.wait_until_ready();
  2240. for (size_t i = 0; i < 10; i++) {
  2241. Client cli(HOST, PORT);
  2242. for (size_t j = 0; j < 100; j++) {
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2249. }
  2250. cli.set_keep_alive(true);
  2251. for (size_t j = 0; j < 100; j++) {
  2252. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2253. ASSERT_TRUE(res);
  2254. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2255. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2256. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2257. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2258. }
  2259. }
  2260. }
  2261. TEST(ExceptionTest, AndErrorHandler) {
  2262. Server svr;
  2263. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2264. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2265. });
  2266. svr.set_exception_handler(
  2267. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2268. EXPECT_FALSE(ep == nullptr);
  2269. try {
  2270. std::rethrow_exception(ep);
  2271. } catch (std::exception &e) {
  2272. res.set_content(e.what(), "text/html");
  2273. } catch (...) {}
  2274. res.status = StatusCode::InternalServerError_500;
  2275. });
  2276. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2277. throw std::runtime_error("EXCEPTION");
  2278. });
  2279. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2280. res.set_content("ERROR", "text/html");
  2281. res.status = StatusCode::InternalServerError_500;
  2282. });
  2283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2284. auto se = detail::scope_exit([&] {
  2285. svr.stop();
  2286. thread.join();
  2287. ASSERT_FALSE(svr.is_running());
  2288. });
  2289. svr.wait_until_ready();
  2290. Client cli(HOST, PORT);
  2291. {
  2292. auto res = cli.Get("/exception");
  2293. ASSERT_TRUE(res);
  2294. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2295. EXPECT_EQ("EXCEPTION", res->body);
  2296. }
  2297. {
  2298. auto res = cli.Get("/error");
  2299. ASSERT_TRUE(res);
  2300. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2301. EXPECT_EQ("ERROR", res->body);
  2302. }
  2303. {
  2304. auto res = cli.Get("/invalid");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2307. EXPECT_EQ("NOT_FOUND", res->body);
  2308. }
  2309. }
  2310. #endif
  2311. TEST(NoContentTest, ContentLength) {
  2312. Server svr;
  2313. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2314. res.status = StatusCode::NoContent_204;
  2315. });
  2316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2317. auto se = detail::scope_exit([&] {
  2318. svr.stop();
  2319. thread.join();
  2320. ASSERT_FALSE(svr.is_running());
  2321. });
  2322. svr.wait_until_ready();
  2323. {
  2324. Client cli(HOST, PORT);
  2325. auto res = cli.Get("/hi");
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2329. }
  2330. }
  2331. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2334. ASSERT_TRUE(svr.is_valid());
  2335. #else
  2336. Server svr;
  2337. #endif
  2338. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2339. if (req.path == "/routing_handler") {
  2340. res.set_header("PRE_ROUTING", "on");
  2341. res.set_content("Routing Handler", "text/plain");
  2342. return httplib::Server::HandlerResponse::Handled;
  2343. }
  2344. return httplib::Server::HandlerResponse::Unhandled;
  2345. });
  2346. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2347. res.set_content("Error", "text/html");
  2348. });
  2349. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2350. if (req.path == "/routing_handler") {
  2351. res.set_header("POST_ROUTING", "on");
  2352. }
  2353. });
  2354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!\n", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. {
  2365. #ifdef CPPHTTPLIB_SSL_ENABLED
  2366. SSLClient cli(HOST, PORT);
  2367. cli.enable_server_certificate_verification(false);
  2368. #else
  2369. Client cli(HOST, PORT);
  2370. #endif
  2371. auto res = cli.Get("/routing_handler");
  2372. ASSERT_TRUE(res);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. EXPECT_EQ("Routing Handler", res->body);
  2375. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2376. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2377. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2378. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2379. }
  2380. {
  2381. #ifdef CPPHTTPLIB_SSL_ENABLED
  2382. SSLClient cli(HOST, PORT);
  2383. cli.enable_server_certificate_verification(false);
  2384. #else
  2385. Client cli(HOST, PORT);
  2386. #endif
  2387. auto res = cli.Get("/hi");
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!\n", res->body);
  2391. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2392. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2393. }
  2394. {
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. SSLClient cli(HOST, PORT);
  2397. cli.enable_server_certificate_verification(false);
  2398. #else
  2399. Client cli(HOST, PORT);
  2400. #endif
  2401. auto res = cli.Get("/aaa");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("Error", res->body);
  2405. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2406. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2407. }
  2408. }
  2409. TEST(RequestHandlerTest, PreRequestHandler) {
  2410. auto route_path = "/user/:user";
  2411. Server svr;
  2412. svr.Get("/hi", [](const Request &, Response &res) {
  2413. res.set_content("hi", "text/plain");
  2414. });
  2415. svr.Get(route_path, [](const Request &req, Response &res) {
  2416. res.set_content(req.path_params.at("user"), "text/plain");
  2417. });
  2418. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2419. if (req.matched_route == route_path) {
  2420. auto user = req.path_params.at("user");
  2421. if (user != "john") {
  2422. res.status = StatusCode::Forbidden_403;
  2423. res.set_content("error", "text/html");
  2424. return Server::HandlerResponse::Handled;
  2425. }
  2426. }
  2427. return Server::HandlerResponse::Unhandled;
  2428. });
  2429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. thread.join();
  2433. ASSERT_FALSE(svr.is_running());
  2434. });
  2435. svr.wait_until_ready();
  2436. Client cli(HOST, PORT);
  2437. {
  2438. auto res = cli.Get("/hi");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(StatusCode::OK_200, res->status);
  2441. EXPECT_EQ("hi", res->body);
  2442. }
  2443. {
  2444. auto res = cli.Get("/user/john");
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ(StatusCode::OK_200, res->status);
  2447. EXPECT_EQ("john", res->body);
  2448. }
  2449. {
  2450. auto res = cli.Get("/user/invalid-user");
  2451. ASSERT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2453. EXPECT_EQ("error", res->body);
  2454. }
  2455. }
  2456. TEST(AnyTest, BasicOperations) {
  2457. // Default construction
  2458. httplib::any a;
  2459. EXPECT_FALSE(a.has_value());
  2460. // Value construction and any_cast (pointer form, noexcept)
  2461. httplib::any b(42);
  2462. EXPECT_TRUE(b.has_value());
  2463. auto *p = httplib::any_cast<int>(&b);
  2464. ASSERT_NE(nullptr, p);
  2465. EXPECT_EQ(42, *p);
  2466. // Type mismatch → nullptr
  2467. auto *q = httplib::any_cast<std::string>(&b);
  2468. EXPECT_EQ(nullptr, q);
  2469. // any_cast (value form) succeeds
  2470. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2471. // any_cast (value form) throws on type mismatch
  2472. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2473. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2474. #endif
  2475. // Copy
  2476. httplib::any c = b;
  2477. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2478. // Move
  2479. httplib::any d = std::move(c);
  2480. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2481. // Assignment with different type
  2482. b = std::string("hello");
  2483. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2484. // Reset
  2485. b.reset();
  2486. EXPECT_FALSE(b.has_value());
  2487. }
  2488. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2489. struct AuthCtx {
  2490. std::string user_id;
  2491. };
  2492. Server svr;
  2493. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2494. res.user_data["auth"] = AuthCtx{"alice"};
  2495. return Server::HandlerResponse::Unhandled;
  2496. });
  2497. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2498. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2499. ASSERT_NE(nullptr, ctx);
  2500. res.set_content("Hello " + ctx->user_id, "text/plain");
  2501. });
  2502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2503. auto se = detail::scope_exit([&] {
  2504. svr.stop();
  2505. thread.join();
  2506. ASSERT_FALSE(svr.is_running());
  2507. });
  2508. svr.wait_until_ready();
  2509. Client cli(HOST, PORT);
  2510. auto res = cli.Get("/me");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("Hello alice", res->body);
  2514. }
  2515. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2516. struct RoleCtx {
  2517. std::string role;
  2518. };
  2519. Server svr;
  2520. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2521. res.user_data["role"] = RoleCtx{"admin"};
  2522. return Server::HandlerResponse::Unhandled;
  2523. });
  2524. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2525. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2526. ASSERT_NE(nullptr, ctx);
  2527. res.set_content(ctx->role, "text/plain");
  2528. });
  2529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2530. auto se = detail::scope_exit([&] {
  2531. svr.stop();
  2532. thread.join();
  2533. ASSERT_FALSE(svr.is_running());
  2534. });
  2535. svr.wait_until_ready();
  2536. Client cli(HOST, PORT);
  2537. auto res = cli.Get("/role");
  2538. ASSERT_TRUE(res);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. EXPECT_EQ("admin", res->body);
  2541. }
  2542. TEST(InvalidFormatTest, StatusCode) {
  2543. Server svr;
  2544. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2545. res.set_content("Hello World!\n", "text/plain");
  2546. res.status = 9999; // Status should be a three-digit code...
  2547. });
  2548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2549. auto se = detail::scope_exit([&] {
  2550. svr.stop();
  2551. thread.join();
  2552. ASSERT_FALSE(svr.is_running());
  2553. });
  2554. svr.wait_until_ready();
  2555. {
  2556. Client cli(HOST, PORT);
  2557. auto res = cli.Get("/hi");
  2558. ASSERT_FALSE(res);
  2559. }
  2560. }
  2561. TEST(URLFragmentTest, WithFragment) {
  2562. Server svr;
  2563. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2564. EXPECT_TRUE(req.target == "/hi");
  2565. });
  2566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2567. auto se = detail::scope_exit([&] {
  2568. svr.stop();
  2569. thread.join();
  2570. ASSERT_FALSE(svr.is_running());
  2571. });
  2572. svr.wait_until_ready();
  2573. {
  2574. Client cli(HOST, PORT);
  2575. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2576. EXPECT_TRUE(res);
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. res = cli.Get("/hi%23key1=val1=key2=val2");
  2579. EXPECT_TRUE(res);
  2580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2581. }
  2582. }
  2583. TEST(HeaderWriter, SetHeaderWriter) {
  2584. Server svr;
  2585. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2586. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2587. return detail::write_headers(strm, hdrs);
  2588. });
  2589. svr.Get("/hi", [](const Request &req, Response &res) {
  2590. auto it = req.headers.find("CustomClientHeader");
  2591. EXPECT_TRUE(it != req.headers.end());
  2592. EXPECT_EQ(it->second, "CustomClientValue");
  2593. res.set_content("Hello World!\n", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. {
  2603. Client cli(HOST, PORT);
  2604. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2605. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2606. return detail::write_headers(strm, hdrs);
  2607. });
  2608. auto res = cli.Get("/hi");
  2609. EXPECT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. auto it = res->headers.find("CustomServerHeader");
  2612. EXPECT_TRUE(it != res->headers.end());
  2613. EXPECT_EQ(it->second, "CustomServerValue");
  2614. }
  2615. }
  2616. class ServerTest : public ::testing::Test {
  2617. protected:
  2618. ServerTest()
  2619. : cli_(HOST, PORT)
  2620. #ifdef CPPHTTPLIB_SSL_ENABLED
  2621. ,
  2622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2623. #endif
  2624. {
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. cli_.enable_server_certificate_verification(false);
  2627. #endif
  2628. // Allow LARGE_DATA (100MB) responses
  2629. cli_.set_payload_max_length(200 * 1024 * 1024);
  2630. }
  2631. virtual void SetUp() {
  2632. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2633. svr_.set_payload_max_length(200 * 1024 * 1024);
  2634. svr_.set_mount_point("/", "./www");
  2635. svr_.set_mount_point("/mount", "./www2");
  2636. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2637. svr_.Get("/hi",
  2638. [&](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!", "text/plain");
  2640. })
  2641. .Get("/file_content",
  2642. [&](const Request & /*req*/, Response &res) {
  2643. res.set_file_content("./www/dir/test.html");
  2644. })
  2645. .Get("/file_content_with_content_type",
  2646. [&](const Request & /*req*/, Response &res) {
  2647. res.set_file_content("./www/file", "text/plain");
  2648. })
  2649. .Get("/invalid_file_content",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. res.set_file_content("./www/dir/invalid_file_path");
  2652. })
  2653. .Get("/http_response_splitting",
  2654. [&](const Request & /*req*/, Response &res) {
  2655. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2656. EXPECT_EQ(0U, res.headers.size());
  2657. EXPECT_FALSE(res.has_header("a"));
  2658. res.set_header("a", "1\nSet-Cookie: a=1");
  2659. EXPECT_EQ(0U, res.headers.size());
  2660. EXPECT_FALSE(res.has_header("a"));
  2661. res.set_header("a", "1\rSet-Cookie: a=1");
  2662. EXPECT_EQ(0U, res.headers.size());
  2663. EXPECT_FALSE(res.has_header("a"));
  2664. res.set_header("a\r\nb", "0");
  2665. EXPECT_EQ(0U, res.headers.size());
  2666. EXPECT_FALSE(res.has_header("a"));
  2667. res.set_header("a\rb", "0");
  2668. EXPECT_EQ(0U, res.headers.size());
  2669. EXPECT_FALSE(res.has_header("a"));
  2670. res.set_header("a\nb", "0");
  2671. EXPECT_EQ(0U, res.headers.size());
  2672. EXPECT_FALSE(res.has_header("a"));
  2673. res.set_redirect("1\r\nSet-Cookie: a=1");
  2674. EXPECT_EQ(0U, res.headers.size());
  2675. EXPECT_FALSE(res.has_header("Location"));
  2676. })
  2677. .Get("/slow",
  2678. [&](const Request & /*req*/, Response &res) {
  2679. std::this_thread::sleep_for(std::chrono::seconds(2));
  2680. res.set_content("slow", "text/plain");
  2681. })
  2682. #if 0
  2683. .Post("/slowpost",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. std::this_thread::sleep_for(std::chrono::seconds(2));
  2686. res.set_content("slow", "text/plain");
  2687. })
  2688. #endif
  2689. .Get("/remote_addr",
  2690. [&](const Request &req, Response &res) {
  2691. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2692. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2694. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2695. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2696. #endif
  2697. res.set_content(req.remote_addr, "text/plain");
  2698. })
  2699. .Get("/local_addr",
  2700. [&](const Request &req, Response &res) {
  2701. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2702. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2703. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2704. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2705. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2706. #endif
  2707. auto local_addr = req.local_addr;
  2708. auto local_port = std::to_string(req.local_port);
  2709. res.set_content(local_addr.append(":").append(local_port),
  2710. "text/plain");
  2711. })
  2712. .Get("/endwith%",
  2713. [&](const Request & /*req*/, Response &res) {
  2714. res.set_content("Hello World!", "text/plain");
  2715. })
  2716. .Get("/a\\+\\+b",
  2717. [&](const Request &req, Response &res) {
  2718. ASSERT_TRUE(req.has_param("a +b"));
  2719. auto val = req.get_param_value("a +b");
  2720. res.set_content(val, "text/plain");
  2721. })
  2722. .Get("/", [&](const Request & /*req*/,
  2723. Response &res) { res.set_redirect("/hi"); })
  2724. .Post("/1",
  2725. [](const Request & /*req*/, Response &res) {
  2726. res.set_redirect("/2", StatusCode::SeeOther_303);
  2727. })
  2728. .Get("/2",
  2729. [](const Request & /*req*/, Response &res) {
  2730. res.set_content("redirected.", "text/plain");
  2731. res.status = StatusCode::OK_200;
  2732. })
  2733. .Post("/person",
  2734. [&](const Request &req, Response &res) {
  2735. if (req.has_param("name") && req.has_param("note")) {
  2736. persons_[req.get_param_value("name")] =
  2737. req.get_param_value("note");
  2738. } else {
  2739. res.status = StatusCode::BadRequest_400;
  2740. }
  2741. })
  2742. .Put("/person",
  2743. [&](const Request &req, Response &res) {
  2744. if (req.has_param("name") && req.has_param("note")) {
  2745. persons_[req.get_param_value("name")] =
  2746. req.get_param_value("note");
  2747. } else {
  2748. res.status = StatusCode::BadRequest_400;
  2749. }
  2750. })
  2751. .Get("/person/(.*)",
  2752. [&](const Request &req, Response &res) {
  2753. string name = req.matches[1];
  2754. if (persons_.find(name) != persons_.end()) {
  2755. auto note = persons_[name];
  2756. res.set_content(note, "text/plain");
  2757. } else {
  2758. res.status = StatusCode::NotFound_404;
  2759. }
  2760. })
  2761. .Delete("/person",
  2762. [&](const Request &req, Response &res) {
  2763. if (req.has_param("name")) {
  2764. string name = req.get_param_value("name");
  2765. if (persons_.find(name) != persons_.end()) {
  2766. persons_.erase(name);
  2767. res.set_content("DELETED", "text/plain");
  2768. } else {
  2769. res.status = StatusCode::NotFound_404;
  2770. }
  2771. } else {
  2772. res.status = StatusCode::BadRequest_400;
  2773. }
  2774. })
  2775. .Post("/x-www-form-urlencoded-json",
  2776. [&](const Request &req, Response &res) {
  2777. auto json = req.get_param_value("json");
  2778. ASSERT_EQ(JSON_DATA, json);
  2779. res.set_content(json, "appliation/json");
  2780. res.status = StatusCode::OK_200;
  2781. })
  2782. .Get("/streamed-chunked",
  2783. [&](const Request & /*req*/, Response &res) {
  2784. res.set_chunked_content_provider(
  2785. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2786. sink.os << "123";
  2787. sink.os << "456";
  2788. sink.os << "789";
  2789. sink.done();
  2790. return true;
  2791. });
  2792. })
  2793. .Get("/streamed-chunked-with-prohibited-trailer",
  2794. [&](const Request & /*req*/, Response &res) {
  2795. auto i = new int(0);
  2796. // Declare both a prohibited trailer (Content-Length) and an
  2797. // allowed one
  2798. res.set_header("Trailer", "Content-Length, X-Allowed");
  2799. res.set_chunked_content_provider(
  2800. "text/plain",
  2801. [i](size_t /*offset*/, DataSink &sink) {
  2802. switch (*i) {
  2803. case 0: sink.os << "123"; break;
  2804. case 1: sink.os << "456"; break;
  2805. case 2: sink.os << "789"; break;
  2806. case 3: {
  2807. sink.done_with_trailer(
  2808. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2809. } break;
  2810. }
  2811. (*i)++;
  2812. return true;
  2813. },
  2814. [i](bool success) {
  2815. EXPECT_TRUE(success);
  2816. delete i;
  2817. });
  2818. })
  2819. .Get("/streamed-chunked2",
  2820. [&](const Request & /*req*/, Response &res) {
  2821. auto i = new int(0);
  2822. res.set_chunked_content_provider(
  2823. "text/plain",
  2824. [i](size_t /*offset*/, DataSink &sink) {
  2825. switch (*i) {
  2826. case 0: sink.os << "123"; break;
  2827. case 1: sink.os << "456"; break;
  2828. case 2: sink.os << "789"; break;
  2829. case 3: sink.done(); break;
  2830. }
  2831. (*i)++;
  2832. return true;
  2833. },
  2834. [i](bool success) {
  2835. EXPECT_TRUE(success);
  2836. delete i;
  2837. });
  2838. })
  2839. .Get("/streamed-chunked-with-trailer",
  2840. [&](const Request & /*req*/, Response &res) {
  2841. auto i = new int(0);
  2842. res.set_header("Trailer", "Dummy1, Dummy2");
  2843. res.set_chunked_content_provider(
  2844. "text/plain",
  2845. [i](size_t /*offset*/, DataSink &sink) {
  2846. switch (*i) {
  2847. case 0: sink.os << "123"; break;
  2848. case 1: sink.os << "456"; break;
  2849. case 2: sink.os << "789"; break;
  2850. case 3: {
  2851. sink.done_with_trailer(
  2852. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2853. } break;
  2854. }
  2855. (*i)++;
  2856. return true;
  2857. },
  2858. [i](bool success) {
  2859. EXPECT_TRUE(success);
  2860. delete i;
  2861. });
  2862. })
  2863. .Get("/streamed",
  2864. [&](const Request & /*req*/, Response &res) {
  2865. res.set_content_provider(
  2866. 6, "text/plain",
  2867. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2868. sink.os << (offset < 3 ? "a" : "b");
  2869. return true;
  2870. });
  2871. })
  2872. .Get("/streamed-with-range",
  2873. [&](const Request &req, Response &res) {
  2874. auto data = new std::string("abcdefg");
  2875. res.set_content_provider(
  2876. data->size(), "text/plain",
  2877. [data](size_t offset, size_t length, DataSink &sink) {
  2878. size_t DATA_CHUNK_SIZE = 4;
  2879. const auto &d = *data;
  2880. auto out_len =
  2881. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2882. auto ret =
  2883. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2884. EXPECT_TRUE(ret);
  2885. return true;
  2886. },
  2887. [data, &req](bool success) {
  2888. EXPECT_EQ(success, !req.has_param("error"));
  2889. delete data;
  2890. });
  2891. })
  2892. .Get("/streamed-cancel",
  2893. [&](const Request & /*req*/, Response &res) {
  2894. res.set_content_provider(
  2895. size_t(-1), "text/plain",
  2896. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2897. sink.os << "data_chunk";
  2898. return true;
  2899. });
  2900. })
  2901. .Get("/regex-with-delimiter",
  2902. [&](const Request &req, Response & /*res*/) {
  2903. ASSERT_TRUE(req.has_param("key"));
  2904. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2905. })
  2906. .Get("/with-range",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_content("abcdefg", "text/plain");
  2909. })
  2910. .Get("/test-start-time",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_NE(req.start_time_,
  2913. std::chrono::steady_clock::time_point::min());
  2914. })
  2915. .Get("/with-range-customized-response",
  2916. [&](const Request & /*req*/, Response &res) {
  2917. res.status = StatusCode::BadRequest_400;
  2918. res.set_content(JSON_DATA, "application/json");
  2919. })
  2920. .Post("/chunked",
  2921. [&](const Request &req, Response & /*res*/) {
  2922. EXPECT_EQ(req.body, "dechunked post body");
  2923. })
  2924. .Post("/large-chunked",
  2925. [&](const Request &req, Response & /*res*/) {
  2926. std::string expected(6 * 30 * 1024u, 'a');
  2927. EXPECT_EQ(req.body, expected);
  2928. })
  2929. .Post("/multipart",
  2930. [&](const Request &req, Response & /*res*/) {
  2931. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2932. req.form.get_field_count("text2") +
  2933. req.form.get_field_count("file3") +
  2934. req.form.get_field_count("file4"));
  2935. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2936. req.form.get_file_count("file2"));
  2937. ASSERT_TRUE(!req.form.has_file("???"));
  2938. ASSERT_TRUE(!req.form.has_field("???"));
  2939. ASSERT_TRUE(req.body.empty());
  2940. {
  2941. const auto &text = req.form.get_field("text1");
  2942. EXPECT_EQ("text default", text);
  2943. }
  2944. {
  2945. const auto &text = req.form.get_field("text2");
  2946. EXPECT_EQ("aωb", text);
  2947. }
  2948. {
  2949. const auto &file = req.form.get_file("file1");
  2950. EXPECT_EQ("hello.txt", file.filename);
  2951. EXPECT_EQ("text/plain", file.content_type);
  2952. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2953. }
  2954. {
  2955. const auto &file = req.form.get_file("file2");
  2956. EXPECT_EQ("world.json", file.filename);
  2957. EXPECT_EQ("application/json", file.content_type);
  2958. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2959. }
  2960. {
  2961. const auto &text = req.form.get_field("file3");
  2962. EXPECT_EQ(0u, text.size());
  2963. }
  2964. {
  2965. const auto &text = req.form.get_field("file4");
  2966. EXPECT_EQ(0u, text.size());
  2967. }
  2968. })
  2969. .Post("/multipart/multi_file_values",
  2970. [&](const Request &req, Response & /*res*/) {
  2971. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2972. req.form.get_field_count("multi_text1"));
  2973. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2974. ASSERT_TRUE(!req.form.has_file("???"));
  2975. ASSERT_TRUE(!req.form.has_field("???"));
  2976. ASSERT_TRUE(req.body.empty());
  2977. {
  2978. const auto &text = req.form.get_field("text");
  2979. EXPECT_EQ("default text", text);
  2980. }
  2981. {
  2982. const auto &text1_values = req.form.get_fields("multi_text1");
  2983. EXPECT_EQ(2u, text1_values.size());
  2984. EXPECT_EQ("aaaaa", text1_values[0]);
  2985. EXPECT_EQ("bbbbb", text1_values[1]);
  2986. }
  2987. {
  2988. const auto &file1_values = req.form.get_files("multi_file1");
  2989. EXPECT_EQ(2u, file1_values.size());
  2990. auto file1 = file1_values[0];
  2991. EXPECT_EQ(file1.filename, "hello.txt");
  2992. EXPECT_EQ(file1.content_type, "text/plain");
  2993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2994. auto file2 = file1_values[1];
  2995. EXPECT_EQ(file2.filename, "world.json");
  2996. EXPECT_EQ(file2.content_type, "application/json");
  2997. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2998. }
  2999. })
  3000. .Post("/empty",
  3001. [&](const Request &req, Response &res) {
  3002. EXPECT_EQ(req.body, "");
  3003. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3004. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3005. res.set_content("empty", "text/plain");
  3006. })
  3007. .Post("/empty-no-content-type",
  3008. [&](const Request &req, Response &res) {
  3009. EXPECT_EQ(req.body, "");
  3010. EXPECT_FALSE(req.has_header("Content-Type"));
  3011. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3012. res.set_content("empty-no-content-type", "text/plain");
  3013. })
  3014. .Post("/path-only",
  3015. [&](const Request &req, Response &res) {
  3016. EXPECT_EQ(req.body, "");
  3017. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3018. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3019. res.set_content("path-only", "text/plain");
  3020. })
  3021. .Post("/path-headers-only",
  3022. [&](const Request &req, Response &res) {
  3023. EXPECT_EQ(req.body, "");
  3024. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3025. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3026. EXPECT_EQ("world", req.get_header_value("hello"));
  3027. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3028. res.set_content("path-headers-only", "text/plain");
  3029. })
  3030. .Post("/post-large",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(req.body, LARGE_DATA);
  3033. res.set_content(req.body, "text/plain");
  3034. })
  3035. .Post("/post-loopback",
  3036. [&](const Request &, Response &res,
  3037. ContentReader const &content_reader) {
  3038. std::string body;
  3039. content_reader([&](const char *data, size_t data_length) {
  3040. body.append(data, data_length);
  3041. return true;
  3042. });
  3043. res.set_content(body, "text/plain");
  3044. })
  3045. .Put("/put-loopback",
  3046. [&](const Request &, Response &res,
  3047. ContentReader const &content_reader) {
  3048. std::string body;
  3049. content_reader([&](const char *data, size_t data_length) {
  3050. body.append(data, data_length);
  3051. return true;
  3052. });
  3053. res.set_content(body, "text/plain");
  3054. })
  3055. .Patch("/patch-loopback",
  3056. [&](const Request &, Response &res,
  3057. ContentReader const &content_reader) {
  3058. std::string body;
  3059. content_reader([&](const char *data, size_t data_length) {
  3060. body.append(data, data_length);
  3061. return true;
  3062. });
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Put("/empty-no-content-type",
  3066. [&](const Request &req, Response &res) {
  3067. EXPECT_EQ(req.body, "");
  3068. EXPECT_FALSE(req.has_header("Content-Type"));
  3069. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3070. res.set_content("empty-no-content-type", "text/plain");
  3071. })
  3072. .Put("/put",
  3073. [&](const Request &req, Response &res) {
  3074. EXPECT_EQ(req.body, "PUT");
  3075. res.set_content(req.body, "text/plain");
  3076. })
  3077. .Put("/put-large",
  3078. [&](const Request &req, Response &res) {
  3079. EXPECT_EQ(req.body, LARGE_DATA);
  3080. res.set_content(req.body, "text/plain");
  3081. })
  3082. .Patch("/patch",
  3083. [&](const Request &req, Response &res) {
  3084. EXPECT_EQ(req.body, "PATCH");
  3085. res.set_content(req.body, "text/plain");
  3086. })
  3087. .Delete("/delete",
  3088. [&](const Request & /*req*/, Response &res) {
  3089. res.set_content("DELETE", "text/plain");
  3090. })
  3091. .Delete("/delete-body",
  3092. [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(req.body, "content");
  3094. res.set_content(req.body, "text/plain");
  3095. })
  3096. .Options(R"(\*)",
  3097. [&](const Request & /*req*/, Response &res) {
  3098. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3099. })
  3100. .Get("/request-target",
  3101. [&](const Request &req, Response & /*res*/) {
  3102. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3103. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3104. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3105. })
  3106. .Get("/long-query-value",
  3107. [&](const Request &req, Response & /*res*/) {
  3108. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3109. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3110. })
  3111. .Get("/too-long-query-value",
  3112. [&](const Request &req, Response & /*res*/) {
  3113. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3114. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3115. })
  3116. .Get("/array-param",
  3117. [&](const Request &req, Response & /*res*/) {
  3118. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3119. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3120. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3121. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3122. })
  3123. .Post("/validate-no-multiple-headers",
  3124. [&](const Request &req, Response & /*res*/) {
  3125. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3126. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3127. })
  3128. .Post("/content_receiver",
  3129. [&](const Request &req, Response &res,
  3130. const ContentReader &content_reader) {
  3131. if (req.is_multipart_form_data()) {
  3132. std::vector<FormData> items;
  3133. content_reader(
  3134. [&](const FormData &file) {
  3135. items.push_back(file);
  3136. return true;
  3137. },
  3138. [&](const char *data, size_t data_length) {
  3139. items.back().content.append(data, data_length);
  3140. return true;
  3141. });
  3142. EXPECT_EQ(5u, items.size());
  3143. {
  3144. const auto &file = get_file_value(items, "text1");
  3145. EXPECT_TRUE(file.filename.empty());
  3146. EXPECT_EQ("text default", file.content);
  3147. }
  3148. {
  3149. const auto &file = get_file_value(items, "text2");
  3150. EXPECT_TRUE(file.filename.empty());
  3151. EXPECT_EQ("aωb", file.content);
  3152. }
  3153. {
  3154. const auto &file = get_file_value(items, "file1");
  3155. EXPECT_EQ("hello.txt", file.filename);
  3156. EXPECT_EQ("text/plain", file.content_type);
  3157. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3158. }
  3159. {
  3160. const auto &file = get_file_value(items, "file2");
  3161. EXPECT_EQ("world.json", file.filename);
  3162. EXPECT_EQ("application/json", file.content_type);
  3163. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3164. }
  3165. {
  3166. const auto &file = get_file_value(items, "file3");
  3167. EXPECT_TRUE(file.filename.empty());
  3168. EXPECT_EQ("application/octet-stream", file.content_type);
  3169. EXPECT_EQ(0u, file.content.size());
  3170. }
  3171. } else {
  3172. std::string body;
  3173. content_reader([&](const char *data, size_t data_length) {
  3174. EXPECT_EQ(7U, data_length);
  3175. body.append(data, data_length);
  3176. return true;
  3177. });
  3178. EXPECT_EQ(body, "content");
  3179. res.set_content(body, "text/plain");
  3180. }
  3181. })
  3182. .Put("/content_receiver",
  3183. [&](const Request & /*req*/, Response &res,
  3184. const ContentReader &content_reader) {
  3185. std::string body;
  3186. content_reader([&](const char *data, size_t data_length) {
  3187. body.append(data, data_length);
  3188. return true;
  3189. });
  3190. EXPECT_EQ(body, "content");
  3191. res.set_content(body, "text/plain");
  3192. })
  3193. .Patch("/content_receiver",
  3194. [&](const Request & /*req*/, Response &res,
  3195. const ContentReader &content_reader) {
  3196. std::string body;
  3197. content_reader([&](const char *data, size_t data_length) {
  3198. body.append(data, data_length);
  3199. return true;
  3200. });
  3201. EXPECT_EQ(body, "content");
  3202. res.set_content(body, "text/plain");
  3203. })
  3204. .Post("/query-string-and-body",
  3205. [&](const Request &req, Response & /*res*/) {
  3206. ASSERT_TRUE(req.has_param("key"));
  3207. EXPECT_EQ(req.get_param_value("key"), "value");
  3208. EXPECT_EQ(req.body, "content");
  3209. })
  3210. .Get("/last-request",
  3211. [&](const Request &req, Response & /*res*/) {
  3212. EXPECT_EQ("close", req.get_header_value("Connection"));
  3213. })
  3214. .Get(R"(/redirect/(\d+))",
  3215. [&](const Request &req, Response &res) {
  3216. auto num = std::stoi(req.matches[1]) + 1;
  3217. std::string url = "/redirect/" + std::to_string(num);
  3218. res.set_redirect(url);
  3219. })
  3220. .Post("/binary",
  3221. [&](const Request &req, Response &res) {
  3222. EXPECT_EQ(4U, req.body.size());
  3223. EXPECT_EQ("application/octet-stream",
  3224. req.get_header_value("Content-Type"));
  3225. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3226. res.set_content(req.body, "application/octet-stream");
  3227. })
  3228. .Put("/binary",
  3229. [&](const Request &req, Response &res) {
  3230. EXPECT_EQ(4U, req.body.size());
  3231. EXPECT_EQ("application/octet-stream",
  3232. req.get_header_value("Content-Type"));
  3233. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3234. res.set_content(req.body, "application/octet-stream");
  3235. })
  3236. .Patch("/binary",
  3237. [&](const Request &req, Response &res) {
  3238. EXPECT_EQ(4U, req.body.size());
  3239. EXPECT_EQ("application/octet-stream",
  3240. req.get_header_value("Content-Type"));
  3241. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3242. res.set_content(req.body, "application/octet-stream");
  3243. })
  3244. .Delete("/binary",
  3245. [&](const Request &req, Response &res) {
  3246. EXPECT_EQ(4U, req.body.size());
  3247. EXPECT_EQ("application/octet-stream",
  3248. req.get_header_value("Content-Type"));
  3249. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3250. res.set_content(req.body, "application/octet-stream");
  3251. })
  3252. .Get("/issue1772",
  3253. [&](const Request & /*req*/, Response &res) {
  3254. res.status = 401;
  3255. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3256. })
  3257. .Delete("/issue609",
  3258. [](const httplib::Request &, httplib::Response &res,
  3259. const httplib::ContentReader &) {
  3260. res.set_content("ok", "text/plain");
  3261. })
  3262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3263. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3264. .Get("/compress",
  3265. [&](const Request & /*req*/, Response &res) {
  3266. res.set_content(
  3267. "12345678901234567890123456789012345678901234567890123456789"
  3268. "01234567890123456789012345678901234567890",
  3269. "text/plain");
  3270. })
  3271. .Get("/compress-with-charset",
  3272. [&](const Request & /*req*/, Response &res) {
  3273. res.set_content(
  3274. "12345678901234567890123456789012345678901234567890123456789"
  3275. "01234567890123456789012345678901234567890",
  3276. "application/json; charset=utf-8");
  3277. })
  3278. .Get("/nocompress",
  3279. [&](const Request & /*req*/, Response &res) {
  3280. res.set_content(
  3281. "12345678901234567890123456789012345678901234567890123456789"
  3282. "01234567890123456789012345678901234567890",
  3283. "application/octet-stream");
  3284. })
  3285. .Post("/compress-multipart",
  3286. [&](const Request &req, Response & /*res*/) {
  3287. EXPECT_EQ(2u, req.form.fields.size());
  3288. ASSERT_TRUE(!req.form.has_field("???"));
  3289. {
  3290. const auto &text = req.form.get_field("key1");
  3291. EXPECT_EQ("test", text);
  3292. }
  3293. {
  3294. const auto &text = req.form.get_field("key2");
  3295. EXPECT_EQ("--abcdefg123", text);
  3296. }
  3297. })
  3298. #endif
  3299. ;
  3300. persons_["john"] = "programmer";
  3301. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3302. svr_.wait_until_ready();
  3303. }
  3304. virtual void TearDown() {
  3305. svr_.stop();
  3306. if (!request_threads_.empty()) {
  3307. std::this_thread::sleep_for(std::chrono::seconds(1));
  3308. for (auto &t : request_threads_) {
  3309. t.join();
  3310. }
  3311. }
  3312. t_.join();
  3313. }
  3314. map<string, string> persons_;
  3315. #ifdef CPPHTTPLIB_SSL_ENABLED
  3316. SSLClient cli_;
  3317. SSLServer svr_;
  3318. #else
  3319. Client cli_;
  3320. Server svr_;
  3321. #endif
  3322. thread t_;
  3323. std::vector<thread> request_threads_;
  3324. };
  3325. TEST_F(ServerTest, GetMethod200) {
  3326. auto res = cli_.Get("/hi");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ("HTTP/1.1", res->version);
  3329. EXPECT_EQ(StatusCode::OK_200, res->status);
  3330. EXPECT_EQ("OK", res->reason);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3333. EXPECT_EQ("Hello World!", res->body);
  3334. }
  3335. TEST_F(ServerTest, GetEmptyFile) {
  3336. auto res = cli_.Get("/empty_file");
  3337. ASSERT_TRUE(res);
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3340. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3341. EXPECT_EQ("", res->body);
  3342. }
  3343. TEST_F(ServerTest, GetFileContent) {
  3344. auto res = cli_.Get("/file_content");
  3345. ASSERT_TRUE(res);
  3346. EXPECT_EQ(StatusCode::OK_200, res->status);
  3347. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3348. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3349. EXPECT_EQ("test.html", res->body);
  3350. }
  3351. TEST_F(ServerTest, GetFileContentWithRange) {
  3352. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3353. ASSERT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3355. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3356. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3357. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3358. EXPECT_EQ("est", res->body);
  3359. }
  3360. TEST_F(ServerTest, GetFileContentWithContentType) {
  3361. auto res = cli_.Get("/file_content_with_content_type");
  3362. ASSERT_TRUE(res);
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3365. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3366. EXPECT_EQ("file\n", res->body);
  3367. }
  3368. TEST_F(ServerTest, GetInvalidFileContent) {
  3369. auto res = cli_.Get("/invalid_file_content");
  3370. ASSERT_TRUE(res);
  3371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3372. }
  3373. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3374. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3375. ASSERT_TRUE(res);
  3376. EXPECT_EQ("HTTP/1.1", res->version);
  3377. EXPECT_EQ(StatusCode::OK_200, res->status);
  3378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3380. EXPECT_EQ("Hello World!", res->body);
  3381. }
  3382. TEST_F(ServerTest, GetMethod302) {
  3383. auto res = cli_.Get("/");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(StatusCode::Found_302, res->status);
  3386. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3387. }
  3388. TEST_F(ServerTest, GetMethod302Redirect) {
  3389. cli_.set_follow_location(true);
  3390. auto res = cli_.Get("/");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::OK_200, res->status);
  3393. EXPECT_EQ("Hello World!", res->body);
  3394. EXPECT_EQ("/hi", res->location);
  3395. }
  3396. TEST_F(ServerTest, GetMethod404) {
  3397. auto res = cli_.Get("/invalid");
  3398. ASSERT_TRUE(res);
  3399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3400. }
  3401. TEST_F(ServerTest, HeadMethod200) {
  3402. auto res = cli_.Head("/hi");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. EXPECT_TRUE(res->body.empty());
  3407. }
  3408. TEST_F(ServerTest, HeadMethod200Static) {
  3409. auto res = cli_.Head("/mount/dir/index.html");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(StatusCode::OK_200, res->status);
  3412. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3413. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3414. EXPECT_TRUE(res->body.empty());
  3415. }
  3416. TEST_F(ServerTest, HeadMethod404) {
  3417. auto res = cli_.Head("/invalid");
  3418. ASSERT_TRUE(res);
  3419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3420. EXPECT_TRUE(res->body.empty());
  3421. }
  3422. TEST_F(ServerTest, GetMethodPersonJohn) {
  3423. auto res = cli_.Get("/person/john");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3427. EXPECT_EQ("programmer", res->body);
  3428. }
  3429. TEST_F(ServerTest, PostMethod1) {
  3430. auto res = cli_.Get("/person/john1");
  3431. ASSERT_TRUE(res);
  3432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3433. res = cli_.Post("/person", "name=john1&note=coder",
  3434. "application/x-www-form-urlencoded");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::OK_200, res->status);
  3437. res = cli_.Get("/person/john1");
  3438. ASSERT_TRUE(res);
  3439. ASSERT_EQ(StatusCode::OK_200, res->status);
  3440. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3441. ASSERT_EQ("coder", res->body);
  3442. }
  3443. TEST_F(ServerTest, PostMethod2) {
  3444. auto res = cli_.Get("/person/john2");
  3445. ASSERT_TRUE(res);
  3446. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3447. Params params;
  3448. params.emplace("name", "john2");
  3449. params.emplace("note", "coder");
  3450. res = cli_.Post("/person", params);
  3451. ASSERT_TRUE(res);
  3452. ASSERT_EQ(StatusCode::OK_200, res->status);
  3453. res = cli_.Get("/person/john2");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3457. ASSERT_EQ("coder", res->body);
  3458. }
  3459. TEST_F(ServerTest, PutMethod3) {
  3460. auto res = cli_.Get("/person/john3");
  3461. ASSERT_TRUE(res);
  3462. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3463. Params params;
  3464. params.emplace("name", "john3");
  3465. params.emplace("note", "coder");
  3466. res = cli_.Put("/person", params);
  3467. ASSERT_TRUE(res);
  3468. ASSERT_EQ(StatusCode::OK_200, res->status);
  3469. res = cli_.Get("/person/john3");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3473. ASSERT_EQ("coder", res->body);
  3474. }
  3475. TEST_F(ServerTest, DeleteMethod1) {
  3476. auto res = cli_.Get("/person/john4");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3479. Params params;
  3480. params.emplace("name", "john4");
  3481. params.emplace("note", "coder");
  3482. res = cli_.Post("/person", params);
  3483. ASSERT_TRUE(res);
  3484. ASSERT_EQ(StatusCode::OK_200, res->status);
  3485. res = cli_.Get("/person/john4");
  3486. ASSERT_TRUE(res);
  3487. ASSERT_EQ(StatusCode::OK_200, res->status);
  3488. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3489. ASSERT_EQ("coder", res->body);
  3490. Params delete_params;
  3491. delete_params.emplace("name", "john4");
  3492. res = cli_.Delete("/person", delete_params);
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ("DELETED", res->body);
  3496. res = cli_.Get("/person/john4");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. }
  3500. TEST_F(ServerTest, DeleteMethod2) {
  3501. auto res = cli_.Get("/person/john5");
  3502. ASSERT_TRUE(res);
  3503. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3504. Params params;
  3505. params.emplace("name", "john5");
  3506. params.emplace("note", "developer");
  3507. res = cli_.Post("/person", params);
  3508. ASSERT_TRUE(res);
  3509. ASSERT_EQ(StatusCode::OK_200, res->status);
  3510. res = cli_.Get("/person/john5");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::OK_200, res->status);
  3513. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3514. ASSERT_EQ("developer", res->body);
  3515. Params delete_params;
  3516. delete_params.emplace("name", "john5");
  3517. Headers headers;
  3518. headers.emplace("Custom-Header", "test-value");
  3519. res = cli_.Delete("/person", headers, delete_params);
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("DELETED", res->body);
  3523. res = cli_.Get("/person/john5");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3526. }
  3527. TEST_F(ServerTest, DeleteMethod3) {
  3528. auto res = cli_.Get("/person/john6");
  3529. ASSERT_TRUE(res);
  3530. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3531. Params params;
  3532. params.emplace("name", "john6");
  3533. params.emplace("note", "tester");
  3534. res = cli_.Post("/person", params);
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. res = cli_.Get("/person/john6");
  3538. ASSERT_TRUE(res);
  3539. ASSERT_EQ(StatusCode::OK_200, res->status);
  3540. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3541. ASSERT_EQ("tester", res->body);
  3542. Params delete_params;
  3543. delete_params.emplace("name", "john6");
  3544. Headers headers;
  3545. headers.emplace("Custom-Header", "test-value");
  3546. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::OK_200, res->status);
  3549. ASSERT_EQ("DELETED", res->body);
  3550. res = cli_.Get("/person/john6");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3553. }
  3554. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3555. Params params;
  3556. params.emplace("json", JSON_DATA);
  3557. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ(JSON_DATA, res->body);
  3561. }
  3562. TEST_F(ServerTest, PostEmptyContent) {
  3563. auto res = cli_.Post("/empty", "", "text/plain");
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. ASSERT_EQ("empty", res->body);
  3567. }
  3568. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3569. auto res = cli_.Post("/empty-no-content-type");
  3570. ASSERT_TRUE(res);
  3571. ASSERT_EQ(StatusCode::OK_200, res->status);
  3572. ASSERT_EQ("empty-no-content-type", res->body);
  3573. }
  3574. TEST_F(ServerTest, PostPathOnly) {
  3575. auto res = cli_.Post("/path-only");
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ("path-only", res->body);
  3579. }
  3580. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3581. auto res = cli_.Post("/path-headers-only",
  3582. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. ASSERT_EQ("path-headers-only", res->body);
  3586. }
  3587. TEST_F(ServerTest, PostLarge) {
  3588. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3589. ASSERT_TRUE(res);
  3590. ASSERT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ(LARGE_DATA, res->body);
  3592. }
  3593. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3594. auto res = cli_.Put("/empty-no-content-type");
  3595. ASSERT_TRUE(res);
  3596. ASSERT_EQ(StatusCode::OK_200, res->status);
  3597. ASSERT_EQ("empty-no-content-type", res->body);
  3598. }
  3599. TEST_F(ServerTest, GetMethodDir) {
  3600. auto res = cli_.Get("/dir/");
  3601. ASSERT_TRUE(res);
  3602. EXPECT_EQ(StatusCode::OK_200, res->status);
  3603. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3604. auto body = R"(<html>
  3605. <head>
  3606. </head>
  3607. <body>
  3608. <a href="/dir/test.html">Test</a>
  3609. <a href="/hi">hi</a>
  3610. </body>
  3611. </html>
  3612. )";
  3613. EXPECT_EQ(body, res->body);
  3614. }
  3615. TEST_F(ServerTest, GetMethodDirTest) {
  3616. auto res = cli_.Get("/dir/test.html");
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("test.html", res->body);
  3621. }
  3622. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3623. auto res = cli_.Get("/dir/../dir/test.html");
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(StatusCode::OK_200, res->status);
  3626. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3627. EXPECT_EQ("test.html", res->body);
  3628. }
  3629. TEST_F(ServerTest, GetMethodInvalidPath) {
  3630. auto res = cli_.Get("/dir/../test.html");
  3631. ASSERT_TRUE(res);
  3632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3633. }
  3634. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3635. auto res = cli_.Get("/../www/dir/test.html");
  3636. ASSERT_TRUE(res);
  3637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3638. }
  3639. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3640. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3643. }
  3644. TEST_F(ServerTest, GetMethodDirMountTest) {
  3645. auto res = cli_.Get("/mount/dir/test.html");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("test.html", res->body);
  3650. }
  3651. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3652. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3656. EXPECT_EQ("test.html", res->body);
  3657. }
  3658. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3659. auto res = cli_.Get("/mount/dir/../test.html");
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3662. }
  3663. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3664. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3667. }
  3668. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3669. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3672. }
  3673. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3674. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3677. }
  3678. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3679. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3682. }
  3683. TEST_F(ServerTest, PostMethod303) {
  3684. auto res = cli_.Post("/1", "body", "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3687. EXPECT_EQ("/2", res->get_header_value("Location"));
  3688. }
  3689. TEST_F(ServerTest, PostMethod303Redirect) {
  3690. cli_.set_follow_location(true);
  3691. auto res = cli_.Post("/1", "body", "text/plain");
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("redirected.", res->body);
  3695. EXPECT_EQ("/2", res->location);
  3696. }
  3697. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3698. auto res = cli_.Get("/dir/test.abcde");
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3702. EXPECT_EQ("abcde", res->body);
  3703. }
  3704. TEST_F(ServerTest, StaticFileRange) {
  3705. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3706. ASSERT_TRUE(res);
  3707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3708. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3709. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ(true, res->has_header("Content-Range"));
  3711. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3712. EXPECT_EQ(std::string("cd"), res->body);
  3713. }
  3714. TEST_F(ServerTest, StaticFileRanges) {
  3715. auto res =
  3716. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3719. EXPECT_TRUE(
  3720. res->get_header_value("Content-Type")
  3721. .find(
  3722. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3723. 0);
  3724. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3725. }
  3726. TEST_F(ServerTest, StaticFileRangeHead) {
  3727. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3730. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3731. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3732. EXPECT_EQ(true, res->has_header("Content-Range"));
  3733. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3734. }
  3735. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3736. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3740. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3741. EXPECT_EQ(true, res->has_header("Content-Range"));
  3742. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3743. res->get_header_value("Content-Range"));
  3744. EXPECT_EQ("LAST\n", res->body);
  3745. }
  3746. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3747. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3751. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3752. EXPECT_EQ(true, res->has_header("Content-Range"));
  3753. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3754. }
  3755. TEST_F(ServerTest, StaticFileBigFile) {
  3756. auto res = cli_.Get("/dir/1MB.txt");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3761. }
  3762. TEST_F(ServerTest, InvalidBaseDirMount) {
  3763. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3764. }
  3765. TEST_F(ServerTest, Binary) {
  3766. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3767. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3768. "application/octet-stream");
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ(4U, res->body.size());
  3772. res = cli_.Put("/binary", binary.data(), binary.size(),
  3773. "application/octet-stream");
  3774. ASSERT_TRUE(res);
  3775. ASSERT_EQ(StatusCode::OK_200, res->status);
  3776. ASSERT_EQ(4U, res->body.size());
  3777. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3778. "application/octet-stream");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(StatusCode::OK_200, res->status);
  3781. ASSERT_EQ(4U, res->body.size());
  3782. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3783. "application/octet-stream");
  3784. ASSERT_TRUE(res);
  3785. ASSERT_EQ(StatusCode::OK_200, res->status);
  3786. ASSERT_EQ(4U, res->body.size());
  3787. }
  3788. TEST_F(ServerTest, BinaryString) {
  3789. auto binary = std::string("\x00\x01\x02\x03", 4);
  3790. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3791. ASSERT_TRUE(res);
  3792. ASSERT_EQ(StatusCode::OK_200, res->status);
  3793. ASSERT_EQ(4U, res->body.size());
  3794. res = cli_.Put("/binary", binary, "application/octet-stream");
  3795. ASSERT_TRUE(res);
  3796. ASSERT_EQ(StatusCode::OK_200, res->status);
  3797. ASSERT_EQ(4U, res->body.size());
  3798. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3799. ASSERT_TRUE(res);
  3800. ASSERT_EQ(StatusCode::OK_200, res->status);
  3801. ASSERT_EQ(4U, res->body.size());
  3802. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3803. ASSERT_TRUE(res);
  3804. ASSERT_EQ(StatusCode::OK_200, res->status);
  3805. ASSERT_EQ(4U, res->body.size());
  3806. }
  3807. TEST_F(ServerTest, EmptyRequest) {
  3808. auto res = cli_.Get("");
  3809. ASSERT_TRUE(!res);
  3810. EXPECT_EQ(Error::Connection, res.error());
  3811. }
  3812. TEST_F(ServerTest, LongRequest) {
  3813. std::string request;
  3814. for (size_t i = 0; i < 545; i++) {
  3815. request += "/TooLongRequest";
  3816. }
  3817. request += "OK";
  3818. auto res = cli_.Get(request.c_str());
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, TooLongRequest) {
  3823. std::string request;
  3824. for (size_t i = 0; i < 546; i++) {
  3825. request += "/TooLongRequest";
  3826. }
  3827. request += "_NG";
  3828. auto start = std::chrono::high_resolution_clock::now();
  3829. cli_.set_keep_alive(true);
  3830. auto res = cli_.Get(request.c_str());
  3831. auto end = std::chrono::high_resolution_clock::now();
  3832. auto elapsed =
  3833. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3834. .count();
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3837. EXPECT_LE(elapsed, 1000);
  3838. EXPECT_EQ("close", res->get_header_value("Connection"));
  3839. EXPECT_FALSE(cli_.is_socket_open());
  3840. }
  3841. TEST_F(ServerTest, AlmostTooLongRequest) {
  3842. // test for #2046 - URI length check shouldn't include other content on req
  3843. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3844. // leading /, space, HTTP/1.1)
  3845. std::string request =
  3846. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3847. auto res = cli_.Get(request.c_str());
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3850. }
  3851. TEST_F(ServerTest, LongHeader) {
  3852. Request req;
  3853. req.method = "GET";
  3854. req.path = "/hi";
  3855. std::string host_and_port;
  3856. host_and_port += HOST;
  3857. host_and_port += ":";
  3858. host_and_port += std::to_string(PORT);
  3859. req.headers.emplace("Host", host_and_port.c_str());
  3860. req.headers.emplace("Accept", "*/*");
  3861. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3862. req.headers.emplace(
  3863. "Header-Name",
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3892. "@@@@@@@@@@@@@@@@");
  3893. auto res = std::make_shared<Response>();
  3894. auto error = Error::Success;
  3895. auto ret = cli_.send(req, *res, error);
  3896. ASSERT_TRUE(ret);
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. }
  3899. TEST_F(ServerTest, LongQueryValue) {
  3900. auto start = std::chrono::high_resolution_clock::now();
  3901. cli_.set_keep_alive(true);
  3902. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3903. auto end = std::chrono::high_resolution_clock::now();
  3904. auto elapsed =
  3905. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3906. .count();
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3909. EXPECT_LE(elapsed, 1000);
  3910. EXPECT_EQ("close", res->get_header_value("Connection"));
  3911. EXPECT_FALSE(cli_.is_socket_open());
  3912. }
  3913. TEST_F(ServerTest, TooLongQueryValue) {
  3914. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3915. ASSERT_FALSE(res);
  3916. EXPECT_EQ(Error::Read, res.error());
  3917. }
  3918. TEST_F(ServerTest, TooLongHeader) {
  3919. Request req;
  3920. req.method = "GET";
  3921. req.path = "/hi";
  3922. std::string host_and_port;
  3923. host_and_port += HOST;
  3924. host_and_port += ":";
  3925. host_and_port += std::to_string(PORT);
  3926. req.headers.emplace("Host", host_and_port.c_str());
  3927. req.headers.emplace("Accept", "*/*");
  3928. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3929. req.headers.emplace(
  3930. "Header-Name",
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3959. "@@@@@@@@@@@@@@@@@");
  3960. auto res = std::make_shared<Response>();
  3961. auto error = Error::Success;
  3962. auto ret = cli_.send(req, *res, error);
  3963. ASSERT_TRUE(ret);
  3964. EXPECT_EQ(StatusCode::OK_200, res->status);
  3965. }
  3966. TEST_F(ServerTest, HeaderCountAtLimit) {
  3967. // Test with headers just under the 100 limit
  3968. httplib::Headers headers;
  3969. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3970. // This should keep us just under the 100 header limit
  3971. for (int i = 0; i < 95; i++) {
  3972. std::string name = "X-Test-Header-" + std::to_string(i);
  3973. std::string value = "value" + std::to_string(i);
  3974. headers.emplace(name, value);
  3975. }
  3976. // This should work fine as we're under the limit
  3977. auto res = cli_.Get("/hi", headers);
  3978. EXPECT_TRUE(res);
  3979. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3980. }
  3981. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3982. // Test with many headers to exceed the 100 limit
  3983. httplib::Headers headers;
  3984. // Add 150 headers to definitely exceed the 100 limit
  3985. for (int i = 0; i < 150; i++) {
  3986. std::string name = "X-Test-Header-" + std::to_string(i);
  3987. std::string value = "value" + std::to_string(i);
  3988. headers.emplace(name, value);
  3989. }
  3990. // This should fail due to exceeding header count limit
  3991. cli_.set_keep_alive(true);
  3992. auto res = cli_.Get("/hi", headers);
  3993. // The server should respond with 400 Bad Request
  3994. ASSERT_TRUE(res);
  3995. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3996. EXPECT_EQ("close", res->get_header_value("Connection"));
  3997. EXPECT_FALSE(cli_.is_socket_open());
  3998. }
  3999. TEST_F(ServerTest, PercentEncoding) {
  4000. auto res = cli_.Get("/e%6edwith%");
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::OK_200, res->status);
  4003. }
  4004. TEST_F(ServerTest, PercentEncodingUnicode) {
  4005. auto res = cli_.Get("/e%u006edwith%");
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::OK_200, res->status);
  4008. }
  4009. TEST_F(ServerTest, InvalidPercentEncoding) {
  4010. auto res = cli_.Get("/%endwith%");
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4013. }
  4014. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4015. auto res = cli_.Get("/%uendwith%");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4018. }
  4019. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4020. auto res = cli_.Get("/hello?aaa=bbb%");
  4021. ASSERT_TRUE(res);
  4022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4023. }
  4024. TEST_F(ServerTest, PlusSignEncoding) {
  4025. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::OK_200, res->status);
  4028. EXPECT_EQ("a +b", res->body);
  4029. }
  4030. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4031. // This test simulates a potential DoS attack using many headers
  4032. // to verify our security fix prevents memory exhaustion
  4033. httplib::Headers attack_headers;
  4034. // Attempt to add many headers like an attacker would (200 headers to far
  4035. // exceed limit)
  4036. for (int i = 0; i < 200; i++) {
  4037. std::string name = "X-Attack-Header-" + std::to_string(i);
  4038. std::string value = "attack_payload_" + std::to_string(i);
  4039. attack_headers.emplace(name, value);
  4040. }
  4041. // Try to POST with excessive headers
  4042. cli_.set_keep_alive(true);
  4043. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4044. // Should either fail or return 400 Bad Request due to security limit
  4045. if (res) {
  4046. // If we get a response, it should be 400 Bad Request
  4047. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4048. EXPECT_EQ("close", res->get_header_value("Connection"));
  4049. }
  4050. EXPECT_FALSE(cli_.is_socket_open());
  4051. }
  4052. TEST_F(ServerTest, MultipartFormData) {
  4053. UploadFormDataItems items = {
  4054. {"text1", "text default", "", ""},
  4055. {"text2", "aωb", "", ""},
  4056. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4057. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4058. {"file3", "", "", "application/octet-stream"},
  4059. {"file4", "", "", " application/json tmp-string "}};
  4060. auto res = cli_.Post("/multipart", items);
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::OK_200, res->status);
  4063. }
  4064. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4065. UploadFormDataItems items = {
  4066. {"text", "default text", "", ""},
  4067. {"multi_text1", "aaaaa", "", ""},
  4068. {"multi_text1", "bbbbb", "", ""},
  4069. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4070. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4071. "application/json"},
  4072. };
  4073. auto res = cli_.Post("/multipart/multi_file_values", items);
  4074. ASSERT_TRUE(res);
  4075. EXPECT_EQ(StatusCode::OK_200, res->status);
  4076. }
  4077. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4078. auto res = cli_.Get("/hi");
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4082. EXPECT_EQ("Hello World!", res->body);
  4083. }
  4084. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4085. Request req;
  4086. req.method = "POST";
  4087. req.path = "/chunked";
  4088. std::string host_and_port;
  4089. host_and_port += HOST;
  4090. host_and_port += ":";
  4091. host_and_port += std::to_string(PORT);
  4092. req.headers.emplace("Host", host_and_port.c_str());
  4093. req.headers.emplace("Accept", "*/*");
  4094. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4095. req.headers.emplace("Content-Type", "text/plain");
  4096. req.headers.emplace("Content-Length", "0");
  4097. req.headers.emplace(
  4098. "Transfer-Encoding",
  4099. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4100. // Client does not chunk, so make a chunked body manually.
  4101. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4102. auto res = std::make_shared<Response>();
  4103. auto error = Error::Success;
  4104. auto ret = cli_.send(req, *res, error);
  4105. ASSERT_TRUE(ret);
  4106. EXPECT_EQ(StatusCode::OK_200, res->status);
  4107. }
  4108. TEST_F(ServerTest, GetStreamed2) {
  4109. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4112. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4113. EXPECT_EQ(true, res->has_header("Content-Range"));
  4114. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4115. EXPECT_EQ(std::string("ab"), res->body);
  4116. }
  4117. TEST_F(ServerTest, GetStreamed) {
  4118. auto res = cli_.Get("/streamed");
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::OK_200, res->status);
  4121. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4122. EXPECT_EQ(std::string("aaabbb"), res->body);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithRange1) {
  4125. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4126. ASSERT_TRUE(res);
  4127. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4128. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4129. EXPECT_EQ(true, res->has_header("Content-Range"));
  4130. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4131. EXPECT_EQ(std::string("def"), res->body);
  4132. }
  4133. TEST_F(ServerTest, GetStreamedWithRange2) {
  4134. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4137. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ(true, res->has_header("Content-Range"));
  4139. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4140. EXPECT_EQ(std::string("bcdefg"), res->body);
  4141. }
  4142. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4143. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4146. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4147. EXPECT_EQ(true, res->has_header("Content-Range"));
  4148. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4149. EXPECT_EQ(std::string("efg"), res->body);
  4150. }
  4151. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4152. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ(false, res->has_header("Content-Range"));
  4157. EXPECT_EQ(0U, res->body.size());
  4158. }
  4159. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4160. auto res = cli_.Get("/streamed-with-range",
  4161. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4162. "92233720368547758079223372036854775807"}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4166. EXPECT_EQ(false, res->has_header("Content-Range"));
  4167. EXPECT_EQ(0U, res->body.size());
  4168. }
  4169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4170. auto res = cli_.Get(
  4171. "/with-range",
  4172. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4173. {"Accept-Encoding", ""}});
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4176. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ(true, res->has_header("Content-Range"));
  4178. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4179. EXPECT_EQ(std::string("abcdefg"), res->body);
  4180. }
  4181. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4182. auto res = cli_.Get("/with-range", {
  4183. {"Range", "bytes=0-"},
  4184. {"Accept-Encoding", ""},
  4185. });
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4188. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4189. EXPECT_EQ(true, res->has_header("Content-Range"));
  4190. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4191. EXPECT_EQ(std::string("abcdefg"), res->body);
  4192. }
  4193. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4194. auto res =
  4195. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4196. ASSERT_TRUE(res);
  4197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4198. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4199. EXPECT_EQ(false, res->has_header("Content-Range"));
  4200. EXPECT_EQ(267U, res->body.size());
  4201. // Check that both range contents are present
  4202. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4203. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4204. // Check that Content-Range headers are present for both ranges
  4205. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4206. std::string::npos);
  4207. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4208. std::string::npos);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4211. Ranges ranges;
  4212. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4213. ranges.emplace_back(0, -1);
  4214. }
  4215. auto res =
  4216. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4219. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4220. EXPECT_EQ(false, res->has_header("Content-Range"));
  4221. EXPECT_EQ(0U, res->body.size());
  4222. }
  4223. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4224. auto res =
  4225. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4228. EXPECT_EQ(5U, res->body.size());
  4229. // Check that overlapping ranges are coalesced into a single range
  4230. EXPECT_EQ("bcdef", res->body);
  4231. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4232. // Should be single range, not multipart
  4233. EXPECT_TRUE(res->has_header("Content-Range"));
  4234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4235. }
  4236. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4237. auto res =
  4238. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ(268U, res->body.size());
  4242. // Check that both range contents are present
  4243. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4244. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4245. // Check that Content-Range headers are present for both ranges
  4246. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4247. std::string::npos);
  4248. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4249. std::string::npos);
  4250. }
  4251. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4252. auto res =
  4253. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4256. EXPECT_EQ(269U, res->body.size());
  4257. // Check that both duplicate range contents are present
  4258. size_t first_abc = res->body.find("abc\r\n");
  4259. EXPECT_TRUE(first_abc != std::string::npos);
  4260. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4261. EXPECT_TRUE(second_abc != std::string::npos);
  4262. // Check that Content-Range headers are present for both ranges
  4263. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4264. EXPECT_TRUE(first_range != std::string::npos);
  4265. size_t second_range =
  4266. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4267. EXPECT_TRUE(second_range != std::string::npos);
  4268. }
  4269. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4270. auto res = cli_.Get("/streamed-with-range?error",
  4271. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4274. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4275. EXPECT_EQ(false, res->has_header("Content-Range"));
  4276. EXPECT_EQ(0U, res->body.size());
  4277. }
  4278. TEST_F(ServerTest, GetStreamedEndless) {
  4279. uint64_t offset = 0;
  4280. auto res = cli_.Get("/streamed-cancel",
  4281. [&](const char * /*data*/, uint64_t data_length) {
  4282. if (offset < 100) {
  4283. offset += data_length;
  4284. return true;
  4285. }
  4286. return false;
  4287. });
  4288. ASSERT_TRUE(!res);
  4289. EXPECT_EQ(Error::Canceled, res.error());
  4290. }
  4291. TEST_F(ServerTest, ClientStop) {
  4292. std::atomic_size_t count{4};
  4293. std::vector<std::thread> threads;
  4294. for (auto i = count.load(); i != 0; --i) {
  4295. threads.emplace_back([&]() {
  4296. auto res = cli_.Get("/streamed-cancel",
  4297. [&](const char *, uint64_t) { return true; });
  4298. --count;
  4299. ASSERT_TRUE(!res);
  4300. EXPECT_TRUE(res.error() == Error::Canceled ||
  4301. res.error() == Error::Read || res.error() == Error::Write);
  4302. });
  4303. }
  4304. std::this_thread::sleep_for(std::chrono::seconds(2));
  4305. while (count != 0) {
  4306. cli_.stop();
  4307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4308. }
  4309. for (auto &t : threads) {
  4310. t.join();
  4311. }
  4312. }
  4313. TEST_F(ServerTest, GetWithRange1) {
  4314. auto res = cli_.Get("/with-range", {
  4315. make_range_header({{3, 5}}),
  4316. {"Accept-Encoding", ""},
  4317. });
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4320. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4321. EXPECT_EQ(true, res->has_header("Content-Range"));
  4322. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4323. EXPECT_EQ(std::string("def"), res->body);
  4324. }
  4325. TEST_F(ServerTest, GetWithRange2) {
  4326. auto res = cli_.Get("/with-range", {
  4327. make_range_header({{1, -1}}),
  4328. {"Accept-Encoding", ""},
  4329. });
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4332. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4333. EXPECT_EQ(true, res->has_header("Content-Range"));
  4334. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4335. EXPECT_EQ(std::string("bcdefg"), res->body);
  4336. }
  4337. TEST_F(ServerTest, GetWithRange3) {
  4338. auto res = cli_.Get("/with-range", {
  4339. make_range_header({{0, 0}}),
  4340. {"Accept-Encoding", ""},
  4341. });
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4344. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4345. EXPECT_EQ(true, res->has_header("Content-Range"));
  4346. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4347. EXPECT_EQ(std::string("a"), res->body);
  4348. }
  4349. TEST_F(ServerTest, GetWithRange4) {
  4350. auto res = cli_.Get("/with-range", {
  4351. make_range_header({{-1, 2}}),
  4352. {"Accept-Encoding", ""},
  4353. });
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4356. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4357. EXPECT_EQ(true, res->has_header("Content-Range"));
  4358. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4359. EXPECT_EQ(std::string("fg"), res->body);
  4360. }
  4361. TEST_F(ServerTest, GetWithRange5) {
  4362. auto res = cli_.Get("/with-range", {
  4363. make_range_header({{0, 5}}),
  4364. {"Accept-Encoding", ""},
  4365. });
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4368. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4371. EXPECT_EQ(std::string("abcdef"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4374. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4377. }
  4378. TEST_F(ServerTest, GetWithRangeMultipart) {
  4379. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4382. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4383. EXPECT_EQ(false, res->has_header("Content-Range"));
  4384. EXPECT_EQ(267U, res->body.size());
  4385. }
  4386. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4387. auto res =
  4388. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4391. }
  4392. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4393. auto res = cli_.Get("/with-range-customized-response",
  4394. {{make_range_header({{1, 2}})}});
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4397. EXPECT_EQ(true, res->has_header("Content-Length"));
  4398. EXPECT_EQ(false, res->has_header("Content-Range"));
  4399. EXPECT_EQ(JSON_DATA, res->body);
  4400. }
  4401. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4402. auto res = cli_.Get("/with-range-customized-response",
  4403. {{make_range_header({{1, 2}, {4, 5}})}});
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4406. EXPECT_EQ(true, res->has_header("Content-Length"));
  4407. EXPECT_EQ(false, res->has_header("Content-Range"));
  4408. EXPECT_EQ(JSON_DATA, res->body);
  4409. }
  4410. TEST_F(ServerTest, Issue1772) {
  4411. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4414. }
  4415. TEST_F(ServerTest, Issue609) {
  4416. auto res = cli_.Delete("/issue609");
  4417. ASSERT_TRUE(res);
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. EXPECT_EQ(std::string("ok"), res->body);
  4420. }
  4421. TEST_F(ServerTest, GetStreamedChunked) {
  4422. auto res = cli_.Get("/streamed-chunked");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. EXPECT_EQ(std::string("123456789"), res->body);
  4426. }
  4427. TEST_F(ServerTest, GetStreamedChunked2) {
  4428. auto res = cli_.Get("/streamed-chunked2");
  4429. ASSERT_TRUE(res);
  4430. EXPECT_EQ(StatusCode::OK_200, res->status);
  4431. EXPECT_EQ(std::string("123456789"), res->body);
  4432. }
  4433. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4434. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. EXPECT_EQ(std::string("123456789"), res->body);
  4438. EXPECT_TRUE(res->has_header("Trailer"));
  4439. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4440. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4441. // Trailers are now stored separately from headers (security fix)
  4442. EXPECT_EQ(2U, res->trailers.size());
  4443. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4444. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4445. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4446. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4447. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4448. // Verify trailers are NOT in headers (security verification)
  4449. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4450. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4451. }
  4452. TEST_F(ServerTest, LargeChunkedPost) {
  4453. Request req;
  4454. req.method = "POST";
  4455. req.path = "/large-chunked";
  4456. std::string host_and_port;
  4457. host_and_port += HOST;
  4458. host_and_port += ":";
  4459. host_and_port += std::to_string(PORT);
  4460. req.headers.emplace("Host", host_and_port.c_str());
  4461. req.headers.emplace("Accept", "*/*");
  4462. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4463. req.headers.emplace("Content-Type", "text/plain");
  4464. req.headers.emplace("Content-Length", "0");
  4465. req.headers.emplace("Transfer-Encoding", "chunked");
  4466. std::string long_string(30 * 1024u, 'a');
  4467. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4468. // Attempt to make a large enough post to exceed OS buffers, to test that
  4469. // the server handles short reads if the full chunk data isn't available.
  4470. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4471. auto res = std::make_shared<Response>();
  4472. auto error = Error::Success;
  4473. auto ret = cli_.send(req, *res, error);
  4474. ASSERT_TRUE(ret);
  4475. EXPECT_EQ(StatusCode::OK_200, res->status);
  4476. }
  4477. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4478. auto res = cli_.Get("/remote_addr");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4482. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4483. }
  4484. TEST_F(ServerTest, GetMethodLocalAddr) {
  4485. auto res = cli_.Get("/local_addr");
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4489. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4490. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4491. }
  4492. TEST_F(ServerTest, HTTPResponseSplitting) {
  4493. auto res = cli_.Get("/http_response_splitting");
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. }
  4497. TEST_F(ServerTest, SlowRequest) {
  4498. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4499. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4500. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4501. }
  4502. #if 0
  4503. TEST_F(ServerTest, SlowPost) {
  4504. char buffer[64 * 1024];
  4505. memset(buffer, 0x42, sizeof(buffer));
  4506. auto res = cli_.Post(
  4507. "/slowpost", 64 * 1024 * 1024,
  4508. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4509. auto ret = sink.write(buffer, sizeof(buffer));
  4510. EXPECT_TRUE(ret);
  4511. return true;
  4512. },
  4513. "text/plain");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. }
  4517. TEST_F(ServerTest, SlowPostFail) {
  4518. char buffer[64 * 1024];
  4519. memset(buffer, 0x42, sizeof(buffer));
  4520. cli_.set_write_timeout(std::chrono::seconds(0));
  4521. auto res = cli_.Post(
  4522. "/slowpost", 64 * 1024 * 1024,
  4523. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4524. sink.write(buffer, sizeof(buffer));
  4525. return true;
  4526. },
  4527. "text/plain");
  4528. ASSERT_TRUE(!res);
  4529. EXPECT_EQ(Error::Write, res.error());
  4530. }
  4531. #endif
  4532. TEST_F(ServerTest, Put) {
  4533. auto res = cli_.Put("/put", "PUT", "text/plain");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("PUT", res->body);
  4537. }
  4538. TEST_F(ServerTest, PutWithContentProvider) {
  4539. auto res = cli_.Put(
  4540. "/put", 3,
  4541. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4542. sink.os << "PUT";
  4543. return true;
  4544. },
  4545. "text/plain");
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("PUT", res->body);
  4549. }
  4550. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4551. auto res = cli_.Post(
  4552. "/post", 42,
  4553. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4554. return false;
  4555. },
  4556. "text/plain");
  4557. ASSERT_TRUE(!res);
  4558. EXPECT_EQ(Error::Canceled, res.error());
  4559. }
  4560. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4561. auto res = cli_.Put(
  4562. "/put",
  4563. [](size_t /*offset*/, DataSink &sink) {
  4564. sink.os << "PUT";
  4565. sink.done();
  4566. return true;
  4567. },
  4568. "text/plain");
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("PUT", res->body);
  4572. }
  4573. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4574. auto res = cli_.Post(
  4575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PostLoopBack) {
  4581. std::string body;
  4582. auto res = cli_.Post(
  4583. "/post-loopback", 9,
  4584. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4585. EXPECT_EQ(9u, length);
  4586. sink.write("123", 3);
  4587. sink.write("456", 3);
  4588. sink.write("789", 3);
  4589. return true;
  4590. },
  4591. "text/plain",
  4592. [&body](const char *data, size_t data_length) {
  4593. body.append(data, data_length);
  4594. return true;
  4595. });
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ("123456789", body);
  4599. }
  4600. TEST_F(ServerTest, PutLoopBack) {
  4601. std::string body;
  4602. auto res = cli_.Put(
  4603. "/put-loopback", 9,
  4604. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4605. EXPECT_EQ(9u, length);
  4606. sink.write("123", 3);
  4607. sink.write("456", 3);
  4608. sink.write("789", 3);
  4609. return true;
  4610. },
  4611. "text/plain",
  4612. [&body](const char *data, size_t data_length) {
  4613. body.append(data, data_length);
  4614. return true;
  4615. });
  4616. ASSERT_TRUE(res);
  4617. EXPECT_EQ(StatusCode::OK_200, res->status);
  4618. EXPECT_EQ("123456789", body);
  4619. }
  4620. TEST_F(ServerTest, PatchLoopBack) {
  4621. std::string body;
  4622. auto res = cli_.Patch(
  4623. "/patch-loopback", 9,
  4624. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4625. EXPECT_EQ(9u, length);
  4626. sink.write("123", 3);
  4627. sink.write("456", 3);
  4628. sink.write("789", 3);
  4629. return true;
  4630. },
  4631. "text/plain",
  4632. [&body](const char *data, size_t data_length) {
  4633. body.append(data, data_length);
  4634. return true;
  4635. });
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("123456789", body);
  4639. }
  4640. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4641. std::string body;
  4642. auto res = cli_.Post(
  4643. "/post-loopback",
  4644. [](size_t /*offset*/, DataSink &sink) {
  4645. sink.write("123", 3);
  4646. sink.write("456", 3);
  4647. sink.write("789", 3);
  4648. sink.done();
  4649. return true;
  4650. },
  4651. "text/plain",
  4652. [&body](const char *data, size_t data_length) {
  4653. body.append(data, data_length);
  4654. return true;
  4655. });
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. EXPECT_EQ("123456789", body);
  4659. }
  4660. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4661. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4662. cli_.set_compress(true);
  4663. auto res = cli_.Put(
  4664. "/put", 3,
  4665. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4666. sink.os << "PUT";
  4667. return true;
  4668. },
  4669. "text/plain");
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("PUT", res->body);
  4673. }
  4674. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4675. cli_.set_compress(true);
  4676. auto res = cli_.Post(
  4677. "/post", 42,
  4678. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4679. return false;
  4680. },
  4681. "text/plain");
  4682. ASSERT_TRUE(!res);
  4683. EXPECT_EQ(Error::Canceled, res.error());
  4684. }
  4685. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4686. cli_.set_compress(true);
  4687. auto res = cli_.Put(
  4688. "/put",
  4689. [](size_t /*offset*/, DataSink &sink) {
  4690. sink.os << "PUT";
  4691. sink.done();
  4692. return true;
  4693. },
  4694. "text/plain");
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::OK_200, res->status);
  4697. EXPECT_EQ("PUT", res->body);
  4698. }
  4699. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4700. cli_.set_compress(true);
  4701. auto res = cli_.Post(
  4702. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4703. "text/plain");
  4704. ASSERT_TRUE(!res);
  4705. EXPECT_EQ(Error::Canceled, res.error());
  4706. }
  4707. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4708. cli_.set_compress(true);
  4709. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4710. ASSERT_TRUE(res);
  4711. EXPECT_EQ(StatusCode::OK_200, res->status);
  4712. EXPECT_EQ(LARGE_DATA, res->body);
  4713. }
  4714. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4715. #ifdef CPPHTTPLIB_SSL_ENABLED
  4716. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4717. Client cli(s.c_str());
  4718. cli.enable_server_certificate_verification(false);
  4719. #else
  4720. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4721. Client cli(s.c_str());
  4722. #endif
  4723. cli.set_compress(true);
  4724. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4725. ASSERT_TRUE(res);
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ(LARGE_DATA, res->body);
  4728. // The compressed size should be less than a 10th of the original. May vary
  4729. // depending on the zlib library.
  4730. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4731. static_cast<uint64_t>(10 * 1024 * 1024));
  4732. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4733. }
  4734. TEST_F(ServerTest, PutContentWithDeflate) {
  4735. cli_.set_compress(false);
  4736. Headers headers;
  4737. headers.emplace("Content-Encoding", "deflate");
  4738. // PUT in deflate format:
  4739. auto res = cli_.Put("/put", headers,
  4740. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("PUT", res->body);
  4744. }
  4745. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4746. Headers headers;
  4747. headers.emplace("Accept-Encoding", "gzip, deflate");
  4748. auto res = cli_.Get("/streamed-chunked", headers);
  4749. ASSERT_TRUE(res);
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ(std::string("123456789"), res->body);
  4752. }
  4753. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4754. Headers headers;
  4755. headers.emplace("Accept-Encoding", "gzip, deflate");
  4756. auto res = cli_.Get("/streamed-chunked2", headers);
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::OK_200, res->status);
  4759. EXPECT_EQ(std::string("123456789"), res->body);
  4760. }
  4761. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4762. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST(GzipDecompressor, ChunkedDecompression) {
  4767. std::string data;
  4768. for (size_t i = 0; i < 32 * 1024; ++i) {
  4769. data.push_back(static_cast<char>('a' + i % 26));
  4770. }
  4771. std::string compressed_data;
  4772. {
  4773. httplib::detail::gzip_compressor compressor;
  4774. bool result = compressor.compress(
  4775. data.data(), data.size(),
  4776. /*last=*/true,
  4777. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4778. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4779. compressed_data_size);
  4780. return true;
  4781. });
  4782. ASSERT_TRUE(result);
  4783. }
  4784. std::string decompressed_data;
  4785. {
  4786. httplib::detail::gzip_decompressor decompressor;
  4787. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4788. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4789. size_t chunk_size = 130;
  4790. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4791. chunk_begin += chunk_size) {
  4792. size_t current_chunk_size =
  4793. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4794. bool result = decompressor.decompress(
  4795. compressed_data.data() + chunk_begin, current_chunk_size,
  4796. [&](const char *decompressed_data_chunk,
  4797. size_t decompressed_data_chunk_size) {
  4798. decompressed_data.insert(decompressed_data.size(),
  4799. decompressed_data_chunk,
  4800. decompressed_data_chunk_size);
  4801. return true;
  4802. });
  4803. ASSERT_TRUE(result);
  4804. }
  4805. }
  4806. ASSERT_EQ(data, decompressed_data);
  4807. }
  4808. TEST(GzipDecompressor, DeflateDecompression) {
  4809. std::string original_text = "Raw deflate without gzip";
  4810. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4811. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4812. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4813. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4814. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4815. std::string decompressed_data;
  4816. {
  4817. httplib::detail::gzip_decompressor decompressor;
  4818. bool result = decompressor.decompress(
  4819. compressed_data.data(), compressed_data.size(),
  4820. [&](const char *decompressed_data_chunk,
  4821. size_t decompressed_data_chunk_size) {
  4822. decompressed_data.insert(decompressed_data.size(),
  4823. decompressed_data_chunk,
  4824. decompressed_data_chunk_size);
  4825. return true;
  4826. });
  4827. ASSERT_TRUE(result);
  4828. }
  4829. ASSERT_EQ(original_text, decompressed_data);
  4830. }
  4831. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4832. std::string original_text = "Raw deflate without gzip";
  4833. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4834. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4835. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4836. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4837. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4838. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4839. std::string decompressed_data;
  4840. {
  4841. httplib::detail::gzip_decompressor decompressor;
  4842. bool result = decompressor.decompress(
  4843. compressed_data.data(), compressed_data.size(),
  4844. [&](const char *decompressed_data_chunk,
  4845. size_t decompressed_data_chunk_size) {
  4846. decompressed_data.insert(decompressed_data.size(),
  4847. decompressed_data_chunk,
  4848. decompressed_data_chunk_size);
  4849. return true;
  4850. });
  4851. ASSERT_TRUE(result);
  4852. }
  4853. ASSERT_EQ(original_text, decompressed_data);
  4854. }
  4855. #ifdef _WIN32
  4856. TEST(GzipDecompressor, LargeRandomData) {
  4857. // prepare large random data that is difficult to be compressed and is
  4858. // expected to have large size even when compressed
  4859. std::random_device seed_gen;
  4860. std::mt19937 random(seed_gen());
  4861. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4862. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4863. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4864. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4865. // compress data over 4GiB
  4866. std::string compressed_data;
  4867. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4868. httplib::detail::gzip_compressor compressor;
  4869. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4870. data.size() * sizeof(std::uint32_t), true,
  4871. [&](const char *data, size_t size) {
  4872. compressed_data.insert(
  4873. compressed_data.size(), data, size);
  4874. return true;
  4875. });
  4876. ASSERT_TRUE(result);
  4877. // FIXME: compressed data size is expected to be greater than 4GiB,
  4878. // but there is no guarantee
  4879. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4880. // decompress data over 4GiB
  4881. std::string decompressed_data;
  4882. decompressed_data.reserve(data_size);
  4883. httplib::detail::gzip_decompressor decompressor;
  4884. result = decompressor.decompress(
  4885. compressed_data.data(), compressed_data.size(),
  4886. [&](const char *data, size_t size) {
  4887. decompressed_data.insert(decompressed_data.size(), data, size);
  4888. return true;
  4889. });
  4890. ASSERT_TRUE(result);
  4891. // compare
  4892. ASSERT_EQ(data_size, decompressed_data.size());
  4893. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4894. 0);
  4895. }
  4896. #endif
  4897. #endif
  4898. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4899. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4900. Headers headers;
  4901. headers.emplace("Accept-Encoding", "br");
  4902. auto res = cli_.Get("/streamed-chunked", headers);
  4903. ASSERT_TRUE(res);
  4904. EXPECT_EQ(StatusCode::OK_200, res->status);
  4905. EXPECT_EQ(std::string("123456789"), res->body);
  4906. }
  4907. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4908. Headers headers;
  4909. headers.emplace("Accept-Encoding", "br");
  4910. auto res = cli_.Get("/streamed-chunked2", headers);
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ(std::string("123456789"), res->body);
  4914. }
  4915. #endif
  4916. TEST_F(ServerTest, Patch) {
  4917. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4918. ASSERT_TRUE(res);
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ("PATCH", res->body);
  4921. }
  4922. TEST_F(ServerTest, Delete) {
  4923. auto res = cli_.Delete("/delete");
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::OK_200, res->status);
  4926. EXPECT_EQ("DELETE", res->body);
  4927. }
  4928. TEST_F(ServerTest, DeleteContentReceiver) {
  4929. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. EXPECT_EQ("content", res->body);
  4933. }
  4934. TEST_F(ServerTest, Options) {
  4935. auto res = cli_.Options("*");
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4939. EXPECT_TRUE(res->body.empty());
  4940. }
  4941. TEST_F(ServerTest, URL) {
  4942. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. }
  4946. TEST_F(ServerTest, ArrayParam) {
  4947. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. }
  4951. TEST_F(ServerTest, NoMultipleHeaders) {
  4952. Headers headers = {{"Content-Length", "5"}};
  4953. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4954. "text/plain");
  4955. ASSERT_TRUE(res);
  4956. EXPECT_EQ(StatusCode::OK_200, res->status);
  4957. }
  4958. TEST_F(ServerTest, PostContentReceiver) {
  4959. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4960. ASSERT_TRUE(res);
  4961. ASSERT_EQ(StatusCode::OK_200, res->status);
  4962. ASSERT_EQ("content", res->body);
  4963. }
  4964. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4965. UploadFormDataItems items = {
  4966. {"text1", "text default", "", ""},
  4967. {"text2", "aωb", "", ""},
  4968. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4969. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4970. {"file3", "", "", "application/octet-stream"},
  4971. };
  4972. auto res = cli_.Post("/content_receiver", items);
  4973. ASSERT_TRUE(res);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. }
  4976. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4977. UploadFormDataItems items = {
  4978. {"text1", "text default", "", ""},
  4979. {"text2", "aωb", "", ""},
  4980. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4981. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4982. {"file3", "", "", "application/octet-stream"},
  4983. };
  4984. auto boundary = std::string("+++++");
  4985. std::string body;
  4986. for (const auto &item : items) {
  4987. body += "--" + boundary + "\r\n";
  4988. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4989. if (!item.filename.empty()) {
  4990. body += "; filename=\"" + item.filename + "\"";
  4991. }
  4992. body += "\r\n";
  4993. if (!item.content_type.empty()) {
  4994. body += "Content-Type: " + item.content_type + "\r\n";
  4995. }
  4996. body += "\r\n";
  4997. body += item.content + "\r\n";
  4998. }
  4999. body += "--" + boundary + "--\r\n";
  5000. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5001. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5002. ASSERT_TRUE(res);
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. }
  5005. TEST_F(ServerTest, PostContentReceiverGzip) {
  5006. cli_.set_compress(true);
  5007. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5008. ASSERT_TRUE(res);
  5009. ASSERT_EQ(StatusCode::OK_200, res->status);
  5010. ASSERT_EQ("content", res->body);
  5011. }
  5012. TEST_F(ServerTest, PutContentReceiver) {
  5013. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5014. ASSERT_TRUE(res);
  5015. ASSERT_EQ(StatusCode::OK_200, res->status);
  5016. ASSERT_EQ("content", res->body);
  5017. }
  5018. TEST_F(ServerTest, PatchContentReceiver) {
  5019. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5020. ASSERT_TRUE(res);
  5021. ASSERT_EQ(StatusCode::OK_200, res->status);
  5022. ASSERT_EQ("content", res->body);
  5023. }
  5024. template <typename ClientType>
  5025. void TestWithHeadersAndContentReceiver(
  5026. ClientType &cli,
  5027. std::function<Result(ClientType &, const std::string &, const Headers &,
  5028. const std::string &, const std::string &,
  5029. ContentReceiver, DownloadProgress)>
  5030. request_func) {
  5031. Headers headers;
  5032. headers.emplace("X-Custom-Header", "test-value");
  5033. std::string received_body;
  5034. auto res = request_func(
  5035. cli, "/content_receiver", headers, "content", "application/json",
  5036. [&](const char *data, size_t data_length) {
  5037. received_body.append(data, data_length);
  5038. return true;
  5039. },
  5040. nullptr);
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. EXPECT_EQ("content", received_body);
  5044. }
  5045. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5046. #ifdef CPPHTTPLIB_SSL_ENABLED
  5047. using ClientT = SSLClient;
  5048. #else
  5049. using ClientT = Client;
  5050. #endif
  5051. TestWithHeadersAndContentReceiver<ClientT>(
  5052. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5053. const std::string &body, const std::string &content_type,
  5054. ContentReceiver receiver, DownloadProgress progress) {
  5055. return cli.Post(path, headers, body, content_type, receiver, progress);
  5056. });
  5057. }
  5058. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5059. #ifdef CPPHTTPLIB_SSL_ENABLED
  5060. using ClientT = SSLClient;
  5061. #else
  5062. using ClientT = Client;
  5063. #endif
  5064. TestWithHeadersAndContentReceiver<ClientT>(
  5065. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5066. const std::string &body, const std::string &content_type,
  5067. ContentReceiver receiver, DownloadProgress progress) {
  5068. return cli.Put(path, headers, body, content_type, receiver, progress);
  5069. });
  5070. }
  5071. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5072. #ifdef CPPHTTPLIB_SSL_ENABLED
  5073. using ClientT = SSLClient;
  5074. #else
  5075. using ClientT = Client;
  5076. #endif
  5077. TestWithHeadersAndContentReceiver<ClientT>(
  5078. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5079. const std::string &body, const std::string &content_type,
  5080. ContentReceiver receiver, DownloadProgress progress) {
  5081. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5082. });
  5083. }
  5084. template <typename ClientType>
  5085. void TestWithHeadersAndContentReceiverWithProgress(
  5086. ClientType &cli,
  5087. std::function<Result(ClientType &, const std::string &, const Headers &,
  5088. const std::string &, const std::string &,
  5089. ContentReceiver, DownloadProgress)>
  5090. request_func) {
  5091. Headers headers;
  5092. headers.emplace("X-Test-Header", "progress-test");
  5093. std::string received_body;
  5094. auto progress_called = false;
  5095. auto res = request_func(
  5096. cli, "/content_receiver", headers, "content", "text/plain",
  5097. [&](const char *data, size_t data_length) {
  5098. received_body.append(data, data_length);
  5099. return true;
  5100. },
  5101. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5102. progress_called = true;
  5103. return true;
  5104. });
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("content", received_body);
  5108. EXPECT_TRUE(progress_called);
  5109. }
  5110. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5111. #ifdef CPPHTTPLIB_SSL_ENABLED
  5112. using ClientT = SSLClient;
  5113. #else
  5114. using ClientT = Client;
  5115. #endif
  5116. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5117. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5118. const std::string &body, const std::string &content_type,
  5119. ContentReceiver receiver, DownloadProgress progress) {
  5120. return cli.Post(path, headers, body, content_type, receiver, progress);
  5121. });
  5122. }
  5123. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5124. #ifdef CPPHTTPLIB_SSL_ENABLED
  5125. using ClientT = SSLClient;
  5126. #else
  5127. using ClientT = Client;
  5128. #endif
  5129. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5131. const std::string &body, const std::string &content_type,
  5132. ContentReceiver receiver, DownloadProgress progress) {
  5133. return cli.Put(path, headers, body, content_type, receiver, progress);
  5134. });
  5135. }
  5136. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5137. #ifdef CPPHTTPLIB_SSL_ENABLED
  5138. using ClientT = SSLClient;
  5139. #else
  5140. using ClientT = Client;
  5141. #endif
  5142. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5144. const std::string &body, const std::string &content_type,
  5145. ContentReceiver receiver, DownloadProgress progress) {
  5146. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5147. });
  5148. }
  5149. template <typename ClientType>
  5150. void TestWithHeadersAndContentReceiverError(
  5151. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5152. const Headers &, const std::string &,
  5153. const std::string &, ContentReceiver)>
  5154. request_func) {
  5155. Headers headers;
  5156. headers.emplace("X-Error-Test", "true");
  5157. std::string received_body;
  5158. auto receiver_failed = false;
  5159. auto res =
  5160. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5161. [&](const char *data, size_t data_length) {
  5162. received_body.append(data, data_length);
  5163. receiver_failed = true;
  5164. return false;
  5165. });
  5166. ASSERT_FALSE(res);
  5167. EXPECT_TRUE(receiver_failed);
  5168. }
  5169. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5170. #ifdef CPPHTTPLIB_SSL_ENABLED
  5171. using ClientT = SSLClient;
  5172. #else
  5173. using ClientT = Client;
  5174. #endif
  5175. TestWithHeadersAndContentReceiverError<ClientT>(
  5176. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5177. const std::string &body, const std::string &content_type,
  5178. ContentReceiver receiver) {
  5179. return cli.Post(path, headers, body, content_type, receiver);
  5180. });
  5181. }
  5182. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5183. #ifdef CPPHTTPLIB_SSL_ENABLED
  5184. using ClientT = SSLClient;
  5185. #else
  5186. using ClientT = Client;
  5187. #endif
  5188. TestWithHeadersAndContentReceiverError<ClientT>(
  5189. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5190. const std::string &body, const std::string &content_type,
  5191. ContentReceiver receiver) {
  5192. return cli.Put(path, headers, body, content_type, receiver);
  5193. });
  5194. }
  5195. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5196. #ifdef CPPHTTPLIB_SSL_ENABLED
  5197. using ClientT = SSLClient;
  5198. #else
  5199. using ClientT = Client;
  5200. #endif
  5201. TestWithHeadersAndContentReceiverError<ClientT>(
  5202. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5203. const std::string &body, const std::string &content_type,
  5204. ContentReceiver receiver) {
  5205. return cli.Patch(path, headers, body, content_type, receiver);
  5206. });
  5207. }
  5208. TEST_F(ServerTest, PostQueryStringAndBody) {
  5209. auto res =
  5210. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5211. ASSERT_TRUE(res);
  5212. ASSERT_EQ(StatusCode::OK_200, res->status);
  5213. }
  5214. TEST_F(ServerTest, HTTP2Magic) {
  5215. Request req;
  5216. req.method = "PRI";
  5217. req.path = "*";
  5218. req.body = "SM";
  5219. auto res = std::make_shared<Response>();
  5220. auto error = Error::Success;
  5221. auto ret = cli_.send(req, *res, error);
  5222. ASSERT_TRUE(ret);
  5223. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5224. }
  5225. TEST_F(ServerTest, KeepAlive) {
  5226. auto res = cli_.Get("/hi");
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("Hello World!", res->body);
  5231. res = cli_.Get("/hi");
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ(StatusCode::OK_200, res->status);
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("Hello World!", res->body);
  5236. res = cli_.Get("/hi");
  5237. ASSERT_TRUE(res);
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ("Hello World!", res->body);
  5241. res = cli_.Get("/not-exist");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5244. res = cli_.Post("/empty", "", "text/plain");
  5245. ASSERT_TRUE(res);
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("empty", res->body);
  5249. EXPECT_EQ("close", res->get_header_value("Connection"));
  5250. res = cli_.Post(
  5251. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5252. "text/plain");
  5253. ASSERT_TRUE(res);
  5254. EXPECT_EQ(StatusCode::OK_200, res->status);
  5255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5256. EXPECT_EQ("empty", res->body);
  5257. cli_.set_keep_alive(false);
  5258. res = cli_.Get("/last-request");
  5259. ASSERT_TRUE(res);
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("close", res->get_header_value("Connection"));
  5262. }
  5263. TEST_F(ServerTest, TooManyRedirect) {
  5264. cli_.set_follow_location(true);
  5265. auto res = cli_.Get("/redirect/0");
  5266. ASSERT_TRUE(!res);
  5267. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5268. }
  5269. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5270. Request req;
  5271. req.method = "FOOBAR";
  5272. req.path = "/hi";
  5273. cli_.set_keep_alive(true);
  5274. auto res = cli_.send(req);
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5277. EXPECT_EQ("close", res->get_header_value("Connection"));
  5278. EXPECT_FALSE(cli_.is_socket_open());
  5279. }
  5280. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5281. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5282. TEST_F(ServerTest, Gzip) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "gzip, deflate");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "gzip, deflate");
  5298. auto res = cli_.Get("/compress-with-charset", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5301. EXPECT_EQ("application/json; charset=utf-8",
  5302. res->get_header_value("Content-Type"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "");
  5311. auto res = cli_.Get("/compress", headers);
  5312. ASSERT_TRUE(res);
  5313. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5315. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5316. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5317. "7890123456789012345678901234567890",
  5318. res->body);
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. }
  5321. TEST_F(ServerTest, GzipWithContentReceiver) {
  5322. Headers headers;
  5323. headers.emplace("Accept-Encoding", "gzip, deflate");
  5324. std::string body;
  5325. auto res = cli_.Get("/compress", headers,
  5326. [&](const char *data, uint64_t data_length) {
  5327. EXPECT_EQ(100U, data_length);
  5328. body.append(data, data_length);
  5329. return true;
  5330. });
  5331. ASSERT_TRUE(res);
  5332. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5334. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5335. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5336. "7890123456789012345678901234567890",
  5337. body);
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. }
  5340. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5341. Headers headers;
  5342. headers.emplace("Accept-Encoding", "gzip, deflate");
  5343. cli_.set_decompress(false);
  5344. auto res = cli_.Get("/compress", headers);
  5345. ASSERT_TRUE(res);
  5346. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5348. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5349. EXPECT_EQ(33U, res->body.size());
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "");
  5355. std::string body;
  5356. auto res = cli_.Get("/compress", headers,
  5357. [&](const char *data, uint64_t data_length) {
  5358. EXPECT_EQ(100U, data_length);
  5359. body.append(data, data_length);
  5360. return true;
  5361. });
  5362. ASSERT_TRUE(res);
  5363. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, NoGzip) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "gzip, deflate");
  5374. auto res = cli_.Get("/nocompress", headers);
  5375. ASSERT_TRUE(res);
  5376. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5377. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5378. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5379. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5380. "7890123456789012345678901234567890",
  5381. res->body);
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. }
  5384. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5385. Headers headers;
  5386. headers.emplace("Accept-Encoding", "gzip, deflate");
  5387. std::string body;
  5388. auto res = cli_.Get("/nocompress", headers,
  5389. [&](const char *data, uint64_t data_length) {
  5390. EXPECT_EQ(100U, data_length);
  5391. body.append(data, data_length);
  5392. return true;
  5393. });
  5394. ASSERT_TRUE(res);
  5395. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5396. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5397. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5399. "7890123456789012345678901234567890",
  5400. body);
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST_F(ServerTest, MultipartFormDataGzip) {
  5404. UploadFormDataItems items = {
  5405. {"key1", "test", "", ""},
  5406. {"key2", "--abcdefg123", "", ""},
  5407. };
  5408. cli_.set_compress(true);
  5409. auto res = cli_.Post("/compress-multipart", items);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. }
  5413. #endif
  5414. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5415. TEST_F(ServerTest, Brotli) {
  5416. Headers headers;
  5417. headers.emplace("Accept-Encoding", "br");
  5418. auto res = cli_.Get("/compress", headers);
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5423. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5424. "7890123456789012345678901234567890",
  5425. res->body);
  5426. EXPECT_EQ(StatusCode::OK_200, res->status);
  5427. }
  5428. #endif
  5429. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5430. TEST_F(ServerTest, Zstd) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "zstd");
  5433. auto res = cli_.Get("/compress", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5438. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5439. "7890123456789012345678901234567890",
  5440. res->body);
  5441. EXPECT_EQ(StatusCode::OK_200, res->status);
  5442. }
  5443. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5444. Headers headers;
  5445. headers.emplace("Accept-Encoding", "");
  5446. auto res = cli_.Get("/compress", headers);
  5447. ASSERT_TRUE(res);
  5448. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5450. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5452. "7890123456789012345678901234567890",
  5453. res->body);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. }
  5456. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "zstd");
  5459. std::string body;
  5460. auto res = cli_.Get("/compress", headers,
  5461. [&](const char *data, uint64_t data_length) {
  5462. EXPECT_EQ(100U, data_length);
  5463. body.append(data, data_length);
  5464. return true;
  5465. });
  5466. ASSERT_TRUE(res);
  5467. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5469. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5471. "7890123456789012345678901234567890",
  5472. body);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. }
  5475. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5476. Headers headers;
  5477. headers.emplace("Accept-Encoding", "zstd");
  5478. cli_.set_decompress(false);
  5479. auto res = cli_.Get("/compress", headers);
  5480. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5481. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5482. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5483. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ(26U, res->body.size());
  5490. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5491. 0);
  5492. }
  5493. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "");
  5496. std::string body;
  5497. auto res = cli_.Get("/compress", headers,
  5498. [&](const char *data, uint64_t data_length) {
  5499. EXPECT_EQ(100U, data_length);
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res);
  5504. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5508. "7890123456789012345678901234567890",
  5509. body);
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. }
  5512. TEST_F(ServerTest, NoZstd) {
  5513. Headers headers;
  5514. headers.emplace("Accept-Encoding", "zstd");
  5515. auto res = cli_.Get("/nocompress", headers);
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5518. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5521. "7890123456789012345678901234567890",
  5522. res->body);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5526. Headers headers;
  5527. headers.emplace("Accept-Encoding", "zstd");
  5528. std::string body;
  5529. auto res = cli_.Get("/nocompress", headers,
  5530. [&](const char *data, uint64_t data_length) {
  5531. EXPECT_EQ(100U, data_length);
  5532. body.append(data, data_length);
  5533. return true;
  5534. });
  5535. ASSERT_TRUE(res);
  5536. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5537. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5538. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5540. "7890123456789012345678901234567890",
  5541. body);
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. }
  5544. // TODO: How to enable zstd ??
  5545. TEST_F(ServerTest, MultipartFormDataZstd) {
  5546. UploadFormDataItems items = {
  5547. {"key1", "test", "", ""},
  5548. {"key2", "--abcdefg123", "", ""},
  5549. };
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "zstd");
  5552. cli_.set_compress(true);
  5553. auto res = cli_.Post("/compress-multipart", headers, items);
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5558. Headers headers;
  5559. headers.emplace("Accept-Encoding", "zstd");
  5560. cli_.set_compress(true);
  5561. auto res = cli_.Put(
  5562. "/put", headers, 3,
  5563. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5564. sink.os << "PUT";
  5565. return true;
  5566. },
  5567. "text/plain");
  5568. ASSERT_TRUE(res);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. EXPECT_EQ("PUT", res->body);
  5571. }
  5572. // Pre-compression logging tests
  5573. TEST_F(ServerTest, PreCompressionLogging) {
  5574. // Test data for compression (matches the actual /compress endpoint content)
  5575. const std::string test_content =
  5576. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5577. "3456789012345678901234567890";
  5578. // Variables to capture logging data
  5579. std::string pre_compression_body;
  5580. std::string pre_compression_content_type;
  5581. std::string pre_compression_content_encoding;
  5582. std::string post_compression_body;
  5583. std::string post_compression_content_type;
  5584. std::string post_compression_content_encoding;
  5585. // Set up pre-compression logger
  5586. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5587. const Response &res) {
  5588. pre_compression_body = res.body;
  5589. pre_compression_content_type = res.get_header_value("Content-Type");
  5590. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5591. });
  5592. // Set up post-compression logger
  5593. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5594. post_compression_body = res.body;
  5595. post_compression_content_type = res.get_header_value("Content-Type");
  5596. post_compression_content_encoding =
  5597. res.get_header_value("Content-Encoding");
  5598. });
  5599. // Test with gzip compression
  5600. Headers headers;
  5601. headers.emplace("Accept-Encoding", "gzip");
  5602. auto res = cli_.Get("/compress", headers);
  5603. // Verify response was compressed
  5604. ASSERT_TRUE(res);
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5607. // Verify pre-compression logger captured uncompressed content
  5608. EXPECT_EQ(test_content, pre_compression_body);
  5609. EXPECT_EQ("text/plain", pre_compression_content_type);
  5610. EXPECT_TRUE(pre_compression_content_encoding
  5611. .empty()); // No encoding header before compression
  5612. // Verify post-compression logger captured compressed content
  5613. EXPECT_NE(test_content,
  5614. post_compression_body); // Should be different after compression
  5615. EXPECT_EQ("text/plain", post_compression_content_type);
  5616. EXPECT_EQ("gzip", post_compression_content_encoding);
  5617. // Verify compressed content is smaller
  5618. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5619. }
  5620. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5621. const std::string test_content =
  5622. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5623. "3456789012345678901234567890";
  5624. std::string pre_compression_body;
  5625. std::string post_compression_body;
  5626. svr_.set_pre_compression_logger(
  5627. [&](const Request & /*req*/, const Response &res) {
  5628. pre_compression_body = res.body;
  5629. });
  5630. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5631. post_compression_body = res.body;
  5632. });
  5633. Headers headers;
  5634. headers.emplace("Accept-Encoding", "br");
  5635. auto res = cli_.Get("/compress", headers);
  5636. ASSERT_TRUE(res);
  5637. EXPECT_EQ(StatusCode::OK_200, res->status);
  5638. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5639. // Verify pre-compression content is uncompressed
  5640. EXPECT_EQ(test_content, pre_compression_body);
  5641. // Verify post-compression content is compressed
  5642. EXPECT_NE(test_content, post_compression_body);
  5643. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5644. }
  5645. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5646. const std::string test_content =
  5647. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5648. "3456789012345678901234567890";
  5649. std::string pre_compression_body;
  5650. std::string post_compression_body;
  5651. svr_.set_pre_compression_logger(
  5652. [&](const Request & /*req*/, const Response &res) {
  5653. pre_compression_body = res.body;
  5654. });
  5655. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5656. post_compression_body = res.body;
  5657. });
  5658. // Request without compression (use /nocompress endpoint)
  5659. Headers headers;
  5660. auto res = cli_.Get("/nocompress", headers);
  5661. ASSERT_TRUE(res);
  5662. EXPECT_EQ(StatusCode::OK_200, res->status);
  5663. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5664. // Pre-compression logger should not be called when no compression is applied
  5665. EXPECT_TRUE(
  5666. pre_compression_body.empty()); // Pre-compression logger not called
  5667. EXPECT_EQ(
  5668. test_content,
  5669. post_compression_body); // Post-compression logger captures final content
  5670. }
  5671. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5672. const std::string test_content =
  5673. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5674. "3456789012345678901234567890";
  5675. std::string pre_compression_body;
  5676. bool pre_logger_called = false;
  5677. // Set only pre-compression logger
  5678. svr_.set_pre_compression_logger(
  5679. [&](const Request & /*req*/, const Response &res) {
  5680. pre_compression_body = res.body;
  5681. pre_logger_called = true;
  5682. });
  5683. Headers headers;
  5684. headers.emplace("Accept-Encoding", "gzip");
  5685. auto res = cli_.Get("/compress", headers);
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5689. // Verify pre-compression logger was called
  5690. EXPECT_TRUE(pre_logger_called);
  5691. EXPECT_EQ(test_content, pre_compression_body);
  5692. }
  5693. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5694. {
  5695. // Test with Expect: 100-continue header - success case
  5696. // Server returns 100 Continue, client sends body, server returns 200 OK
  5697. Request req;
  5698. req.method = "POST";
  5699. req.path = "/post-large";
  5700. req.set_header("Expect", "100-continue");
  5701. req.body = LARGE_DATA;
  5702. Response res;
  5703. auto error = Error::Success;
  5704. cli_.set_keep_alive(true);
  5705. auto ret = cli_.send(req, res, error);
  5706. EXPECT_TRUE(ret);
  5707. EXPECT_EQ(StatusCode::OK_200, res.status);
  5708. EXPECT_EQ(LARGE_DATA, res.body);
  5709. }
  5710. {
  5711. // Test with Expect: 100-continue header - error case
  5712. // Client should not send the body when server returns an error
  5713. Request req;
  5714. req.method = "POST";
  5715. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5716. req.set_header("Expect", "100-continue");
  5717. req.body = LARGE_DATA;
  5718. Response res;
  5719. auto error = Error::Success;
  5720. auto start = std::chrono::high_resolution_clock::now();
  5721. cli_.set_keep_alive(true);
  5722. auto ret = cli_.send(req, res, error);
  5723. auto end = std::chrono::high_resolution_clock::now();
  5724. auto elapsed =
  5725. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5726. .count();
  5727. // With Expect: 100-continue, request completes successfully but with error
  5728. EXPECT_TRUE(ret);
  5729. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5730. EXPECT_EQ("close", res.get_header_value("Connection"));
  5731. EXPECT_FALSE(cli_.is_socket_open());
  5732. EXPECT_LE(elapsed, 200);
  5733. }
  5734. {
  5735. // Send an extra GET request to ensure error recovery without hanging
  5736. Request req;
  5737. req.method = "GET";
  5738. req.path = "/hi";
  5739. auto start = std::chrono::high_resolution_clock::now();
  5740. auto res = cli_.send(req);
  5741. auto end = std::chrono::high_resolution_clock::now();
  5742. auto elapsed =
  5743. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5744. .count();
  5745. ASSERT_TRUE(res);
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("Hello World!", res->body);
  5748. EXPECT_LE(elapsed, 500);
  5749. }
  5750. }
  5751. TEST(ZstdDecompressor, ChunkedDecompression) {
  5752. std::string data;
  5753. for (size_t i = 0; i < 32 * 1024; ++i) {
  5754. data.push_back(static_cast<char>('a' + i % 26));
  5755. }
  5756. std::string compressed_data;
  5757. {
  5758. httplib::detail::zstd_compressor compressor;
  5759. bool result = compressor.compress(
  5760. data.data(), data.size(),
  5761. /*last=*/true,
  5762. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5763. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5764. compressed_data_size);
  5765. return true;
  5766. });
  5767. ASSERT_TRUE(result);
  5768. }
  5769. std::string decompressed_data;
  5770. {
  5771. httplib::detail::zstd_decompressor decompressor;
  5772. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5773. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5774. size_t chunk_size = 130;
  5775. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5776. chunk_begin += chunk_size) {
  5777. size_t current_chunk_size =
  5778. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5779. bool result = decompressor.decompress(
  5780. compressed_data.data() + chunk_begin, current_chunk_size,
  5781. [&](const char *decompressed_data_chunk,
  5782. size_t decompressed_data_chunk_size) {
  5783. decompressed_data.insert(decompressed_data.size(),
  5784. decompressed_data_chunk,
  5785. decompressed_data_chunk_size);
  5786. return true;
  5787. });
  5788. ASSERT_TRUE(result);
  5789. }
  5790. }
  5791. ASSERT_EQ(data, decompressed_data);
  5792. }
  5793. TEST(ZstdDecompressor, Decompress) {
  5794. std::string original_text = "Compressed with ZSTD";
  5795. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5796. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5797. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5798. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5799. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5800. std::string decompressed_data;
  5801. {
  5802. httplib::detail::zstd_decompressor decompressor;
  5803. bool result = decompressor.decompress(
  5804. compressed_data.data(), compressed_data.size(),
  5805. [&](const char *decompressed_data_chunk,
  5806. size_t decompressed_data_chunk_size) {
  5807. decompressed_data.insert(decompressed_data.size(),
  5808. decompressed_data_chunk,
  5809. decompressed_data_chunk_size);
  5810. return true;
  5811. });
  5812. ASSERT_TRUE(result);
  5813. }
  5814. ASSERT_EQ(original_text, decompressed_data);
  5815. }
  5816. #endif
  5817. // Sends a raw request to a server listening at HOST:PORT.
  5818. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5819. std::string *resp = nullptr) {
  5820. auto error = Error::Success;
  5821. auto client_sock = detail::create_client_socket(
  5822. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5823. /*connection_timeout_sec=*/5, 0,
  5824. /*read_timeout_sec=*/5, 0,
  5825. /*write_timeout_sec=*/5, 0, std::string(), error);
  5826. if (client_sock == INVALID_SOCKET) { return false; }
  5827. auto ret = detail::process_client_socket(
  5828. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5829. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5830. if (req.size() !=
  5831. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5832. return false;
  5833. }
  5834. char buf[512];
  5835. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5836. while (line_reader.getline()) {
  5837. if (resp) { *resp += line_reader.ptr(); }
  5838. }
  5839. return true;
  5840. });
  5841. detail::close_socket(client_sock);
  5842. return ret;
  5843. }
  5844. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5845. Server svr;
  5846. std::string header_value;
  5847. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5848. header_value = req.get_header_value("foo");
  5849. res.set_content("ok", "text/plain");
  5850. });
  5851. thread t = thread([&] { svr.listen(HOST, PORT); });
  5852. auto se = detail::scope_exit([&] {
  5853. svr.stop();
  5854. t.join();
  5855. ASSERT_FALSE(svr.is_running());
  5856. });
  5857. svr.wait_until_ready();
  5858. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5859. // like characters are not treated the same - use vertical tab and escape.
  5860. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5861. "foo: \t \v bar \x1B\t \r\n"
  5862. "Connection: close\r\n"
  5863. "\r\n";
  5864. std::string res;
  5865. ASSERT_TRUE(send_request(5, req, &res));
  5866. EXPECT_EQ(header_value, "");
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5868. }
  5869. // Sends a raw request and verifies that there isn't a crash or exception.
  5870. static void test_raw_request(const std::string &req,
  5871. std::string *out = nullptr) {
  5872. Server svr;
  5873. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5874. res.set_content("ok", "text/plain");
  5875. });
  5876. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5877. res.set_content("ok", "text/plain");
  5878. });
  5879. svr.Get("/header_field_value_check",
  5880. [&](const Request & /*req*/, Response &res) {
  5881. res.set_content("ok", "text/plain");
  5882. });
  5883. // Server read timeout must be longer than the client read timeout for the
  5884. // bug to reproduce, probably to force the server to process a request
  5885. // without a trailing blank line.
  5886. const time_t client_read_timeout_sec = 1;
  5887. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5888. bool listen_thread_ok = false;
  5889. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. ASSERT_FALSE(svr.is_running());
  5894. EXPECT_TRUE(listen_thread_ok);
  5895. });
  5896. svr.wait_until_ready();
  5897. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5898. }
  5899. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5900. // A certain header line causes an exception if the header property is parsed
  5901. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5902. test_raw_request(
  5903. "GET /hi HTTP/1.1\r\n"
  5904. " : "
  5905. " "
  5906. " ");
  5907. }
  5908. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5909. // A certain header line causes an exception if the header property *name* is
  5910. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5911. // greedy matcher and requires backtracking when there are a lot of ":"
  5912. // characters.
  5913. // This occurs with libc++ but not libstdc++.
  5914. test_raw_request(
  5915. "GET /hi HTTP/1.1\r\n"
  5916. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5917. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5918. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5919. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5920. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5921. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5922. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5923. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5924. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5925. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5926. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5927. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5928. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5929. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5930. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5931. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5932. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5933. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5934. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5935. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5936. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5937. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5938. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5939. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5940. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5941. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5942. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5943. "&&&%%%");
  5944. }
  5945. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5946. // Make sure this doesn't crash the server.
  5947. // In a previous version of the header line regex, the "\r" rendered the line
  5948. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5949. // a new position where the leading white space ended and the field value
  5950. // began.
  5951. // The crash occurs with libc++ but not libstdc++.
  5952. test_raw_request("GET /hi HTTP/1.1\r\n"
  5953. "a:" +
  5954. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5955. "\r\n"
  5956. "\r\n");
  5957. }
  5958. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5959. std::string out;
  5960. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5961. "Content-Type: text/plain\r\n"
  5962. "Transfer-Encoding: chunked\r\n"
  5963. "\r\n"
  5964. "nothex\r\n",
  5965. &out);
  5966. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5967. }
  5968. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5969. std::string out;
  5970. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5971. "Content-Type: text/plain\r\n"
  5972. "Transfer-Encoding: chunked\r\n"
  5973. "\r\n"
  5974. "3\r\n"
  5975. "xyz\r\n"
  5976. "NaN\r\n",
  5977. &out);
  5978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5979. }
  5980. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5981. std::string out;
  5982. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5983. "Content-Type: text/plain\r\n"
  5984. "Transfer-Encoding: chunked\r\n"
  5985. "\r\n"
  5986. // Length is too large for 64 bits.
  5987. "1ffffffffffffffff\r\n"
  5988. "xyz\r\n",
  5989. &out);
  5990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5991. }
  5992. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5993. test_raw_request("GET /hi HTTP/1.1\r\n"
  5994. "Content-Type: text/plain\r\n\r");
  5995. }
  5996. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5997. std::string out;
  5998. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5999. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6000. }
  6001. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6002. Server svr;
  6003. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6004. EXPECT_TRUE(!req.remote_addr.empty());
  6005. });
  6006. thread t = thread([&] { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. ASSERT_FALSE(svr.is_running());
  6011. });
  6012. svr.wait_until_ready();
  6013. // Send an invalid request line to trigger Bad Request
  6014. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6015. std::string out;
  6016. ASSERT_TRUE(send_request(5, bad_req, &out));
  6017. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6018. }
  6019. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6020. std::string out;
  6021. std::string request(
  6022. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6023. test_raw_request(request, &out);
  6024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6025. }
  6026. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6027. std::string out;
  6028. std::string request(
  6029. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6030. test_raw_request(request, &out);
  6031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6032. }
  6033. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6034. std::string out;
  6035. std::string request(
  6036. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6037. test_raw_request(request, &out);
  6038. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6039. }
  6040. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6041. std::string out;
  6042. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6043. "Test: \r\n\r\n",
  6044. &out);
  6045. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6046. }
  6047. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6048. Server svr;
  6049. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6050. res.set_header("Cache-Control", "no-cache");
  6051. res.set_chunked_content_provider(
  6052. "text/event-stream", [](size_t offset, DataSink &sink) {
  6053. std::string s = "data:";
  6054. s += std::to_string(offset);
  6055. s += "\n\n";
  6056. auto ret = sink.write(s.data(), s.size());
  6057. EXPECT_TRUE(ret);
  6058. std::this_thread::sleep_for(std::chrono::seconds(1));
  6059. return true;
  6060. });
  6061. });
  6062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6063. svr.wait_until_ready();
  6064. Client client(HOST, PORT);
  6065. const Headers headers = {{"Accept", "text/event-stream"}};
  6066. auto get_thread = std::thread([&client, &headers]() {
  6067. auto res = client.Get(
  6068. "/events", headers,
  6069. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6070. });
  6071. auto se = detail::scope_exit([&] {
  6072. svr.stop();
  6073. get_thread.join();
  6074. listen_thread.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. // Give GET time to get a few messages.
  6078. std::this_thread::sleep_for(std::chrono::seconds(2));
  6079. }
  6080. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6081. httplib::Server svr;
  6082. svr.Post("/hi",
  6083. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6084. res.status = StatusCode::OK_200;
  6085. });
  6086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6087. svr.wait_until_ready();
  6088. Client cli(HOST, PORT);
  6089. auto res = cli.Post("/hi", "data", "text/plain");
  6090. ASSERT_TRUE(res);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. svr.stop();
  6093. thread.join();
  6094. ASSERT_FALSE(svr.is_running());
  6095. res = cli.Post("/hi", "data", "text/plain");
  6096. ASSERT_FALSE(res);
  6097. }
  6098. TEST(ServerStopTest, ListenFailure) {
  6099. Server svr;
  6100. auto t = thread([&]() {
  6101. auto ret = svr.listen("????", PORT);
  6102. EXPECT_FALSE(ret);
  6103. });
  6104. svr.wait_until_ready();
  6105. svr.stop();
  6106. t.join();
  6107. }
  6108. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6109. TEST(ServerStopTest, Decommision) {
  6110. Server svr;
  6111. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6112. for (int i = 0; i < 4; i++) {
  6113. auto is_even = !(i % 2);
  6114. std::thread t{[&] {
  6115. try {
  6116. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6117. if (is_even) {
  6118. throw std::runtime_error("Some thing that happens to go wrong.");
  6119. }
  6120. svr.listen(HOST, PORT);
  6121. } catch (...) { svr.decommission(); }
  6122. }};
  6123. svr.wait_until_ready();
  6124. // Server is up
  6125. {
  6126. Client cli(HOST, PORT);
  6127. auto res = cli.Get("/hi");
  6128. if (is_even) {
  6129. EXPECT_FALSE(res);
  6130. } else {
  6131. EXPECT_TRUE(res);
  6132. EXPECT_EQ("hi...", res->body);
  6133. }
  6134. }
  6135. svr.stop();
  6136. t.join();
  6137. // Server is down...
  6138. {
  6139. Client cli(HOST, PORT);
  6140. auto res = cli.Get("/hi");
  6141. EXPECT_FALSE(res);
  6142. }
  6143. }
  6144. }
  6145. #endif
  6146. // Helper function for string body upload progress tests
  6147. template <typename SetupHandler, typename ClientCall>
  6148. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6149. ClientCall &&client_call,
  6150. const string &body) {
  6151. Server svr;
  6152. setup_handler(svr);
  6153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6154. auto se = detail::scope_exit([&] {
  6155. svr.stop();
  6156. t.join();
  6157. });
  6158. svr.wait_until_ready();
  6159. Client cli(HOST, PORT);
  6160. vector<uint64_t> progress_values;
  6161. bool progress_called = false;
  6162. auto res =
  6163. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6164. progress_values.push_back(current);
  6165. progress_called = true;
  6166. return true;
  6167. });
  6168. ASSERT_TRUE(res);
  6169. EXPECT_EQ(200, res->status);
  6170. EXPECT_TRUE(progress_called);
  6171. }
  6172. TEST(UploadProgressTest, PostStringBodyBasic) {
  6173. TestStringBodyUploadProgress(
  6174. [](Server &svr) {
  6175. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6176. res.set_content("received", "text/plain");
  6177. });
  6178. },
  6179. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6180. return cli.Post("/test", body, "text/plain", progress_callback);
  6181. },
  6182. "test data for upload progress");
  6183. }
  6184. TEST(UploadProgressTest, PutStringBodyBasic) {
  6185. TestStringBodyUploadProgress(
  6186. [](Server &svr) {
  6187. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6188. res.set_content("put received", "text/plain");
  6189. });
  6190. },
  6191. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6192. return cli.Put("/test", body, "text/plain", progress_callback);
  6193. },
  6194. "put test data for upload progress");
  6195. }
  6196. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6197. TestStringBodyUploadProgress(
  6198. [](Server &svr) {
  6199. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6200. res.set_content("patch received", "text/plain");
  6201. });
  6202. },
  6203. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6204. return cli.Patch("/test", body, "text/plain", progress_callback);
  6205. },
  6206. "patch test data for upload progress");
  6207. }
  6208. // Helper function for content provider upload progress tests
  6209. template <typename SetupHandler, typename ClientCall>
  6210. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6211. ClientCall &&client_call) {
  6212. Server svr;
  6213. setup_handler(svr);
  6214. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6215. auto se = detail::scope_exit([&] {
  6216. svr.stop();
  6217. t.join();
  6218. });
  6219. svr.wait_until_ready();
  6220. Client cli(HOST, PORT);
  6221. vector<uint64_t> progress_values;
  6222. auto res =
  6223. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6224. progress_values.push_back(current);
  6225. return true;
  6226. });
  6227. ASSERT_TRUE(res);
  6228. EXPECT_EQ(200, res->status);
  6229. EXPECT_FALSE(progress_values.empty());
  6230. }
  6231. TEST(UploadProgressTest, PostContentProviderProgress) {
  6232. TestContentProviderUploadProgress(
  6233. [](Server &svr) {
  6234. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6235. res.set_content("provider received", "text/plain");
  6236. });
  6237. },
  6238. [](Client &cli, UploadProgress progress_callback) {
  6239. return cli.Post(
  6240. "/test", 10,
  6241. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6242. sink.os << "test data";
  6243. return true;
  6244. },
  6245. "text/plain", progress_callback);
  6246. });
  6247. }
  6248. // Helper function for multipart upload progress tests
  6249. template <typename SetupHandler, typename ClientCall>
  6250. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6251. ClientCall &&client_call,
  6252. const string &endpoint) {
  6253. Server svr;
  6254. setup_handler(svr);
  6255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6256. auto se = detail::scope_exit([&] {
  6257. svr.stop();
  6258. t.join();
  6259. });
  6260. svr.wait_until_ready();
  6261. Client cli(HOST, PORT);
  6262. vector<uint64_t> progress_values;
  6263. UploadFormDataItems items = {
  6264. {"field1", "value1", "", ""},
  6265. {"field2", "longer value for progress tracking test", "", ""},
  6266. {"file1", "file content data for upload progress", "test.txt",
  6267. "text/plain"}};
  6268. auto res = client_call(cli, endpoint, items,
  6269. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6270. progress_values.push_back(current);
  6271. return true;
  6272. });
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ(200, res->status);
  6275. EXPECT_FALSE(progress_values.empty());
  6276. }
  6277. TEST(UploadProgressTest, PostMultipartProgress) {
  6278. TestMultipartUploadProgress(
  6279. [](Server &svr) {
  6280. svr.Post("/multipart", [](const Request &req, Response &res) {
  6281. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6282. res.set_content("multipart received", "text/plain");
  6283. });
  6284. },
  6285. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6286. UploadProgress progress_callback) {
  6287. return cli.Post(endpoint, items, progress_callback);
  6288. },
  6289. "/multipart");
  6290. }
  6291. // Helper function for basic download progress tests
  6292. template <typename SetupHandler, typename ClientCall>
  6293. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6294. ClientCall &&client_call, const string &endpoint,
  6295. size_t expected_content_size) {
  6296. Server svr;
  6297. setup_handler(svr);
  6298. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6299. auto se = detail::scope_exit([&] {
  6300. svr.stop();
  6301. t.join();
  6302. });
  6303. svr.wait_until_ready();
  6304. Client cli(HOST, PORT);
  6305. vector<uint64_t> progress_values;
  6306. auto res = client_call(cli, endpoint,
  6307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6308. progress_values.push_back(current);
  6309. return true;
  6310. });
  6311. ASSERT_TRUE(res);
  6312. EXPECT_EQ(200, res->status);
  6313. EXPECT_FALSE(progress_values.empty());
  6314. EXPECT_EQ(expected_content_size, res->body.size());
  6315. }
  6316. TEST(DownloadProgressTest, GetBasic) {
  6317. TestBasicDownloadProgress(
  6318. [](Server &svr) {
  6319. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6320. string content(1000, 'D');
  6321. res.set_content(content, "text/plain");
  6322. });
  6323. },
  6324. [](Client &cli, const string &endpoint,
  6325. DownloadProgress progress_callback) {
  6326. return cli.Get(endpoint, progress_callback);
  6327. },
  6328. "/download", 1000u);
  6329. }
  6330. // Helper function for content receiver download progress tests
  6331. template <typename SetupHandler, typename ClientCall>
  6332. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6333. ClientCall &&client_call,
  6334. const string &endpoint,
  6335. size_t expected_content_size) {
  6336. Server svr;
  6337. setup_handler(svr);
  6338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6339. auto se = detail::scope_exit([&] {
  6340. svr.stop();
  6341. t.join();
  6342. });
  6343. svr.wait_until_ready();
  6344. Client cli(HOST, PORT);
  6345. vector<uint64_t> progress_values;
  6346. string received_body;
  6347. auto res = client_call(
  6348. cli, endpoint,
  6349. [&](const char *data, size_t data_length) -> bool {
  6350. received_body.append(data, data_length);
  6351. return true;
  6352. },
  6353. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6354. progress_values.push_back(current);
  6355. return true;
  6356. });
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(200, res->status);
  6359. EXPECT_FALSE(progress_values.empty());
  6360. EXPECT_EQ(expected_content_size, received_body.size());
  6361. EXPECT_TRUE(res->body.empty());
  6362. }
  6363. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6364. TestContentReceiverDownloadProgress(
  6365. [](Server &svr) {
  6366. svr.Get("/download-receiver",
  6367. [](const Request & /*req*/, Response &res) {
  6368. string content(2000, 'R');
  6369. res.set_content(content, "text/plain");
  6370. });
  6371. },
  6372. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6373. DownloadProgress progress_callback) {
  6374. return cli.Get(endpoint, content_receiver, progress_callback);
  6375. },
  6376. "/download-receiver", 2000u);
  6377. }
  6378. TEST(StreamingTest, NoContentLengthStreaming) {
  6379. Server svr;
  6380. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6381. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6382. if (offset < 6) {
  6383. sink.os << (offset < 3 ? "a" : "b");
  6384. } else {
  6385. sink.done();
  6386. }
  6387. return true;
  6388. });
  6389. });
  6390. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6391. auto listen_se = detail::scope_exit([&] {
  6392. svr.stop();
  6393. listen_thread.join();
  6394. ASSERT_FALSE(svr.is_running());
  6395. });
  6396. svr.wait_until_ready();
  6397. Client client(HOST, PORT);
  6398. auto get_thread = std::thread([&client]() {
  6399. std::string s;
  6400. auto res =
  6401. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6402. s += std::string(data, len);
  6403. return true;
  6404. });
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("aaabbb", s);
  6408. });
  6409. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6410. // Give GET time to get a few messages.
  6411. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6412. }
  6413. TEST(MountTest, Unmount) {
  6414. Server svr;
  6415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6416. auto se = detail::scope_exit([&] {
  6417. svr.stop();
  6418. listen_thread.join();
  6419. ASSERT_FALSE(svr.is_running());
  6420. });
  6421. svr.wait_until_ready();
  6422. Client cli("localhost", PORT);
  6423. svr.set_mount_point("/mount2", "./www2");
  6424. auto res = cli.Get("/");
  6425. ASSERT_TRUE(res);
  6426. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6427. res = cli.Get("/mount2/dir/test.html");
  6428. ASSERT_TRUE(res);
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. svr.set_mount_point("/", "./www");
  6431. res = cli.Get("/dir/");
  6432. ASSERT_TRUE(res);
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. svr.remove_mount_point("/");
  6435. res = cli.Get("/dir/");
  6436. ASSERT_TRUE(res);
  6437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6438. svr.remove_mount_point("/mount2");
  6439. res = cli.Get("/mount2/dir/test.html");
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6442. }
  6443. TEST(MountTest, Redicect) {
  6444. Server svr;
  6445. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6446. auto se = detail::scope_exit([&] {
  6447. svr.stop();
  6448. listen_thread.join();
  6449. ASSERT_FALSE(svr.is_running());
  6450. });
  6451. svr.set_mount_point("/", "./www");
  6452. svr.wait_until_ready();
  6453. Client cli("localhost", PORT);
  6454. auto res = cli.Get("/dir/");
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. res = cli.Get("/dir");
  6458. ASSERT_TRUE(res);
  6459. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6460. res = cli.Get("/file");
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. res = cli.Get("/file/");
  6464. ASSERT_TRUE(res);
  6465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6466. cli.set_follow_location(true);
  6467. res = cli.Get("/dir");
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. }
  6471. TEST(MountTest, MultibytesPathName) {
  6472. Server svr;
  6473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6474. auto se = detail::scope_exit([&] {
  6475. svr.stop();
  6476. listen_thread.join();
  6477. ASSERT_FALSE(svr.is_running());
  6478. });
  6479. svr.set_mount_point("/", "./www");
  6480. svr.wait_until_ready();
  6481. Client cli("localhost", PORT);
  6482. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6483. ASSERT_TRUE(res);
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6486. }
  6487. TEST(KeepAliveTest, ReadTimeout) {
  6488. Server svr;
  6489. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6490. std::this_thread::sleep_for(std::chrono::seconds(2));
  6491. res.set_content("a", "text/plain");
  6492. });
  6493. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6494. res.set_content("b", "text/plain");
  6495. });
  6496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6497. auto se = detail::scope_exit([&] {
  6498. svr.stop();
  6499. listen_thread.join();
  6500. ASSERT_FALSE(svr.is_running());
  6501. });
  6502. svr.wait_until_ready();
  6503. Client cli("localhost", PORT);
  6504. cli.set_keep_alive(true);
  6505. cli.set_read_timeout(std::chrono::seconds(1));
  6506. auto resa = cli.Get("/a");
  6507. ASSERT_FALSE(resa);
  6508. EXPECT_EQ(Error::Read, resa.error());
  6509. auto resb = cli.Get("/b");
  6510. ASSERT_TRUE(resb);
  6511. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6512. EXPECT_EQ("b", resb->body);
  6513. }
  6514. TEST(KeepAliveTest, MaxCount) {
  6515. size_t keep_alive_max_count = 3;
  6516. Server svr;
  6517. svr.set_keep_alive_max_count(keep_alive_max_count);
  6518. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6519. res.set_content("Hello World!", "text/plain");
  6520. });
  6521. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6522. auto se = detail::scope_exit([&] {
  6523. svr.stop();
  6524. listen_thread.join();
  6525. ASSERT_FALSE(svr.is_running());
  6526. });
  6527. svr.wait_until_ready();
  6528. Client cli(HOST, PORT);
  6529. cli.set_keep_alive(true);
  6530. for (size_t i = 0; i < 5; i++) {
  6531. auto result = cli.Get("/hi");
  6532. ASSERT_TRUE(result);
  6533. EXPECT_EQ(StatusCode::OK_200, result->status);
  6534. if (i == keep_alive_max_count - 1) {
  6535. EXPECT_EQ("close", result->get_header_value("Connection"));
  6536. } else {
  6537. EXPECT_FALSE(result->has_header("Connection"));
  6538. }
  6539. }
  6540. }
  6541. TEST(KeepAliveTest, Issue1041) {
  6542. Server svr;
  6543. svr.set_keep_alive_timeout(3);
  6544. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6545. res.set_content("Hello World!", "text/plain");
  6546. });
  6547. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6548. auto se = detail::scope_exit([&] {
  6549. svr.stop();
  6550. listen_thread.join();
  6551. ASSERT_FALSE(svr.is_running());
  6552. });
  6553. svr.wait_until_ready();
  6554. Client cli(HOST, PORT);
  6555. cli.set_keep_alive(true);
  6556. auto result = cli.Get("/hi");
  6557. ASSERT_TRUE(result);
  6558. EXPECT_EQ(StatusCode::OK_200, result->status);
  6559. std::this_thread::sleep_for(std::chrono::seconds(5));
  6560. result = cli.Get("/hi");
  6561. ASSERT_TRUE(result);
  6562. EXPECT_EQ(StatusCode::OK_200, result->status);
  6563. }
  6564. TEST(KeepAliveTest, Issue1959) {
  6565. Server svr;
  6566. svr.set_keep_alive_timeout(5);
  6567. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6568. res.set_content("a", "text/plain");
  6569. });
  6570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6571. auto se = detail::scope_exit([&] {
  6572. if (!svr.is_running()) return;
  6573. svr.stop();
  6574. listen_thread.join();
  6575. ASSERT_FALSE(svr.is_running());
  6576. });
  6577. svr.wait_until_ready();
  6578. Client cli("localhost", PORT);
  6579. cli.set_keep_alive(true);
  6580. using namespace std::chrono;
  6581. auto start = steady_clock::now();
  6582. cli.Get("/a");
  6583. svr.stop();
  6584. listen_thread.join();
  6585. auto end = steady_clock::now();
  6586. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6587. EXPECT_LT(elapsed, 5000);
  6588. }
  6589. #ifdef CPPHTTPLIB_SSL_ENABLED
  6590. TEST(KeepAliveTest, SSLClientReconnection) {
  6591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6592. ASSERT_TRUE(svr.is_valid());
  6593. svr.set_keep_alive_timeout(1);
  6594. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6595. res.set_content("Hello World!", "text/plain");
  6596. });
  6597. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6598. auto se = detail::scope_exit([&] {
  6599. svr.stop();
  6600. listen_thread.join();
  6601. ASSERT_FALSE(svr.is_running());
  6602. });
  6603. svr.wait_until_ready();
  6604. SSLClient cli(HOST, PORT);
  6605. cli.enable_server_certificate_verification(false);
  6606. cli.set_keep_alive(true);
  6607. auto result = cli.Get("/hi");
  6608. ASSERT_TRUE(result);
  6609. EXPECT_EQ(StatusCode::OK_200, result->status);
  6610. result = cli.Get("/hi");
  6611. ASSERT_TRUE(result);
  6612. EXPECT_EQ(StatusCode::OK_200, result->status);
  6613. std::this_thread::sleep_for(std::chrono::seconds(2));
  6614. // Recoonect
  6615. result = cli.Get("/hi");
  6616. ASSERT_TRUE(result);
  6617. EXPECT_EQ(StatusCode::OK_200, result->status);
  6618. result = cli.Get("/hi");
  6619. ASSERT_TRUE(result);
  6620. EXPECT_EQ(StatusCode::OK_200, result->status);
  6621. }
  6622. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6624. ASSERT_TRUE(svr.is_valid());
  6625. svr.set_keep_alive_timeout(1);
  6626. std::string content = "reconnect";
  6627. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6628. res.set_content("Hello World!", "text/plain");
  6629. });
  6630. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6631. auto se = detail::scope_exit([&] {
  6632. svr.stop();
  6633. listen_thread.join();
  6634. ASSERT_FALSE(svr.is_running());
  6635. });
  6636. svr.wait_until_ready();
  6637. SSLClient cli(HOST, PORT);
  6638. cli.enable_server_certificate_verification(false);
  6639. cli.set_keep_alive(true);
  6640. auto result = cli.Post(
  6641. "/hi", content.size(),
  6642. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6643. sink.write(content.c_str(), content.size());
  6644. return true;
  6645. },
  6646. "text/plain");
  6647. ASSERT_TRUE(result);
  6648. EXPECT_EQ(200, result->status);
  6649. std::this_thread::sleep_for(std::chrono::seconds(2));
  6650. // Recoonect
  6651. result = cli.Post(
  6652. "/hi", content.size(),
  6653. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6654. sink.write(content.c_str(), content.size());
  6655. return true;
  6656. },
  6657. "text/plain");
  6658. ASSERT_TRUE(result);
  6659. EXPECT_EQ(200, result->status);
  6660. result = cli.Post(
  6661. "/hi", content.size(),
  6662. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6663. sink.write(content.c_str(), content.size());
  6664. return true;
  6665. },
  6666. "text/plain");
  6667. ASSERT_TRUE(result);
  6668. EXPECT_EQ(200, result->status);
  6669. }
  6670. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6671. using namespace httplib::tls;
  6672. {
  6673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6674. ASSERT_TRUE(svr.is_valid());
  6675. svr.Get("/sni", [&](const Request &req, Response &res) {
  6676. std::string expected = req.sni();
  6677. EXPECT_EQ(expected, req.get_param_value("expected"));
  6678. res.set_content("ok", "text/plain");
  6679. });
  6680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6681. auto se = detail::scope_exit([&] {
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. {
  6688. SSLClient cli("localhost", PORT);
  6689. cli.enable_server_certificate_verification(false);
  6690. auto res = cli.Get("/sni?expected=localhost");
  6691. ASSERT_TRUE(res);
  6692. }
  6693. {
  6694. SSLClient cli("::1", PORT);
  6695. cli.enable_server_certificate_verification(false);
  6696. auto res = cli.Get("/sni?expected=");
  6697. // NOTE: This may fail if the server is listening on IPv4 only
  6698. // (e.g., when localhost resolves to 127.0.0.1 only)
  6699. if (res) {
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. } else {
  6702. EXPECT_EQ(Error::Connection, res.error());
  6703. }
  6704. }
  6705. }
  6706. }
  6707. #endif
  6708. TEST(ClientProblemDetectionTest, ContentProvider) {
  6709. Server svr;
  6710. size_t content_length = 1024 * 1024;
  6711. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6712. res.set_content_provider(
  6713. content_length, "text/plain",
  6714. [&](size_t offset, size_t length, DataSink &sink) {
  6715. auto out_len = std::min(length, static_cast<size_t>(1024));
  6716. std::string out(out_len, '@');
  6717. sink.write(out.data(), out_len);
  6718. return offset < 4096;
  6719. },
  6720. [](bool success) { ASSERT_FALSE(success); });
  6721. });
  6722. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6723. res.set_content_provider(
  6724. 0, "text/plain",
  6725. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6726. EXPECT_TRUE(false);
  6727. return true;
  6728. },
  6729. [](bool success) { ASSERT_FALSE(success); });
  6730. });
  6731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6732. auto se = detail::scope_exit([&] {
  6733. svr.stop();
  6734. listen_thread.join();
  6735. ASSERT_FALSE(svr.is_running());
  6736. });
  6737. svr.wait_until_ready();
  6738. Client cli("localhost", PORT);
  6739. {
  6740. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6741. size_t /*data_length*/) { return false; });
  6742. ASSERT_FALSE(res);
  6743. }
  6744. {
  6745. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6746. size_t /*data_length*/) { return false; });
  6747. ASSERT_TRUE(res);
  6748. }
  6749. }
  6750. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6751. Server svr;
  6752. svr.set_error_handler([](Request const &, Response &res) -> void {
  6753. res.set_chunked_content_provider(
  6754. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6755. sink.os << "hello";
  6756. sink.os << "world";
  6757. sink.done();
  6758. return true;
  6759. });
  6760. });
  6761. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6762. auto se = detail::scope_exit([&] {
  6763. svr.stop();
  6764. listen_thread.join();
  6765. ASSERT_FALSE(svr.is_running());
  6766. });
  6767. svr.wait_until_ready();
  6768. Client cli("localhost", PORT);
  6769. auto res = cli.Get("/");
  6770. ASSERT_TRUE(res);
  6771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6772. EXPECT_EQ("helloworld", res->body);
  6773. }
  6774. TEST(LongPollingTest, ClientCloseDetection) {
  6775. Server svr;
  6776. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6777. res.set_chunked_content_provider(
  6778. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6779. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6780. sink.os << "hello";
  6781. auto count = 10;
  6782. while (count > 0 && sink.is_writable()) {
  6783. this_thread::sleep_for(chrono::milliseconds(10));
  6784. count--;
  6785. }
  6786. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6787. return true;
  6788. });
  6789. });
  6790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6791. auto se = detail::scope_exit([&] {
  6792. svr.stop();
  6793. listen_thread.join();
  6794. ASSERT_FALSE(svr.is_running());
  6795. });
  6796. svr.wait_until_ready();
  6797. Client cli("localhost", PORT);
  6798. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6799. EXPECT_EQ("hello", string(data, data_length));
  6800. return false; // close the socket immediately.
  6801. });
  6802. ASSERT_FALSE(res);
  6803. }
  6804. TEST(GetWithParametersTest, GetWithParameters) {
  6805. Server svr;
  6806. svr.Get("/", [&](const Request &req, Response &) {
  6807. EXPECT_EQ("world", req.get_param_value("hello"));
  6808. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6809. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6810. });
  6811. svr.Get("/params", [&](const Request &req, Response &) {
  6812. EXPECT_EQ("world", req.get_param_value("hello"));
  6813. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6814. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6815. });
  6816. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6817. EXPECT_EQ("resource-id", req.matches[1]);
  6818. EXPECT_EQ("foo", req.get_param_value("param1"));
  6819. EXPECT_EQ("bar", req.get_param_value("param2"));
  6820. });
  6821. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6822. EXPECT_EQ("user-id", req.path_params.at("id"));
  6823. EXPECT_EQ("foo", req.get_param_value("param1"));
  6824. EXPECT_EQ("bar", req.get_param_value("param2"));
  6825. });
  6826. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6827. auto se = detail::scope_exit([&] {
  6828. svr.stop();
  6829. listen_thread.join();
  6830. ASSERT_FALSE(svr.is_running());
  6831. });
  6832. svr.wait_until_ready();
  6833. {
  6834. Client cli(HOST, PORT);
  6835. Params params;
  6836. params.emplace("hello", "world");
  6837. params.emplace("hello2", "world2");
  6838. params.emplace("hello3", "world3");
  6839. auto res = cli.Get("/", params, Headers{});
  6840. ASSERT_TRUE(res);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. {
  6844. Client cli(HOST, PORT);
  6845. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6846. ASSERT_TRUE(res);
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. {
  6850. Client cli(HOST, PORT);
  6851. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6852. ASSERT_TRUE(res);
  6853. EXPECT_EQ(StatusCode::OK_200, res->status);
  6854. }
  6855. {
  6856. Client cli(HOST, PORT);
  6857. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6858. ASSERT_TRUE(res);
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. }
  6861. }
  6862. TEST(GetWithParametersTest, GetWithParameters2) {
  6863. Server svr;
  6864. svr.Get("/", [&](const Request &req, Response &res) {
  6865. auto text = req.get_param_value("hello");
  6866. res.set_content(text, "text/plain");
  6867. });
  6868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6869. auto se = detail::scope_exit([&] {
  6870. svr.stop();
  6871. listen_thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli("localhost", PORT);
  6876. Params params;
  6877. params.emplace("hello", "world");
  6878. std::string body;
  6879. auto res = cli.Get("/", params, Headers{},
  6880. [&](const char *data, size_t data_length) {
  6881. body.append(data, data_length);
  6882. return true;
  6883. });
  6884. ASSERT_TRUE(res);
  6885. EXPECT_EQ(StatusCode::OK_200, res->status);
  6886. EXPECT_EQ("world", body);
  6887. }
  6888. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6889. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6890. auto host = "httpcan.org";
  6891. auto path = std::string{"/range/32"};
  6892. #else
  6893. auto host = "nghttp2.org";
  6894. auto path = std::string{"/httpbin/range/32"};
  6895. #endif
  6896. #ifdef CPPHTTPLIB_SSL_ENABLED
  6897. SSLClient cli(host);
  6898. #else
  6899. Client cli(host);
  6900. #endif
  6901. cli.set_default_headers({make_range_header({{1, 10}})});
  6902. cli.set_connection_timeout(5);
  6903. {
  6904. auto res = cli.Get(path);
  6905. ASSERT_TRUE(res);
  6906. EXPECT_EQ("bcdefghijk", res->body);
  6907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6908. }
  6909. {
  6910. auto res = cli.Get(path);
  6911. ASSERT_TRUE(res);
  6912. EXPECT_EQ("bcdefghijk", res->body);
  6913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6914. }
  6915. }
  6916. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6917. Server svr;
  6918. svr.set_default_headers({{"Hello", "World"}});
  6919. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6920. res.set_content("ok", "text/plain");
  6921. });
  6922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6923. auto se = detail::scope_exit([&] {
  6924. svr.stop();
  6925. listen_thread.join();
  6926. ASSERT_FALSE(svr.is_running());
  6927. });
  6928. svr.wait_until_ready();
  6929. Client cli("localhost", PORT);
  6930. auto res = cli.Get("/");
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. EXPECT_EQ("ok", res->body);
  6934. EXPECT_EQ("World", res->get_header_value("Hello"));
  6935. }
  6936. #ifdef CPPHTTPLIB_SSL_ENABLED
  6937. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6939. ASSERT_TRUE(svr.is_valid());
  6940. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6941. std::this_thread::sleep_for(std::chrono::seconds(2));
  6942. res.set_content("a", "text/plain");
  6943. });
  6944. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6945. res.set_content("b", "text/plain");
  6946. });
  6947. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6948. auto se = detail::scope_exit([&] {
  6949. svr.stop();
  6950. listen_thread.join();
  6951. ASSERT_FALSE(svr.is_running());
  6952. });
  6953. svr.wait_until_ready();
  6954. SSLClient cli("localhost", PORT);
  6955. cli.enable_server_certificate_verification(false);
  6956. cli.set_keep_alive(true);
  6957. cli.set_read_timeout(std::chrono::seconds(1));
  6958. auto resa = cli.Get("/a");
  6959. ASSERT_TRUE(!resa);
  6960. EXPECT_EQ(Error::Read, resa.error());
  6961. auto resb = cli.Get("/b");
  6962. ASSERT_TRUE(resb);
  6963. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6964. EXPECT_EQ("b", resb->body);
  6965. }
  6966. #endif
  6967. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6968. protected:
  6969. ServerTestWithAI_PASSIVE()
  6970. : cli_(HOST, PORT)
  6971. #ifdef CPPHTTPLIB_SSL_ENABLED
  6972. ,
  6973. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6974. #endif
  6975. {
  6976. #ifdef CPPHTTPLIB_SSL_ENABLED
  6977. cli_.enable_server_certificate_verification(false);
  6978. #endif
  6979. }
  6980. virtual void SetUp() {
  6981. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6982. res.set_content("Hello World!", "text/plain");
  6983. });
  6984. t_ = thread(
  6985. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6986. svr_.wait_until_ready();
  6987. }
  6988. virtual void TearDown() {
  6989. svr_.stop();
  6990. t_.join();
  6991. }
  6992. #ifdef CPPHTTPLIB_SSL_ENABLED
  6993. SSLClient cli_;
  6994. SSLServer svr_;
  6995. #else
  6996. Client cli_;
  6997. Server svr_;
  6998. #endif
  6999. thread t_;
  7000. };
  7001. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7002. auto res = cli_.Get("/hi");
  7003. ASSERT_TRUE(res);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7006. EXPECT_EQ("Hello World!", res->body);
  7007. }
  7008. class ServerUpDownTest : public ::testing::Test {
  7009. protected:
  7010. ServerUpDownTest() : cli_(HOST, PORT) {}
  7011. virtual void SetUp() {
  7012. t_ = thread([&]() {
  7013. svr_.bind_to_any_port(HOST);
  7014. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7015. ASSERT_TRUE(svr_.listen_after_bind());
  7016. });
  7017. svr_.wait_until_ready();
  7018. }
  7019. virtual void TearDown() {
  7020. svr_.stop();
  7021. t_.join();
  7022. }
  7023. Client cli_;
  7024. Server svr_;
  7025. thread t_;
  7026. };
  7027. TEST_F(ServerUpDownTest, QuickStartStop) {
  7028. // Should not crash, especially when run with
  7029. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7030. }
  7031. class PayloadMaxLengthTest : public ::testing::Test {
  7032. protected:
  7033. PayloadMaxLengthTest()
  7034. : cli_(HOST, PORT)
  7035. #ifdef CPPHTTPLIB_SSL_ENABLED
  7036. ,
  7037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7038. #endif
  7039. {
  7040. #ifdef CPPHTTPLIB_SSL_ENABLED
  7041. cli_.enable_server_certificate_verification(false);
  7042. #endif
  7043. }
  7044. virtual void SetUp() {
  7045. svr_.set_payload_max_length(8);
  7046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7047. res.set_content("test", "text/plain");
  7048. });
  7049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7050. svr_.wait_until_ready();
  7051. }
  7052. virtual void TearDown() {
  7053. svr_.stop();
  7054. t_.join();
  7055. }
  7056. #ifdef CPPHTTPLIB_SSL_ENABLED
  7057. SSLClient cli_;
  7058. SSLServer svr_;
  7059. #else
  7060. Client cli_;
  7061. Server svr_;
  7062. #endif
  7063. thread t_;
  7064. };
  7065. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7066. auto res = cli_.Post("/test", "123456789", "text/plain");
  7067. ASSERT_TRUE(res);
  7068. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7069. res = cli_.Post("/test", "12345678", "text/plain");
  7070. ASSERT_TRUE(res);
  7071. EXPECT_EQ(StatusCode::OK_200, res->status);
  7072. }
  7073. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7074. // Test chunked encoding with payload exceeding the 8-byte limit
  7075. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7076. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7077. ASSERT_TRUE(res);
  7078. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7079. }
  7080. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7081. // Test chunked encoding with payload within the 8-byte limit
  7082. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7083. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7084. ASSERT_TRUE(res);
  7085. EXPECT_EQ(StatusCode::OK_200, res->status);
  7086. }
  7087. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7088. // Test using send_request to send chunked data exceeding payload limit
  7089. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7090. "Host: " +
  7091. std::string(HOST) + ":" + std::to_string(PORT) +
  7092. "\r\n"
  7093. "Transfer-Encoding: chunked\r\n"
  7094. "Connection: close\r\n"
  7095. "\r\n"
  7096. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7097. "0123456789\r\n"
  7098. "0\r\n" // End chunk
  7099. "\r\n";
  7100. std::string response;
  7101. bool result = send_request(1, chunked_request, &response);
  7102. if (!result) {
  7103. // If send_request fails, it might be because the server closed the
  7104. // connection due to payload limit enforcement, which is acceptable
  7105. SUCCEED()
  7106. << "Server rejected oversized chunked request (connection closed)";
  7107. } else {
  7108. // If we got a response, check if it's an error response or connection was
  7109. // closed early Short response length indicates connection was closed due to
  7110. // payload limit
  7111. if (response.length() <= 10) {
  7112. SUCCEED() << "Server closed connection for oversized chunked request";
  7113. } else {
  7114. // Check for error status codes
  7115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7116. response.find("Payload Too Large") != std::string::npos ||
  7117. response.find("400") != std::string::npos);
  7118. }
  7119. }
  7120. }
  7121. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7122. // Test request without Content-Length header exceeding payload limit
  7123. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7124. "Host: " +
  7125. std::string(HOST) + ":" +
  7126. std::to_string(PORT) +
  7127. "\r\n"
  7128. "Connection: close\r\n"
  7129. "\r\n";
  7130. // Add payload exceeding the 8-byte limit
  7131. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7132. request_without_content_length += large_payload;
  7133. std::string response;
  7134. bool result = send_request(1, request_without_content_length, &response);
  7135. if (!result) {
  7136. // If send_request fails, server likely closed connection due to payload
  7137. // limit
  7138. SUCCEED() << "Server rejected oversized request without Content-Length "
  7139. "(connection closed)";
  7140. } else {
  7141. // Check if server responded with error or closed connection early
  7142. if (response.length() <= 10) {
  7143. SUCCEED() << "Server closed connection for oversized request without "
  7144. "Content-Length";
  7145. } else {
  7146. // Check for error status codes
  7147. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7148. response.find("Payload Too Large") != std::string::npos ||
  7149. response.find("400") != std::string::npos);
  7150. }
  7151. }
  7152. }
  7153. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7154. // Test request without Content-Length header within payload limit
  7155. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7156. "Host: " +
  7157. std::string(HOST) + ":" +
  7158. std::to_string(PORT) +
  7159. "\r\n"
  7160. "Connection: close\r\n"
  7161. "\r\n";
  7162. // Add payload within the 8-byte limit
  7163. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7164. request_without_content_length += small_payload;
  7165. std::string response;
  7166. bool result = send_request(1, request_without_content_length, &response);
  7167. // For requests without Content-Length, the server may have different behavior
  7168. // The key is that it should not reject due to payload limit for small
  7169. // payloads
  7170. if (result) {
  7171. // Check for any HTTP response (success or error, but not connection closed)
  7172. if (response.length() > 10) {
  7173. SUCCEED()
  7174. << "Server processed request without Content-Length within limit";
  7175. } else {
  7176. // Short response might indicate connection closed, which is acceptable
  7177. SUCCEED() << "Server closed connection for request without "
  7178. "Content-Length (acceptable behavior)";
  7179. }
  7180. } else {
  7181. // Connection failure might be due to protocol requirements
  7182. SUCCEED() << "Connection issue with request without Content-Length "
  7183. "(environment-specific)";
  7184. }
  7185. }
  7186. class LargePayloadMaxLengthTest : public ::testing::Test {
  7187. protected:
  7188. LargePayloadMaxLengthTest()
  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. // Set 10MB payload limit
  7201. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7202. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7203. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7204. res.set_content("Large payload test", "text/plain");
  7205. });
  7206. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7207. svr_.wait_until_ready();
  7208. }
  7209. virtual void TearDown() {
  7210. svr_.stop();
  7211. t_.join();
  7212. }
  7213. #ifdef CPPHTTPLIB_SSL_ENABLED
  7214. SSLClient cli_;
  7215. SSLServer svr_;
  7216. #else
  7217. Client cli_;
  7218. Server svr_;
  7219. #endif
  7220. thread t_;
  7221. };
  7222. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7223. // Test chunked encoding with payload within 10MB limit
  7224. std::string medium_payload(5 * 1024 * 1024,
  7225. 'A'); // 5MB payload, within 10MB limit
  7226. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7227. ASSERT_TRUE(res);
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. }
  7230. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7231. // Test chunked encoding with payload exceeding 10MB limit
  7232. std::string large_payload(12 * 1024 * 1024,
  7233. 'B'); // 12MB payload, exceeds 10MB limit
  7234. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7235. // Server may either return 413 or close the connection
  7236. if (res) {
  7237. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7238. } else {
  7239. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7240. }
  7241. }
  7242. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7243. // Test request without Content-Length header within 10MB limit
  7244. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7245. "Host: " +
  7246. std::string(HOST) + ":" +
  7247. std::to_string(PORT) +
  7248. "\r\n"
  7249. "Connection: close\r\n"
  7250. "\r\n";
  7251. // Add 1MB payload (within 10MB limit)
  7252. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7253. request_without_content_length += medium_payload;
  7254. std::string response;
  7255. bool result = send_request(5, request_without_content_length, &response);
  7256. if (result) {
  7257. // Should get a proper HTTP response for payloads within limit
  7258. if (response.length() > 10) {
  7259. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7260. "10MB limit";
  7261. } else {
  7262. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7263. "Content-Length)";
  7264. }
  7265. } else {
  7266. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7267. }
  7268. }
  7269. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7270. // Test request without Content-Length header exceeding 10MB limit
  7271. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7272. "Host: " +
  7273. std::string(HOST) + ":" +
  7274. std::to_string(PORT) +
  7275. "\r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. // Add 12MB payload (exceeds 10MB limit)
  7279. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7280. request_without_content_length += large_payload;
  7281. std::string response;
  7282. bool result = send_request(10, request_without_content_length, &response);
  7283. if (!result) {
  7284. // Server should close connection due to payload limit
  7285. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7286. "(connection closed)";
  7287. } else {
  7288. // Check for error response
  7289. if (response.length() <= 10) {
  7290. SUCCEED()
  7291. << "Server closed connection for 12MB request exceeding 10MB limit";
  7292. } else {
  7293. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7294. response.find("Payload Too Large") != std::string::npos ||
  7295. response.find("400") != std::string::npos);
  7296. }
  7297. }
  7298. }
  7299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7300. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7301. // path.
  7302. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7303. Server svr;
  7304. const size_t LIMIT = 64 * 1024; // 64KB
  7305. svr.set_payload_max_length(LIMIT);
  7306. size_t total = 0;
  7307. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7308. const ContentReader &content_reader) {
  7309. content_reader([&](const char * /*data*/, size_t len) {
  7310. total += len;
  7311. return true;
  7312. });
  7313. res.status = 200;
  7314. res.set_content("stream_ok", "text/plain");
  7315. });
  7316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7317. auto se = detail::scope_exit([&] {
  7318. svr.stop();
  7319. thread.join();
  7320. ASSERT_FALSE(svr.is_running());
  7321. });
  7322. svr.wait_until_ready();
  7323. // Prepare 256KB raw data and gzip-compress it
  7324. std::string raw(256 * 1024, 'A');
  7325. std::string gz;
  7326. {
  7327. z_stream zs{};
  7328. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7329. Z_DEFAULT_STRATEGY);
  7330. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7331. zs.avail_in = static_cast<uInt>(raw.size());
  7332. char outbuf[4096];
  7333. int ret;
  7334. do {
  7335. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7336. zs.avail_out = sizeof(outbuf);
  7337. ret = deflate(&zs, Z_FINISH);
  7338. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7339. } while (ret != Z_STREAM_END);
  7340. deflateEnd(&zs);
  7341. }
  7342. Client cli(HOST, PORT);
  7343. cli.set_connection_timeout(std::chrono::seconds(5));
  7344. Headers headers = {{"Content-Encoding", "gzip"}};
  7345. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7346. "application/octet-stream");
  7347. ASSERT_TRUE(res);
  7348. // Server must reject oversized decompressed payloads with 413.
  7349. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7350. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7351. EXPECT_LE(total, LIMIT);
  7352. }
  7353. #endif
  7354. // Regression test for DoS vulnerability: a malicious server sending a response
  7355. // without Content-Length header must not cause unbounded memory consumption on
  7356. // the client side. The client should stop reading after a reasonable limit,
  7357. // similar to the server-side set_payload_max_length protection.
  7358. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7359. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7360. #ifndef _WIN32
  7361. signal(SIGPIPE, SIG_IGN);
  7362. #endif
  7363. auto server_thread = std::thread([] {
  7364. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7365. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7366. default_socket_options(srv);
  7367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7368. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7369. sockaddr_in addr{};
  7370. addr.sin_family = AF_INET;
  7371. addr.sin_port = htons(PORT + 2);
  7372. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7373. int opt = 1;
  7374. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7375. #ifdef _WIN32
  7376. reinterpret_cast<const char *>(&opt),
  7377. #else
  7378. &opt,
  7379. #endif
  7380. sizeof(opt));
  7381. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7382. ::listen(srv, 1);
  7383. sockaddr_in cli_addr{};
  7384. socklen_t cli_len = sizeof(cli_addr);
  7385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7386. if (cli != INVALID_SOCKET) {
  7387. char buf[4096];
  7388. ::recv(cli, buf, sizeof(buf), 0);
  7389. // Malicious response: no Content-Length, no chunked encoding
  7390. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7391. "Connection: close\r\n"
  7392. "\r\n";
  7393. ::send(cli,
  7394. #ifdef _WIN32
  7395. static_cast<const char *>(response_header.c_str()),
  7396. static_cast<int>(response_header.size()),
  7397. #else
  7398. response_header.c_str(), response_header.size(),
  7399. #endif
  7400. 0);
  7401. // Send 10MB of data
  7402. std::string chunk(64 * 1024, 'A');
  7403. size_t total_sent = 0;
  7404. while (total_sent < MALICIOUS_DATA_SIZE) {
  7405. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7406. auto sent = ::send(cli,
  7407. #ifdef _WIN32
  7408. static_cast<const char *>(chunk.c_str()),
  7409. static_cast<int>(to_send),
  7410. #else
  7411. chunk.c_str(), to_send,
  7412. #endif
  7413. 0);
  7414. if (sent <= 0) break;
  7415. total_sent += static_cast<size_t>(sent);
  7416. }
  7417. detail::close_socket(cli);
  7418. }
  7419. detail::close_socket(srv);
  7420. });
  7421. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7422. size_t total_read = 0;
  7423. {
  7424. Client cli("127.0.0.1", PORT + 2);
  7425. cli.set_read_timeout(5, 0);
  7426. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7427. auto stream = cli.open_stream("GET", "/malicious");
  7428. ASSERT_TRUE(stream.is_valid());
  7429. char buffer[64 * 1024];
  7430. ssize_t n;
  7431. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7432. total_read += static_cast<size_t>(n);
  7433. }
  7434. } // StreamHandle and Client destroyed here, closing the socket
  7435. server_thread.join();
  7436. // With set_payload_max_length, the client must stop reading before consuming
  7437. // all 10MB. The read loop should be cut off at or near the configured limit.
  7438. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7439. << "Client read " << total_read << " bytes, exceeding the configured "
  7440. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7441. }
  7442. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7443. // the entire response body without truncation.
  7444. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7445. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7446. #ifndef _WIN32
  7447. signal(SIGPIPE, SIG_IGN);
  7448. #endif
  7449. auto server_thread = std::thread([] {
  7450. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7451. default_socket_options(srv);
  7452. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7453. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7454. sockaddr_in addr{};
  7455. addr.sin_family = AF_INET;
  7456. addr.sin_port = htons(PORT + 2);
  7457. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7458. int opt = 1;
  7459. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7460. #ifdef _WIN32
  7461. reinterpret_cast<const char *>(&opt),
  7462. #else
  7463. &opt,
  7464. #endif
  7465. sizeof(opt));
  7466. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7467. ::listen(srv, 1);
  7468. sockaddr_in cli_addr{};
  7469. socklen_t cli_len = sizeof(cli_addr);
  7470. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7471. if (cli != INVALID_SOCKET) {
  7472. char buf[4096];
  7473. ::recv(cli, buf, sizeof(buf), 0);
  7474. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7475. "Connection: close\r\n"
  7476. "\r\n";
  7477. ::send(cli,
  7478. #ifdef _WIN32
  7479. static_cast<const char *>(response_header.c_str()),
  7480. static_cast<int>(response_header.size()),
  7481. #else
  7482. response_header.c_str(), response_header.size(),
  7483. #endif
  7484. 0);
  7485. std::string chunk(64 * 1024, 'A');
  7486. size_t total_sent = 0;
  7487. while (total_sent < DATA_SIZE) {
  7488. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7489. auto sent = ::send(cli,
  7490. #ifdef _WIN32
  7491. static_cast<const char *>(chunk.c_str()),
  7492. static_cast<int>(to_send),
  7493. #else
  7494. chunk.c_str(), to_send,
  7495. #endif
  7496. 0);
  7497. if (sent <= 0) break;
  7498. total_sent += static_cast<size_t>(sent);
  7499. }
  7500. #ifdef _WIN32
  7501. ::shutdown(cli, SD_SEND);
  7502. #else
  7503. ::shutdown(cli, SHUT_WR);
  7504. #endif
  7505. // Drain until the client closes its end, ensuring all data is delivered
  7506. char drain[1024];
  7507. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7508. detail::close_socket(cli);
  7509. }
  7510. detail::close_socket(srv);
  7511. });
  7512. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7513. size_t total_read = 0;
  7514. {
  7515. Client cli("127.0.0.1", PORT + 2);
  7516. cli.set_read_timeout(5, 0);
  7517. cli.set_payload_max_length(0); // 0 means no limit
  7518. auto stream = cli.open_stream("GET", "/data");
  7519. ASSERT_TRUE(stream.is_valid());
  7520. char buffer[64 * 1024];
  7521. ssize_t n;
  7522. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7523. total_read += static_cast<size_t>(n);
  7524. }
  7525. }
  7526. server_thread.join();
  7527. EXPECT_EQ(total_read, DATA_SIZE)
  7528. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7529. << " bytes without truncation, but only read " << total_read << " bytes.";
  7530. }
  7531. // Verify that content_receiver bypasses the default payload_max_length,
  7532. // allowing streaming downloads larger than 100MB without requiring an explicit
  7533. // set_payload_max_length call.
  7534. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7535. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7536. #ifndef _WIN32
  7537. signal(SIGPIPE, SIG_IGN);
  7538. #endif
  7539. auto server_thread = std::thread([] {
  7540. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7541. default_socket_options(srv);
  7542. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7543. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7544. sockaddr_in addr{};
  7545. addr.sin_family = AF_INET;
  7546. addr.sin_port = htons(PORT + 2);
  7547. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7548. int opt = 1;
  7549. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7550. #ifdef _WIN32
  7551. reinterpret_cast<const char *>(&opt),
  7552. #else
  7553. &opt,
  7554. #endif
  7555. sizeof(opt));
  7556. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7557. ::listen(srv, 1);
  7558. sockaddr_in cli_addr{};
  7559. socklen_t cli_len = sizeof(cli_addr);
  7560. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7561. if (cli != INVALID_SOCKET) {
  7562. char buf[4096];
  7563. ::recv(cli, buf, sizeof(buf), 0);
  7564. // Response with Content-Length larger than default 100MB limit
  7565. auto content_length = std::to_string(DATA_SIZE);
  7566. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7567. "Content-Length: " +
  7568. content_length +
  7569. "\r\n"
  7570. "Connection: close\r\n"
  7571. "\r\n";
  7572. ::send(cli,
  7573. #ifdef _WIN32
  7574. static_cast<const char *>(response_header.c_str()),
  7575. static_cast<int>(response_header.size()),
  7576. #else
  7577. response_header.c_str(), response_header.size(),
  7578. #endif
  7579. 0);
  7580. std::string chunk(64 * 1024, 'A');
  7581. size_t total_sent = 0;
  7582. while (total_sent < DATA_SIZE) {
  7583. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7584. auto sent = ::send(cli,
  7585. #ifdef _WIN32
  7586. static_cast<const char *>(chunk.c_str()),
  7587. static_cast<int>(to_send),
  7588. #else
  7589. chunk.c_str(), to_send,
  7590. #endif
  7591. 0);
  7592. if (sent <= 0) break;
  7593. total_sent += static_cast<size_t>(sent);
  7594. }
  7595. detail::close_socket(cli);
  7596. }
  7597. detail::close_socket(srv);
  7598. });
  7599. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7600. size_t total_received = 0;
  7601. {
  7602. Client cli("127.0.0.1", PORT + 2);
  7603. cli.set_read_timeout(10, 0);
  7604. // Do NOT call set_payload_max_length — use the default 100MB limit
  7605. auto res =
  7606. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7607. total_received += data_length;
  7608. return true;
  7609. });
  7610. ASSERT_TRUE(res);
  7611. EXPECT_EQ(StatusCode::OK_200, res->status);
  7612. }
  7613. server_thread.join();
  7614. EXPECT_EQ(total_received, DATA_SIZE)
  7615. << "With content_receiver, the client should read all " << DATA_SIZE
  7616. << " bytes despite the default 100MB payload_max_length, but only read "
  7617. << total_received << " bytes.";
  7618. }
  7619. // Verify that an explicit set_payload_max_length smaller than the response is
  7620. // enforced even when a content_receiver is used.
  7621. TEST(ClientVulnerabilityTest,
  7622. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7623. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7624. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7625. #ifndef _WIN32
  7626. signal(SIGPIPE, SIG_IGN);
  7627. #endif
  7628. auto server_thread = std::thread([] {
  7629. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7630. default_socket_options(srv);
  7631. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7632. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7633. sockaddr_in addr{};
  7634. addr.sin_family = AF_INET;
  7635. addr.sin_port = htons(PORT + 2);
  7636. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7637. int opt = 1;
  7638. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7639. #ifdef _WIN32
  7640. reinterpret_cast<const char *>(&opt),
  7641. #else
  7642. &opt,
  7643. #endif
  7644. sizeof(opt));
  7645. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7646. ::listen(srv, 1);
  7647. sockaddr_in cli_addr{};
  7648. socklen_t cli_len = sizeof(cli_addr);
  7649. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7650. if (cli != INVALID_SOCKET) {
  7651. char buf[4096];
  7652. ::recv(cli, buf, sizeof(buf), 0);
  7653. auto content_length = std::to_string(DATA_SIZE);
  7654. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7655. "Content-Length: " +
  7656. content_length +
  7657. "\r\n"
  7658. "Connection: close\r\n"
  7659. "\r\n";
  7660. ::send(cli,
  7661. #ifdef _WIN32
  7662. static_cast<const char *>(response_header.c_str()),
  7663. static_cast<int>(response_header.size()),
  7664. #else
  7665. response_header.c_str(), response_header.size(),
  7666. #endif
  7667. 0);
  7668. std::string chunk(64 * 1024, 'A');
  7669. size_t total_sent = 0;
  7670. while (total_sent < DATA_SIZE) {
  7671. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7672. auto sent = ::send(cli,
  7673. #ifdef _WIN32
  7674. static_cast<const char *>(chunk.c_str()),
  7675. static_cast<int>(to_send),
  7676. #else
  7677. chunk.c_str(), to_send,
  7678. #endif
  7679. 0);
  7680. if (sent <= 0) break;
  7681. total_sent += static_cast<size_t>(sent);
  7682. }
  7683. detail::close_socket(cli);
  7684. }
  7685. detail::close_socket(srv);
  7686. });
  7687. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7688. size_t total_received = 0;
  7689. {
  7690. Client cli("127.0.0.1", PORT + 2);
  7691. cli.set_read_timeout(10, 0);
  7692. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7693. auto res =
  7694. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7695. total_received += data_length;
  7696. return true;
  7697. });
  7698. // Should fail because 200MB exceeds the explicit 150MB limit
  7699. EXPECT_FALSE(res);
  7700. }
  7701. server_thread.join();
  7702. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7703. << "Client with content_receiver should respect the explicit "
  7704. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7705. << total_received << " bytes.";
  7706. }
  7707. // Verify that an explicit set_payload_max_length larger than the response
  7708. // allows the content_receiver to read all data successfully.
  7709. TEST(ClientVulnerabilityTest,
  7710. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7711. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7712. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7713. #ifndef _WIN32
  7714. signal(SIGPIPE, SIG_IGN);
  7715. #endif
  7716. auto server_thread = std::thread([] {
  7717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7718. default_socket_options(srv);
  7719. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7720. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7721. sockaddr_in addr{};
  7722. addr.sin_family = AF_INET;
  7723. addr.sin_port = htons(PORT + 2);
  7724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7725. int opt = 1;
  7726. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7727. #ifdef _WIN32
  7728. reinterpret_cast<const char *>(&opt),
  7729. #else
  7730. &opt,
  7731. #endif
  7732. sizeof(opt));
  7733. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7734. ::listen(srv, 1);
  7735. sockaddr_in cli_addr{};
  7736. socklen_t cli_len = sizeof(cli_addr);
  7737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7738. if (cli != INVALID_SOCKET) {
  7739. char buf[4096];
  7740. ::recv(cli, buf, sizeof(buf), 0);
  7741. auto content_length = std::to_string(DATA_SIZE);
  7742. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7743. "Content-Length: " +
  7744. content_length +
  7745. "\r\n"
  7746. "Connection: close\r\n"
  7747. "\r\n";
  7748. ::send(cli,
  7749. #ifdef _WIN32
  7750. static_cast<const char *>(response_header.c_str()),
  7751. static_cast<int>(response_header.size()),
  7752. #else
  7753. response_header.c_str(), response_header.size(),
  7754. #endif
  7755. 0);
  7756. std::string chunk(64 * 1024, 'A');
  7757. size_t total_sent = 0;
  7758. while (total_sent < DATA_SIZE) {
  7759. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7760. auto sent = ::send(cli,
  7761. #ifdef _WIN32
  7762. static_cast<const char *>(chunk.c_str()),
  7763. static_cast<int>(to_send),
  7764. #else
  7765. chunk.c_str(), to_send,
  7766. #endif
  7767. 0);
  7768. if (sent <= 0) break;
  7769. total_sent += static_cast<size_t>(sent);
  7770. }
  7771. #ifdef _WIN32
  7772. ::shutdown(cli, SD_SEND);
  7773. #else
  7774. ::shutdown(cli, SHUT_WR);
  7775. #endif
  7776. char drain[1024];
  7777. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7778. detail::close_socket(cli);
  7779. }
  7780. detail::close_socket(srv);
  7781. });
  7782. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7783. size_t total_received = 0;
  7784. {
  7785. Client cli("127.0.0.1", PORT + 2);
  7786. cli.set_read_timeout(10, 0);
  7787. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7788. auto res =
  7789. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7790. total_received += data_length;
  7791. return true;
  7792. });
  7793. ASSERT_TRUE(res);
  7794. EXPECT_EQ(StatusCode::OK_200, res->status);
  7795. }
  7796. server_thread.join();
  7797. EXPECT_EQ(total_received, DATA_SIZE)
  7798. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7799. << " bytes (larger than " << DATA_SIZE
  7800. << " bytes response), content_receiver should read all data, but only "
  7801. "read "
  7802. << total_received << " bytes.";
  7803. }
  7804. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7805. // Regression test for "zip bomb" attack on the client side: a malicious server
  7806. // sends a small gzip-compressed response that decompresses to a huge payload.
  7807. // The client must enforce payload_max_length on the decompressed size.
  7808. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7809. constexpr size_t DECOMPRESSED_SIZE =
  7810. 10 * 1024 * 1024; // 10MB after decompression
  7811. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7812. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7813. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7814. std::string compressed;
  7815. {
  7816. httplib::detail::gzip_compressor compressor;
  7817. bool ok =
  7818. compressor.compress(uncompressed.data(), uncompressed.size(),
  7819. /*last=*/true, [&](const char *buf, size_t len) {
  7820. compressed.append(buf, len);
  7821. return true;
  7822. });
  7823. ASSERT_TRUE(ok);
  7824. }
  7825. // Sanity: compressed data should be much smaller than the decompressed size
  7826. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7827. #ifndef _WIN32
  7828. signal(SIGPIPE, SIG_IGN);
  7829. #endif
  7830. // Set up the listening socket in the main thread so the server is guaranteed
  7831. // to be ready before the client connects (eliminates race condition).
  7832. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7833. default_socket_options(srv);
  7834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7836. sockaddr_in addr{};
  7837. addr.sin_family = AF_INET;
  7838. addr.sin_port = htons(PORT + 3);
  7839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7840. int opt = 1;
  7841. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7842. #ifdef _WIN32
  7843. reinterpret_cast<const char *>(&opt),
  7844. #else
  7845. &opt,
  7846. #endif
  7847. sizeof(opt));
  7848. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7849. ASSERT_EQ(0, ::listen(srv, 1));
  7850. auto server_thread = std::thread([&compressed, srv] {
  7851. sockaddr_in cli_addr{};
  7852. socklen_t cli_len = sizeof(cli_addr);
  7853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7854. if (cli != INVALID_SOCKET) {
  7855. // Read the full HTTP request (until \r\n\r\n)
  7856. char buf[4096];
  7857. size_t total = 0;
  7858. while (total < sizeof(buf)) {
  7859. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7860. if (n <= 0) break;
  7861. total += static_cast<size_t>(n);
  7862. // Check for end of headers
  7863. if (total >= 4) {
  7864. std::string req(buf, total);
  7865. if (req.find("\r\n\r\n") != std::string::npos) break;
  7866. }
  7867. }
  7868. // Malicious response: gzip-compressed body, no Content-Length
  7869. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7870. "Content-Encoding: gzip\r\n"
  7871. "Connection: close\r\n"
  7872. "\r\n";
  7873. ::send(cli,
  7874. #ifdef _WIN32
  7875. static_cast<const char *>(response_header.c_str()),
  7876. static_cast<int>(response_header.size()),
  7877. #else
  7878. response_header.c_str(), response_header.size(),
  7879. #endif
  7880. 0);
  7881. // Send the compressed payload (small on the wire, huge when decompressed)
  7882. size_t total_sent = 0;
  7883. while (total_sent < compressed.size()) {
  7884. auto to_send = std::min(compressed.size() - total_sent,
  7885. static_cast<size_t>(64 * 1024));
  7886. auto sent =
  7887. ::send(cli,
  7888. #ifdef _WIN32
  7889. static_cast<const char *>(compressed.c_str() + total_sent),
  7890. static_cast<int>(to_send),
  7891. #else
  7892. compressed.c_str() + total_sent, to_send,
  7893. #endif
  7894. 0);
  7895. if (sent <= 0) break;
  7896. total_sent += static_cast<size_t>(sent);
  7897. }
  7898. detail::close_socket(cli);
  7899. }
  7900. });
  7901. auto se = detail::scope_exit([&] {
  7902. detail::close_socket(srv);
  7903. server_thread.join();
  7904. });
  7905. size_t total_decompressed = 0;
  7906. {
  7907. Client cli("127.0.0.1", PORT + 3);
  7908. cli.set_read_timeout(5, 0);
  7909. cli.set_decompress(true);
  7910. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7911. auto stream = cli.open_stream("GET", "/zipbomb");
  7912. ASSERT_TRUE(stream.is_valid());
  7913. char buffer[64 * 1024];
  7914. ssize_t n;
  7915. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7916. total_decompressed += static_cast<size_t>(n);
  7917. }
  7918. }
  7919. // The decompressed size must be capped by payload_max_length. Without
  7920. // protection, the client would decompress the full 10MB from a tiny
  7921. // compressed payload, enabling a zip bomb DoS attack.
  7922. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7923. << "Client decompressed " << total_decompressed
  7924. << " bytes from a gzip response. The decompressed size should be "
  7925. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7926. }
  7927. #endif
  7928. TEST(HostAndPortPropertiesTest, NoSSL) {
  7929. httplib::Client cli("www.google.com", 1234);
  7930. ASSERT_EQ("www.google.com", cli.host());
  7931. ASSERT_EQ(1234, cli.port());
  7932. }
  7933. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7934. httplib::Client cli("www.google.com:1234");
  7935. ASSERT_EQ("www.google.com", cli.host());
  7936. ASSERT_EQ(1234, cli.port());
  7937. }
  7938. #ifdef CPPHTTPLIB_SSL_ENABLED
  7939. TEST(HostAndPortPropertiesTest, SSL) {
  7940. httplib::SSLClient cli("www.google.com");
  7941. ASSERT_EQ("www.google.com", cli.host());
  7942. ASSERT_EQ(443, cli.port());
  7943. }
  7944. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7945. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7946. std::string cert;
  7947. read_file(CA_CERT_FILE, cert);
  7948. httplib::SSLClient httplib_client("www.google.com");
  7949. // Load CA store first time
  7950. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7951. // Load CA store second time (update)
  7952. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7953. // Verify client is still valid and can make connections
  7954. httplib_client.enable_server_certificate_verification(true);
  7955. auto res = httplib_client.Get("/");
  7956. ASSERT_TRUE(res);
  7957. // Google may return 200 or 301 depending on various factors
  7958. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7959. res->status == StatusCode::MovedPermanently_301);
  7960. }
  7961. TEST(SSLClientTest, ServerNameIndication_Online) {
  7962. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7963. auto host = "httpcan.org";
  7964. auto path = std::string{"/get"};
  7965. #else
  7966. auto host = "nghttp2.org";
  7967. auto path = std::string{"/httpbin/get"};
  7968. #endif
  7969. SSLClient cli(host, 443);
  7970. auto res = cli.Get(path);
  7971. ASSERT_TRUE(res);
  7972. ASSERT_EQ(StatusCode::OK_200, res->status);
  7973. }
  7974. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7975. // Use a site that will cause SSL verification failure due to self-signed cert
  7976. SSLClient cli("self-signed.badssl.com", 443);
  7977. cli.enable_server_certificate_verification(true);
  7978. auto res = cli.Get("/");
  7979. ASSERT_TRUE(!res);
  7980. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7981. // Verify backend error is captured for SSLServerVerification
  7982. // This occurs when certificate verification fails
  7983. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7984. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7985. EXPECT_NE(0UL, res.ssl_backend_error());
  7986. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7987. // For OpenSSL, ssl_error is 0 for verification errors
  7988. EXPECT_EQ(0, res.ssl_error());
  7989. #if !defined(_WIN32) || \
  7990. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7991. // On non-Windows or when Windows Schannel is disabled, the error comes
  7992. // from OpenSSL's verification
  7993. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7994. res.ssl_backend_error());
  7995. #endif
  7996. #endif
  7997. }
  7998. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7999. // Use a site where hostname doesn't match the certificate
  8000. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8001. SSLClient cli("wrong.host.badssl.com", 443);
  8002. cli.enable_server_certificate_verification(true);
  8003. cli.enable_server_hostname_verification(true);
  8004. auto res = cli.Get("/");
  8005. ASSERT_TRUE(!res);
  8006. // The error type depends on when hostname verification occurs:
  8007. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8008. // - Mbed TLS: SSLServerVerification (during handshake)
  8009. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8010. res.error() == Error::SSLServerVerification);
  8011. // Verify backend error is captured for hostname verification failure
  8012. EXPECT_NE(0UL, res.ssl_backend_error());
  8013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8014. // For OpenSSL, ssl_error is 0 for verification errors
  8015. EXPECT_EQ(0, res.ssl_error());
  8016. #if !defined(_WIN32) || \
  8017. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8018. // On non-Windows or when Windows Schannel is disabled, the error comes
  8019. // from OpenSSL's hostname verification
  8020. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8021. res.ssl_backend_error());
  8022. #endif
  8023. #endif
  8024. }
  8025. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8026. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8027. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8028. SSLClient cli("www.google.com", 443);
  8029. cli.enable_server_certificate_verification(true);
  8030. auto res = cli.Get("/");
  8031. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8032. }
  8033. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8034. SSLClient cli("www.google.com", 443);
  8035. cli.enable_server_certificate_verification(true);
  8036. cli.enable_windows_certificate_verification(false);
  8037. auto res = cli.Get("/");
  8038. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8039. }
  8040. #endif
  8041. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8042. Client cli("https://google.com");
  8043. auto res = cli.Get("/");
  8044. ASSERT_TRUE(res);
  8045. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8046. }
  8047. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8048. SSLClient cli("google.com");
  8049. cli.set_ca_cert_path(CA_CERT_FILE);
  8050. auto res = cli.Get("/");
  8051. ASSERT_TRUE(res);
  8052. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8053. }
  8054. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8055. SSLClient cli("google.com");
  8056. cli.enable_server_certificate_verification(true);
  8057. cli.set_ca_cert_path("hello");
  8058. auto res = cli.Get("/");
  8059. ASSERT_TRUE(!res);
  8060. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8061. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8062. // should be set
  8063. EXPECT_EQ(0, res.ssl_error());
  8064. // Verify backend error is captured for SSLLoadingCerts
  8065. // This error occurs when loading CA certificates fails
  8066. EXPECT_NE(0UL, res.ssl_backend_error());
  8067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8068. // OpenSSL specific error codes:
  8069. // > openssl errstr 0x80000002
  8070. // error:80000002:system library::No such file or directory
  8071. // > openssl errstr 0xA000126
  8072. // error:0A000126:SSL routines::unexpected eof while reading
  8073. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8074. res.ssl_backend_error() == 0xA000126);
  8075. #endif
  8076. }
  8077. TEST(SSLClientTest, ServerCertificateVerification4) {
  8078. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8079. ASSERT_TRUE(svr.is_valid());
  8080. svr.Get("/test", [&](const Request &, Response &res) {
  8081. res.set_content("test", "text/plain");
  8082. svr.stop();
  8083. ASSERT_TRUE(true);
  8084. });
  8085. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8086. auto se = detail::scope_exit([&] {
  8087. t.join();
  8088. ASSERT_FALSE(svr.is_running());
  8089. });
  8090. svr.wait_until_ready();
  8091. SSLClient cli("127.0.0.1", PORT);
  8092. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8093. cli.enable_server_certificate_verification(true);
  8094. cli.set_connection_timeout(30);
  8095. auto res = cli.Get("/test");
  8096. ASSERT_TRUE(res);
  8097. ASSERT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8100. std::string cert;
  8101. read_file(CA_CERT_FILE, cert);
  8102. SSLClient cli("google.com");
  8103. cli.load_ca_cert_store(cert.data(), cert.size());
  8104. const auto res = cli.Get("/");
  8105. ASSERT_TRUE(res);
  8106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8107. }
  8108. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8109. // clang-format off
  8110. static constexpr char cert[] =
  8111. "GlobalSign Root CA\n"
  8112. "==================\n"
  8113. "-----BEGIN CERTIFICATE-----\n"
  8114. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8115. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8116. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8117. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8118. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8119. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8120. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8121. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8122. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8123. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8124. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8125. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8126. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8127. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8128. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8129. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8130. "-----END CERTIFICATE-----\n";
  8131. // clang-format on
  8132. SSLClient cli("google.com");
  8133. cli.load_ca_cert_store(cert, sizeof(cert));
  8134. const auto res = cli.Get("/");
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8137. }
  8138. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8139. SSLClient cli("www.youtube.com");
  8140. cli.set_ca_cert_path(CA_CERT_FILE);
  8141. cli.enable_server_certificate_verification(true);
  8142. cli.set_follow_location(true);
  8143. auto res = cli.Get("/");
  8144. ASSERT_TRUE(res);
  8145. ASSERT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8148. SSLClient cli("wWw.YouTube.Com");
  8149. cli.set_ca_cert_path(CA_CERT_FILE);
  8150. cli.enable_server_certificate_verification(true);
  8151. cli.enable_server_hostname_verification(true);
  8152. cli.set_follow_location(true);
  8153. auto res = cli.Get("/");
  8154. ASSERT_TRUE(res);
  8155. ASSERT_EQ(StatusCode::OK_200, res->status);
  8156. }
  8157. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8158. SSLClient cli("gOoGlE.COm");
  8159. cli.enable_server_certificate_verification(true);
  8160. cli.enable_server_hostname_verification(true);
  8161. cli.set_follow_location(true);
  8162. auto res = cli.Get("/");
  8163. ASSERT_TRUE(res);
  8164. ASSERT_EQ(StatusCode::OK_200, res->status);
  8165. }
  8166. TEST(SSLClientTest, Issue2004_Online) {
  8167. Client client("https://google.com");
  8168. client.set_follow_location(true);
  8169. auto res = client.Get("/");
  8170. ASSERT_TRUE(res);
  8171. ASSERT_EQ(StatusCode::OK_200, res->status);
  8172. auto body = res->body;
  8173. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8174. }
  8175. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8176. // Create SSLClient with invalid cert/key to make is_valid() return false
  8177. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8178. "nonexistent_key.pem");
  8179. // is_valid() should be false due to cert loading failure
  8180. ASSERT_FALSE(cli.is_valid());
  8181. auto res = cli.Get("/");
  8182. ASSERT_FALSE(res);
  8183. EXPECT_EQ(Error::SSLConnection, res.error());
  8184. }
  8185. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8186. // Test for Issue #2251: SSL error not properly reported when client cert
  8187. // and key paths are swapped or mismatched
  8188. // This simulates the scenario where user accidentally swaps the cert and key
  8189. // files
  8190. // Using client cert file as private key and vice versa (completely wrong)
  8191. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8192. // Should fail validation due to cert/key mismatch
  8193. ASSERT_FALSE(cli.is_valid());
  8194. // Attempt to make a request should fail with proper error
  8195. auto res = cli.Get("/");
  8196. ASSERT_FALSE(res);
  8197. EXPECT_EQ(Error::SSLConnection, res.error());
  8198. // SSL error should be recorded in the Result object (this is the key fix for
  8199. // Issue #2251)
  8200. auto backend_error = res.ssl_backend_error();
  8201. EXPECT_NE(0u, backend_error);
  8202. }
  8203. // Tests cert/key mismatch detection at the TLS context level
  8204. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8205. // Test that using mismatched cert/key causes connection failure.
  8206. // We verify this at the SSLClient level rather than through internal
  8207. // TLS API functions.
  8208. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8209. cli.enable_server_certificate_verification(false);
  8210. cli.set_connection_timeout(2);
  8211. // The mismatch should cause a connection or handshake error
  8212. auto res = cli.Get("/test");
  8213. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8214. // Either way, the request should fail
  8215. EXPECT_FALSE(res);
  8216. }
  8217. #endif
  8218. #if 0
  8219. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8220. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8221. ASSERT_TRUE(cli != nullptr);
  8222. cli->set_address_family(AF_INET6);
  8223. cli->set_interface("en0");
  8224. auto res = cli->Get("/get");
  8225. ASSERT_TRUE(res);
  8226. ASSERT_EQ(StatusCode::OK_200, res->status);
  8227. }
  8228. #endif
  8229. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8230. #ifdef CPPHTTPLIB_SSL_ENABLED
  8231. void ClientCertPresent(
  8232. const std::string &client_cert_file,
  8233. const std::string &client_private_key_file,
  8234. const std::string &client_encrypted_private_key_pass = std::string()) {
  8235. using namespace httplib::tls;
  8236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8237. CLIENT_CA_CERT_DIR);
  8238. ASSERT_TRUE(svr.is_valid());
  8239. svr.Get("/test", [&](const Request &req, Response &res) {
  8240. res.set_content("test", "text/plain");
  8241. auto cert = req.peer_cert();
  8242. ASSERT_TRUE(static_cast<bool>(cert));
  8243. std::string common_name = cert.subject_cn();
  8244. EXPECT_EQ("Common Name", common_name);
  8245. });
  8246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8247. auto se = detail::scope_exit([&] {
  8248. svr.stop();
  8249. t.join();
  8250. ASSERT_FALSE(svr.is_running());
  8251. });
  8252. svr.wait_until_ready();
  8253. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8254. client_encrypted_private_key_pass);
  8255. cli.enable_server_certificate_verification(false);
  8256. cli.set_connection_timeout(30);
  8257. auto res = cli.Get("/test");
  8258. ASSERT_TRUE(res);
  8259. ASSERT_EQ(StatusCode::OK_200, res->status);
  8260. }
  8261. TEST(SSLClientServerTest, ClientCertPresent) {
  8262. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8263. }
  8264. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8265. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8266. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8267. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8268. }
  8269. // PEM memory-based constructor tests (works with all TLS backends)
  8270. void PemMemoryClientCertPresent(
  8271. const std::string &client_cert_file,
  8272. const std::string &client_private_key_file,
  8273. const std::string &client_encrypted_private_key_pass = std::string()) {
  8274. // Read PEM files into memory
  8275. std::string server_cert_pem, server_key_pem;
  8276. std::string client_ca_pem;
  8277. std::string client_cert_pem, client_key_pem;
  8278. read_file(SERVER_CERT_FILE, server_cert_pem);
  8279. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8280. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8281. read_file(client_cert_file, client_cert_pem);
  8282. read_file(client_private_key_file, client_key_pem);
  8283. // Create server with PEM memory
  8284. SSLServer::PemMemory server_pem = {
  8285. server_cert_pem.c_str(),
  8286. server_cert_pem.size(),
  8287. server_key_pem.c_str(),
  8288. server_key_pem.size(),
  8289. client_ca_pem.c_str(),
  8290. client_ca_pem.size(),
  8291. nullptr // no password for server key
  8292. };
  8293. SSLServer svr(server_pem);
  8294. ASSERT_TRUE(svr.is_valid());
  8295. svr.Get("/test", [&](const Request &, Response &res) {
  8296. res.set_content("test", "text/plain");
  8297. });
  8298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8299. auto se = detail::scope_exit([&] {
  8300. svr.stop();
  8301. t.join();
  8302. ASSERT_FALSE(svr.is_running());
  8303. });
  8304. svr.wait_until_ready();
  8305. // Create client with PEM memory
  8306. const char *password = client_encrypted_private_key_pass.empty()
  8307. ? nullptr
  8308. : client_encrypted_private_key_pass.c_str();
  8309. SSLClient::PemMemory client_pem = {
  8310. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8311. client_key_pem.size(), password};
  8312. SSLClient cli(HOST, PORT, client_pem);
  8313. cli.enable_server_certificate_verification(false);
  8314. cli.set_connection_timeout(30);
  8315. auto res = cli.Get("/test");
  8316. ASSERT_TRUE(res);
  8317. ASSERT_EQ(StatusCode::OK_200, res->status);
  8318. }
  8319. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8320. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8321. }
  8322. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8323. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8324. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8325. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8326. }
  8327. TEST(SSLClientServerTest, ClientCertMissing) {
  8328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8329. CLIENT_CA_CERT_DIR);
  8330. ASSERT_TRUE(svr.is_valid());
  8331. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8332. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8333. auto se = detail::scope_exit([&] {
  8334. svr.stop();
  8335. t.join();
  8336. ASSERT_FALSE(svr.is_running());
  8337. });
  8338. svr.wait_until_ready();
  8339. SSLClient cli(HOST, PORT);
  8340. cli.set_connection_timeout(30);
  8341. auto res = cli.Get("/test");
  8342. ASSERT_TRUE(!res);
  8343. // When client cert is missing and server requires it, connection fails
  8344. // Error type depends on backend implementation
  8345. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8346. res.error() == Error::SSLConnection);
  8347. // Verify backend error is captured
  8348. // Note: This test may have different error codes depending on the exact
  8349. // verification failure
  8350. EXPECT_NE(0UL, res.ssl_backend_error());
  8351. }
  8352. TEST(SSLClientServerTest, TrustDirOptional) {
  8353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8354. ASSERT_TRUE(svr.is_valid());
  8355. svr.Get("/test", [&](const Request &, Response &res) {
  8356. res.set_content("test", "text/plain");
  8357. });
  8358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8366. cli.enable_server_certificate_verification(false);
  8367. cli.set_connection_timeout(30);
  8368. auto res = cli.Get("/test");
  8369. ASSERT_TRUE(res);
  8370. ASSERT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8373. class NoListenSSLServer : public SSLServer {
  8374. public:
  8375. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8376. const char *client_ca_cert_file_path,
  8377. const char *client_ca_cert_dir_path = nullptr)
  8378. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8379. client_ca_cert_dir_path),
  8380. stop_(false) {}
  8381. std::atomic_bool stop_;
  8382. private:
  8383. bool process_and_close_socket(socket_t /*sock*/) override {
  8384. // Don't create SSL context
  8385. while (!stop_.load()) {
  8386. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8387. }
  8388. return true;
  8389. }
  8390. };
  8391. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8392. CLIENT_CA_CERT_FILE);
  8393. ASSERT_TRUE(svr.is_valid());
  8394. svr.Get("/test", [&](const Request &, Response &res) {
  8395. res.set_content("test", "text/plain");
  8396. });
  8397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8398. auto se = detail::scope_exit([&] {
  8399. svr.stop_ = true;
  8400. svr.stop();
  8401. t.join();
  8402. ASSERT_FALSE(svr.is_running());
  8403. });
  8404. svr.wait_until_ready();
  8405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8406. cli.enable_server_certificate_verification(false);
  8407. cli.set_connection_timeout(1);
  8408. auto res = cli.Get("/test");
  8409. ASSERT_TRUE(!res);
  8410. EXPECT_EQ(Error::SSLConnection, res.error());
  8411. // Timeout results in WantRead error code (maps to backend-specific value)
  8412. EXPECT_NE(0, res.ssl_error());
  8413. }
  8414. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8415. // Test SSLServer with client certificate verification using the standard
  8416. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8418. CLIENT_CA_CERT_DIR);
  8419. ASSERT_TRUE(svr.is_valid());
  8420. svr.Get("/test", [&](const Request &req, Response &res) {
  8421. res.set_content("test", "text/plain");
  8422. auto cert = req.peer_cert();
  8423. ASSERT_TRUE(static_cast<bool>(cert));
  8424. auto common_name = cert.subject_cn();
  8425. EXPECT_EQ("Common Name", common_name);
  8426. });
  8427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8428. auto se = detail::scope_exit([&] {
  8429. svr.stop();
  8430. t.join();
  8431. ASSERT_FALSE(svr.is_running());
  8432. });
  8433. svr.wait_until_ready();
  8434. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8435. cli.enable_server_certificate_verification(false);
  8436. cli.set_connection_timeout(30);
  8437. auto res = cli.Get("/test");
  8438. ASSERT_TRUE(res);
  8439. ASSERT_EQ(StatusCode::OK_200, res->status);
  8440. }
  8441. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8442. // Verifies that wildcard matching and exact matching work consistently
  8443. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8444. using namespace httplib::tls;
  8445. // We need a running server to test against
  8446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8447. ASSERT_TRUE(svr.is_valid());
  8448. svr.Get("/test", [](const Request &, Response &res) {
  8449. res.set_content("ok", "text/plain");
  8450. });
  8451. thread t([&]() { svr.listen(HOST, PORT); });
  8452. auto se = detail::scope_exit([&] {
  8453. svr.stop();
  8454. t.join();
  8455. });
  8456. svr.wait_until_ready();
  8457. bool verify_callback_called = false;
  8458. bool verify_result_wrong = false;
  8459. SSLClient cli(HOST, PORT);
  8460. cli.enable_server_certificate_verification(true);
  8461. cli.set_ca_cert_path(CA_CERT_FILE);
  8462. cli.set_connection_timeout(5);
  8463. // Note: Test certificate has CN="Common Name", not "localhost"
  8464. bool verify_result_cn = false;
  8465. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8466. verify_callback_called = true;
  8467. if (!ctx.cert) return false;
  8468. // Test 1: "Common Name" should match (our test server cert CN)
  8469. verify_result_cn = ctx.check_hostname("Common Name");
  8470. // Test 2: wrong hostname should not match
  8471. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8472. return true; // Accept for the purpose of this test
  8473. });
  8474. auto res = cli.Get("/test");
  8475. // The request may succeed or fail depending on cert configuration
  8476. // but the callback should have been called
  8477. ASSERT_TRUE(verify_callback_called)
  8478. << "Verify callback should have been called";
  8479. // CN="Common Name" should match our test certificate
  8480. EXPECT_TRUE(verify_result_cn)
  8481. << "verify_hostname should match 'Common Name' (certificate CN)";
  8482. // Wrong hostname should not match
  8483. EXPECT_FALSE(verify_result_wrong)
  8484. << "verify_hostname should not match 'wronghost.example.com'";
  8485. }
  8486. #endif
  8487. // mbedTLS-specific callback constructor test
  8488. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8489. #ifdef CPPHTTPLIB_SSL_ENABLED
  8490. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8492. ASSERT_TRUE(svr.is_valid());
  8493. // Set up a handler to verify client certificate is present
  8494. bool client_cert_verified = false;
  8495. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8496. // Verify that client certificate was provided
  8497. client_cert_verified = true;
  8498. res.set_content("success", "text/plain");
  8499. });
  8500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8501. auto se = detail::scope_exit([&] {
  8502. svr.stop();
  8503. t.join();
  8504. ASSERT_FALSE(svr.is_running());
  8505. });
  8506. svr.wait_until_ready();
  8507. // Client with certificate
  8508. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8509. cli.enable_server_certificate_verification(false);
  8510. cli.set_connection_timeout(30);
  8511. auto res = cli.Get("/test");
  8512. ASSERT_TRUE(res);
  8513. ASSERT_EQ(StatusCode::OK_200, res->status);
  8514. ASSERT_TRUE(client_cert_verified);
  8515. EXPECT_EQ("success", res->body);
  8516. }
  8517. #endif
  8518. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8519. // backends
  8520. #ifdef CPPHTTPLIB_SSL_ENABLED
  8521. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8522. using namespace httplib::tls;
  8523. // Test that when client CA cert file is provided,
  8524. // the server properly requests and validates client certificates
  8525. // Create a server with client authentication
  8526. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8527. ASSERT_TRUE(svr.is_valid());
  8528. bool handler_called = false;
  8529. svr.Get("/test", [&](const Request &req, Response &res) {
  8530. handler_called = true;
  8531. // Verify that a client certificate was provided
  8532. auto cert = req.peer_cert();
  8533. ASSERT_TRUE(static_cast<bool>(cert));
  8534. // Get the issuer name
  8535. std::string issuer_str = cert.issuer_name();
  8536. ASSERT_FALSE(issuer_str.empty());
  8537. // The client certificate should be issued by our test CA
  8538. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8539. res.set_content("authenticated", "text/plain");
  8540. });
  8541. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8542. auto se = detail::scope_exit([&] {
  8543. svr.stop();
  8544. t.join();
  8545. ASSERT_FALSE(svr.is_running());
  8546. });
  8547. svr.wait_until_ready();
  8548. // Connect with a client certificate issued by the CA
  8549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8550. cli.enable_server_certificate_verification(false);
  8551. cli.set_connection_timeout(30);
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. ASSERT_TRUE(handler_called);
  8556. EXPECT_EQ("authenticated", res->body);
  8557. }
  8558. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8559. using namespace httplib::tls;
  8560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8561. ASSERT_TRUE(svr.is_valid());
  8562. svr.Get("/test", [](const Request &, Response &res) {
  8563. res.set_content("ok", "text/plain");
  8564. });
  8565. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8566. auto se = detail::scope_exit([&] {
  8567. svr.stop();
  8568. t.join();
  8569. });
  8570. svr.wait_until_ready();
  8571. SSLClient cli(HOST, PORT);
  8572. cli.enable_server_certificate_verification(false);
  8573. cli.set_connection_timeout(30);
  8574. bool cert_checked = false;
  8575. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8576. if (ctx.cert) {
  8577. auto sans = ctx.sans();
  8578. // Test certificate may or may not have SANs - just verify the API
  8579. // works If SANs exist, verify the types are valid
  8580. for (const auto &san : sans) {
  8581. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8582. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8583. san.type == SanType::OTHER);
  8584. EXPECT_FALSE(san.value.empty());
  8585. }
  8586. cert_checked = true;
  8587. }
  8588. return true;
  8589. });
  8590. auto res = cli.Get("/test");
  8591. ASSERT_TRUE(res);
  8592. EXPECT_TRUE(cert_checked);
  8593. }
  8594. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8595. using namespace httplib::tls;
  8596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8597. ASSERT_TRUE(svr.is_valid());
  8598. svr.Get("/test", [](const Request &, Response &res) {
  8599. res.set_content("ok", "text/plain");
  8600. });
  8601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8602. auto se = detail::scope_exit([&] {
  8603. svr.stop();
  8604. t.join();
  8605. });
  8606. svr.wait_until_ready();
  8607. SSLClient cli(HOST, PORT);
  8608. cli.enable_server_certificate_verification(false);
  8609. cli.set_connection_timeout(30);
  8610. bool validity_checked = false;
  8611. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8612. if (ctx.cert) {
  8613. time_t not_before = 0, not_after = 0;
  8614. bool result = ctx.validity(not_before, not_after);
  8615. EXPECT_TRUE(result);
  8616. // Verify that not_before < now < not_after for a valid cert
  8617. time_t now = time(nullptr);
  8618. EXPECT_LT(not_before, now);
  8619. EXPECT_GT(not_after, now);
  8620. validity_checked = true;
  8621. }
  8622. return true;
  8623. });
  8624. auto res = cli.Get("/test");
  8625. ASSERT_TRUE(res);
  8626. EXPECT_TRUE(validity_checked);
  8627. }
  8628. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8629. using namespace httplib::tls;
  8630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8631. ASSERT_TRUE(svr.is_valid());
  8632. svr.Get("/test", [](const Request &, Response &res) {
  8633. res.set_content("ok", "text/plain");
  8634. });
  8635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8636. auto se = detail::scope_exit([&] {
  8637. svr.stop();
  8638. t.join();
  8639. });
  8640. svr.wait_until_ready();
  8641. SSLClient cli(HOST, PORT);
  8642. cli.enable_server_certificate_verification(false);
  8643. cli.set_connection_timeout(30);
  8644. bool serial_checked = false;
  8645. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8646. if (ctx.cert) {
  8647. std::string serial = ctx.serial();
  8648. EXPECT_FALSE(serial.empty());
  8649. // Serial should be a hex string
  8650. for (char c : serial) {
  8651. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8652. (c >= 'a' && c <= 'f'));
  8653. }
  8654. serial_checked = true;
  8655. }
  8656. return true;
  8657. });
  8658. auto res = cli.Get("/test");
  8659. ASSERT_TRUE(res);
  8660. EXPECT_TRUE(serial_checked);
  8661. }
  8662. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8663. // Test 1: Valid CA file - no error should be recorded
  8664. {
  8665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8666. CLIENT_CA_CERT_FILE);
  8667. ASSERT_TRUE(svr.is_valid());
  8668. // With valid setup, last_ssl_error should be 0
  8669. EXPECT_EQ(0, svr.ssl_last_error());
  8670. }
  8671. // Test 2: Invalid CA file content
  8672. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8673. {
  8674. // Create a temporary file with completely invalid content
  8675. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8676. {
  8677. std::ofstream ofs(temp_invalid_ca);
  8678. ofs << "This is not a certificate file at all\n";
  8679. ofs << "Just plain text content\n";
  8680. }
  8681. // Create server with invalid CA file
  8682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8683. // Clean up temporary file
  8684. std::remove(temp_invalid_ca);
  8685. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8686. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8687. // Note: SSL_CTX_load_verify_locations typically fails first,
  8688. // but our error handling code path is still exercised
  8689. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8690. }
  8691. }
  8692. TEST(VerifyCallbackTest, VerifyContextFields) {
  8693. using namespace httplib::tls;
  8694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8695. ASSERT_TRUE(svr.is_valid());
  8696. svr.Get("/test", [](const Request &, Response &res) {
  8697. res.set_content("ok", "text/plain");
  8698. });
  8699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8700. auto se = detail::scope_exit([&] {
  8701. svr.stop();
  8702. t.join();
  8703. });
  8704. svr.wait_until_ready();
  8705. SSLClient cli(HOST, PORT);
  8706. cli.enable_server_certificate_verification(false);
  8707. cli.set_connection_timeout(30);
  8708. int callback_count = 0;
  8709. bool saw_leaf_cert = false;
  8710. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8711. if (ctx.cert) {
  8712. callback_count++;
  8713. // We should see at least one certificate (the leaf)
  8714. std::string cn = ctx.subject_cn();
  8715. if (!cn.empty()) { saw_leaf_cert = true; }
  8716. // Verify context fields are populated
  8717. EXPECT_NE(ctx.session, nullptr);
  8718. EXPECT_GE(ctx.depth, 0);
  8719. }
  8720. return true;
  8721. });
  8722. auto res = cli.Get("/test");
  8723. ASSERT_TRUE(res);
  8724. EXPECT_GT(callback_count, 0);
  8725. EXPECT_TRUE(saw_leaf_cert);
  8726. }
  8727. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8728. using httplib::tls::TlsError;
  8729. // Test that verify_error_to_string returns empty for success
  8730. std::string success_str = TlsError::verify_error_to_string(0);
  8731. EXPECT_TRUE(success_str.empty());
  8732. // Test that verify_error_to_string returns non-empty for error codes
  8733. // Using a common error code (certificate expired)
  8734. std::string error_str =
  8735. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8736. EXPECT_FALSE(error_str.empty());
  8737. }
  8738. TEST(SessionVerifierTest, CertificateAccepted) {
  8739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8740. ASSERT_TRUE(svr.is_valid());
  8741. svr.Get("/test", [](const Request &, Response &res) {
  8742. res.set_content("ok", "text/plain");
  8743. });
  8744. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8745. auto se = detail::scope_exit([&] {
  8746. svr.stop();
  8747. t.join();
  8748. });
  8749. svr.wait_until_ready();
  8750. SSLClient cli(HOST, PORT);
  8751. cli.enable_server_certificate_verification(false);
  8752. cli.set_connection_timeout(30);
  8753. bool callback_called = false;
  8754. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8755. EXPECT_NE(session, nullptr);
  8756. callback_called = true;
  8757. return SSLVerifierResponse::CertificateAccepted;
  8758. });
  8759. auto res = cli.Get("/test");
  8760. ASSERT_TRUE(res);
  8761. EXPECT_EQ(200, res->status);
  8762. EXPECT_TRUE(callback_called);
  8763. }
  8764. TEST(SessionVerifierTest, CertificateRejected) {
  8765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8766. ASSERT_TRUE(svr.is_valid());
  8767. svr.Get("/test", [](const Request &, Response &res) {
  8768. res.set_content("ok", "text/plain");
  8769. });
  8770. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8771. auto se = detail::scope_exit([&] {
  8772. svr.stop();
  8773. t.join();
  8774. });
  8775. svr.wait_until_ready();
  8776. SSLClient cli(HOST, PORT);
  8777. cli.enable_server_certificate_verification(false);
  8778. cli.set_connection_timeout(30);
  8779. bool callback_called = false;
  8780. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8781. EXPECT_NE(session, nullptr);
  8782. callback_called = true;
  8783. return SSLVerifierResponse::CertificateRejected;
  8784. });
  8785. auto res = cli.Get("/test");
  8786. EXPECT_FALSE(res);
  8787. EXPECT_TRUE(callback_called);
  8788. }
  8789. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8791. ASSERT_TRUE(svr.is_valid());
  8792. svr.Get("/test", [](const Request &, Response &res) {
  8793. res.set_content("ok", "text/plain");
  8794. });
  8795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. t.join();
  8799. });
  8800. svr.wait_until_ready();
  8801. // NoDecisionMade with verification disabled should succeed (no default check)
  8802. SSLClient cli(HOST, PORT);
  8803. cli.enable_server_certificate_verification(false);
  8804. cli.set_connection_timeout(30);
  8805. bool callback_called = false;
  8806. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8807. EXPECT_NE(session, nullptr);
  8808. callback_called = true;
  8809. return SSLVerifierResponse::NoDecisionMade;
  8810. });
  8811. auto res = cli.Get("/test");
  8812. ASSERT_TRUE(res);
  8813. EXPECT_EQ(200, res->status);
  8814. EXPECT_TRUE(callback_called);
  8815. }
  8816. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8818. ASSERT_TRUE(svr.is_valid());
  8819. svr.Get("/test", [](const Request &, Response &res) {
  8820. res.set_content("ok", "text/plain");
  8821. });
  8822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8823. auto se = detail::scope_exit([&] {
  8824. svr.stop();
  8825. t.join();
  8826. });
  8827. svr.wait_until_ready();
  8828. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8829. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8830. // so we only check that the request fails, not whether the callback was
  8831. // called.
  8832. SSLClient cli(HOST, PORT);
  8833. cli.enable_server_certificate_verification(true);
  8834. cli.set_connection_timeout(30);
  8835. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8836. EXPECT_NE(session, nullptr);
  8837. return SSLVerifierResponse::NoDecisionMade;
  8838. });
  8839. auto res = cli.Get("/test");
  8840. EXPECT_FALSE(res);
  8841. }
  8842. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8843. // Test SSL server using PemMemory constructor with client CA certificates
  8844. // Read PEM files
  8845. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8846. read_file(SERVER_CERT_FILE, server_cert_pem);
  8847. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8848. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8849. // Create SSLServer with PemMemory constructor including client CA
  8850. SSLServer::PemMemory server_pem = {
  8851. server_cert_pem.c_str(),
  8852. server_cert_pem.size(),
  8853. server_key_pem.c_str(),
  8854. server_key_pem.size(),
  8855. client_ca_pem.c_str(),
  8856. client_ca_pem.size(),
  8857. nullptr // no password for server key
  8858. };
  8859. SSLServer svr(server_pem);
  8860. ASSERT_TRUE(svr.is_valid());
  8861. // No SSL error should be recorded for valid setup
  8862. EXPECT_EQ(0, svr.ssl_last_error());
  8863. // Set up server endpoints
  8864. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8865. res.set_content("ok", "text/plain");
  8866. });
  8867. // Start server in a thread
  8868. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8869. svr.wait_until_ready();
  8870. // Connect with client certificate (using constructor with paths)
  8871. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8872. cli.enable_server_certificate_verification(false);
  8873. auto res = cli.Get("/test-pem-ca");
  8874. ASSERT_TRUE(res);
  8875. EXPECT_EQ(200, res->status);
  8876. EXPECT_EQ("ok", res->body);
  8877. svr.stop();
  8878. server_thread.join();
  8879. }
  8880. #endif
  8881. #ifdef _WIN32
  8882. TEST(CleanupTest, WSACleanup) {
  8883. int ret = WSACleanup();
  8884. ASSERT_EQ(0, ret);
  8885. }
  8886. #endif
  8887. #ifndef CPPHTTPLIB_SSL_ENABLED
  8888. TEST(NoSSLSupport, SimpleInterface) {
  8889. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8890. }
  8891. #endif
  8892. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8893. TEST(InvalidScheme, SimpleInterface) {
  8894. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8895. }
  8896. #endif
  8897. TEST(NoScheme, SimpleInterface) {
  8898. Client cli("yahoo.com:80");
  8899. ASSERT_TRUE(cli.is_valid());
  8900. }
  8901. TEST(SendAPI, SimpleInterface_Online) {
  8902. Client cli("http://yahoo.com");
  8903. Request req;
  8904. req.method = "GET";
  8905. req.path = "/";
  8906. auto res = cli.send(req);
  8907. ASSERT_TRUE(res);
  8908. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8909. }
  8910. TEST(SendAPI, WithParamsInRequest) {
  8911. Server svr;
  8912. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8913. EXPECT_TRUE(req.has_param("test"));
  8914. EXPECT_EQ("test_value", req.get_param_value("test"));
  8915. });
  8916. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. Client cli(HOST, PORT);
  8924. {
  8925. Request req;
  8926. req.method = "GET";
  8927. req.path = "/";
  8928. req.params.emplace("test", "test_value");
  8929. auto res = cli.send(req);
  8930. ASSERT_TRUE(res);
  8931. }
  8932. {
  8933. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8934. ASSERT_TRUE(res);
  8935. }
  8936. }
  8937. TEST(ClientImplMethods, GetSocketTest) {
  8938. httplib::Server svr;
  8939. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8940. res.status = StatusCode::OK_200;
  8941. });
  8942. auto port = svr.bind_to_any_port("127.0.0.1");
  8943. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8944. auto se = detail::scope_exit([&] {
  8945. svr.stop();
  8946. thread.join();
  8947. ASSERT_FALSE(svr.is_running());
  8948. });
  8949. svr.wait_until_ready();
  8950. {
  8951. httplib::Client cli("127.0.0.1", port);
  8952. cli.set_keep_alive(true);
  8953. // Use the behavior of cpp-httplib of opening the connection
  8954. // only when the first request happens. If that changes,
  8955. // this test would be obsolete.
  8956. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8957. // This also implicitly tests the server. But other tests would fail much
  8958. // earlier than this one to be considered.
  8959. auto res = cli.Get("/");
  8960. ASSERT_TRUE(res);
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8963. }
  8964. }
  8965. // Disabled due to out-of-memory problem on GitHub Actions
  8966. #ifdef _WIN64
  8967. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8968. // allocate content size larger than 2GB in memory
  8969. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8970. char *content = (char *)malloc(content_size);
  8971. ASSERT_TRUE(content);
  8972. Server svr;
  8973. svr.Get("/foo",
  8974. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8975. res.set_content(content, content_size, "application/octet-stream");
  8976. });
  8977. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8978. auto se = detail::scope_exit([&] {
  8979. svr.stop();
  8980. listen_thread.join();
  8981. if (content) free(content);
  8982. ASSERT_FALSE(svr.is_running());
  8983. });
  8984. svr.wait_until_ready();
  8985. Client cli(HOST, PORT);
  8986. auto res = cli.Get("/foo");
  8987. ASSERT_TRUE(res);
  8988. EXPECT_EQ(StatusCode::OK_200, res->status);
  8989. EXPECT_EQ(content_size, res->body.length());
  8990. }
  8991. #endif
  8992. #ifdef CPPHTTPLIB_SSL_ENABLED
  8993. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8994. Client cli("http://yahoo.com");
  8995. auto res = cli.Get("/");
  8996. ASSERT_TRUE(res);
  8997. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8998. cli.set_follow_location(true);
  8999. res = cli.Get("/");
  9000. ASSERT_TRUE(res);
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9003. }
  9004. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9005. Client cli("https://yahoo.com");
  9006. auto res = cli.Get("/");
  9007. ASSERT_TRUE(res);
  9008. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9009. cli.set_follow_location(true);
  9010. res = cli.Get("/");
  9011. ASSERT_TRUE(res);
  9012. EXPECT_EQ(StatusCode::OK_200, res->status);
  9013. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9014. }
  9015. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9016. Client cli("https://yahoo.com");
  9017. auto res = cli.Get("/");
  9018. ASSERT_TRUE(res);
  9019. ASSERT_FALSE(!res);
  9020. ASSERT_TRUE(res);
  9021. ASSERT_FALSE(res == nullptr);
  9022. ASSERT_TRUE(res != nullptr);
  9023. EXPECT_EQ(Error::Success, res.error());
  9024. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9025. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9026. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9027. cli.set_follow_location(true);
  9028. res = cli.Get("/");
  9029. ASSERT_TRUE(res);
  9030. EXPECT_EQ(Error::Success, res.error());
  9031. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9032. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9033. EXPECT_EQ(StatusCode::OK_200, res->status);
  9034. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9035. }
  9036. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9037. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9038. Client cli("https://cdnjs.cloudflare.com");
  9039. auto res =
  9040. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9041. ASSERT_TRUE(res);
  9042. EXPECT_EQ(StatusCode::OK_200, res->status);
  9043. EXPECT_EQ(287630U, res->body.size());
  9044. EXPECT_EQ("application/javascript; charset=utf-8",
  9045. res->get_header_value("Content-Type"));
  9046. }
  9047. #endif
  9048. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9049. #undef REDIR_HOST // Silence compiler warning
  9050. #define REDIR_HOST "https://httpbingo.org"
  9051. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9052. Client cli(REDIR_HOST);
  9053. cli.set_follow_location(true);
  9054. auto res =
  9055. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::OK_200, res->status);
  9058. }
  9059. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9060. Client cli(REDIR_HOST);
  9061. cli.set_follow_location(true);
  9062. Params params;
  9063. params.emplace("url", "http://example.com");
  9064. params.emplace("status_code", "302");
  9065. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9066. ASSERT_TRUE(res);
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. }
  9069. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9070. Client cli(REDIR_HOST);
  9071. cli.set_follow_location(true);
  9072. Params params;
  9073. params.emplace("url", "http://example.com");
  9074. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. }
  9078. TEST(HttpToHttpsRedirectTest, CertFile) {
  9079. auto ssl_port = PORT + 1;
  9080. Server svr;
  9081. ASSERT_TRUE(svr.is_valid());
  9082. svr.Get("/index", [&](const Request &, Response &res) {
  9083. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9084. "/index");
  9085. svr.stop();
  9086. });
  9087. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9088. ASSERT_TRUE(ssl_svr.is_valid());
  9089. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9090. res.set_content("test", "text/plain");
  9091. ssl_svr.stop();
  9092. });
  9093. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9094. thread t2 =
  9095. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9096. auto se = detail::scope_exit([&] {
  9097. t2.join();
  9098. t.join();
  9099. ASSERT_FALSE(svr.is_running());
  9100. });
  9101. svr.wait_until_ready();
  9102. ssl_svr.wait_until_ready();
  9103. Client cli("127.0.0.1", PORT);
  9104. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9105. cli.enable_server_certificate_verification(true);
  9106. cli.set_follow_location(true);
  9107. cli.set_connection_timeout(30);
  9108. auto res = cli.Get("/index");
  9109. ASSERT_TRUE(res);
  9110. ASSERT_EQ(StatusCode::OK_200, res->status);
  9111. }
  9112. TEST(SSLClientRedirectTest, CertFile) {
  9113. auto ssl_port = PORT + 1;
  9114. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9115. ASSERT_TRUE(ssl_svr1.is_valid());
  9116. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9117. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9118. "/index");
  9119. ssl_svr1.stop();
  9120. });
  9121. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9122. ASSERT_TRUE(ssl_svr2.is_valid());
  9123. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9124. res.set_content("test", "text/plain");
  9125. ssl_svr2.stop();
  9126. });
  9127. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9128. thread t2 =
  9129. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9130. auto se = detail::scope_exit([&] {
  9131. t2.join();
  9132. t.join();
  9133. ASSERT_FALSE(ssl_svr1.is_running());
  9134. });
  9135. ssl_svr1.wait_until_ready();
  9136. ssl_svr2.wait_until_ready();
  9137. SSLClient cli("127.0.0.1", PORT);
  9138. std::string cert;
  9139. read_file(SERVER_CERT2_FILE, cert);
  9140. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9141. cli.enable_server_certificate_verification(true);
  9142. cli.set_follow_location(true);
  9143. cli.set_connection_timeout(30);
  9144. auto res = cli.Get("/index");
  9145. ASSERT_TRUE(res);
  9146. ASSERT_EQ(StatusCode::OK_200, res->status);
  9147. }
  9148. #endif
  9149. #ifdef CPPHTTPLIB_SSL_ENABLED
  9150. // Test that set_ca_cert_store() skips system certs (consistent with
  9151. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9152. // should be trusted - system certs should NOT be loaded.
  9153. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9154. // Load a specific cert that is NOT a system CA cert
  9155. std::string cert;
  9156. read_file(SERVER_CERT2_FILE, cert);
  9157. SSLClient cli("google.com");
  9158. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9159. cli.enable_server_certificate_verification(true);
  9160. // This should FAIL because:
  9161. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9162. // 2. System certs should NOT be loaded when custom store is set
  9163. // If system certs WERE loaded, this would succeed
  9164. auto res = cli.Get("/");
  9165. ASSERT_FALSE(res);
  9166. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9167. }
  9168. TEST(MultipartFormDataTest, LargeData) {
  9169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9170. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9171. const ContentReader &content_reader) {
  9172. if (req.is_multipart_form_data()) {
  9173. std::vector<FormData> items;
  9174. content_reader(
  9175. [&](const FormData &file) {
  9176. items.push_back(file);
  9177. return true;
  9178. },
  9179. [&](const char *data, size_t data_length) {
  9180. items.back().content.append(data, data_length);
  9181. return true;
  9182. });
  9183. EXPECT_TRUE(std::string(items[0].name) == "document");
  9184. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9185. EXPECT_TRUE(items[0].filename == "2MB_data");
  9186. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9187. EXPECT_TRUE(items[1].name == "hello");
  9188. EXPECT_TRUE(items[1].content == "world");
  9189. EXPECT_TRUE(items[1].filename == "");
  9190. EXPECT_TRUE(items[1].content_type == "");
  9191. } else {
  9192. std::string body;
  9193. content_reader([&](const char *data, size_t data_length) {
  9194. body.append(data, data_length);
  9195. return true;
  9196. });
  9197. }
  9198. });
  9199. auto port = svr.bind_to_any_port(HOST);
  9200. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9201. auto se = detail::scope_exit([&] {
  9202. svr.stop();
  9203. t.join();
  9204. ASSERT_FALSE(svr.is_running());
  9205. });
  9206. svr.wait_until_ready();
  9207. {
  9208. std::string data(1024 * 1024 * 2, '.');
  9209. std::stringstream buffer;
  9210. buffer << data;
  9211. SSLClient cli(HOST, port);
  9212. cli.enable_server_certificate_verification(false);
  9213. UploadFormDataItems items{
  9214. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9215. {"hello", "world", "", ""},
  9216. };
  9217. auto res = cli.Post("/post", items);
  9218. ASSERT_TRUE(res);
  9219. ASSERT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. }
  9222. TEST(MultipartFormDataTest, DataProviderItems) {
  9223. std::random_device seed_gen;
  9224. std::mt19937 random(seed_gen());
  9225. std::string rand1;
  9226. rand1.resize(1000);
  9227. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9228. std::string rand2;
  9229. rand2.resize(3000);
  9230. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9232. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9233. const ContentReader &content_reader) {
  9234. ASSERT_FALSE(req.is_multipart_form_data());
  9235. std::string body;
  9236. content_reader([&](const char *data, size_t data_length) {
  9237. body.append(data, data_length);
  9238. return true;
  9239. });
  9240. EXPECT_EQ(body, "");
  9241. });
  9242. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9243. const ContentReader &content_reader) {
  9244. ASSERT_TRUE(req.is_multipart_form_data());
  9245. std::vector<FormData> items;
  9246. content_reader(
  9247. [&](const FormData &file) {
  9248. items.push_back(file);
  9249. return true;
  9250. },
  9251. [&](const char *data, size_t data_length) {
  9252. items.back().content.append(data, data_length);
  9253. return true;
  9254. });
  9255. ASSERT_TRUE(items.size() == 2);
  9256. EXPECT_EQ(std::string(items[0].name), "name1");
  9257. EXPECT_EQ(items[0].content, "Testing123");
  9258. EXPECT_EQ(items[0].filename, "filename1");
  9259. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9260. EXPECT_EQ(items[1].name, "name2");
  9261. EXPECT_EQ(items[1].content, "Testing456");
  9262. EXPECT_EQ(items[1].filename, "");
  9263. EXPECT_EQ(items[1].content_type, "");
  9264. });
  9265. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9266. const ContentReader &content_reader) {
  9267. ASSERT_TRUE(req.is_multipart_form_data());
  9268. std::vector<FormData> items;
  9269. content_reader(
  9270. [&](const FormData &file) {
  9271. items.push_back(file);
  9272. return true;
  9273. },
  9274. [&](const char *data, size_t data_length) {
  9275. items.back().content.append(data, data_length);
  9276. return true;
  9277. });
  9278. ASSERT_TRUE(items.size() == 2);
  9279. EXPECT_EQ(items[0].name, "name3");
  9280. EXPECT_EQ(items[0].content, rand1);
  9281. EXPECT_EQ(items[0].filename, "filename3");
  9282. EXPECT_EQ(items[0].content_type, "");
  9283. EXPECT_EQ(items[1].name, "name4");
  9284. EXPECT_EQ(items[1].content, rand2);
  9285. EXPECT_EQ(items[1].filename, "filename4");
  9286. EXPECT_EQ(items[1].content_type, "");
  9287. });
  9288. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9289. const ContentReader &content_reader) {
  9290. ASSERT_TRUE(req.is_multipart_form_data());
  9291. std::vector<FormData> items;
  9292. content_reader(
  9293. [&](const FormData &file) {
  9294. items.push_back(file);
  9295. return true;
  9296. },
  9297. [&](const char *data, size_t data_length) {
  9298. items.back().content.append(data, data_length);
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(items.size() == 4);
  9302. EXPECT_EQ(std::string(items[0].name), "name1");
  9303. EXPECT_EQ(items[0].content, "Testing123");
  9304. EXPECT_EQ(items[0].filename, "filename1");
  9305. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9306. EXPECT_EQ(items[1].name, "name2");
  9307. EXPECT_EQ(items[1].content, "Testing456");
  9308. EXPECT_EQ(items[1].filename, "");
  9309. EXPECT_EQ(items[1].content_type, "");
  9310. EXPECT_EQ(items[2].name, "name3");
  9311. EXPECT_EQ(items[2].content, rand1);
  9312. EXPECT_EQ(items[2].filename, "filename3");
  9313. EXPECT_EQ(items[2].content_type, "");
  9314. EXPECT_EQ(items[3].name, "name4");
  9315. EXPECT_EQ(items[3].content, rand2);
  9316. EXPECT_EQ(items[3].filename, "filename4");
  9317. EXPECT_EQ(items[3].content_type, "");
  9318. });
  9319. auto port = svr.bind_to_any_port("localhost");
  9320. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9321. auto se = detail::scope_exit([&] {
  9322. svr.stop();
  9323. t.join();
  9324. ASSERT_FALSE(svr.is_running());
  9325. });
  9326. svr.wait_until_ready();
  9327. {
  9328. SSLClient cli("localhost", port);
  9329. cli.enable_server_certificate_verification(false);
  9330. UploadFormDataItems items{
  9331. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9332. {"name2", "Testing456", "", ""}, // not a file
  9333. };
  9334. {
  9335. auto res = cli.Post("/post-none", {}, {}, {});
  9336. ASSERT_TRUE(res);
  9337. ASSERT_EQ(StatusCode::OK_200, res->status);
  9338. }
  9339. FormDataProviderItems providers;
  9340. {
  9341. auto res =
  9342. cli.Post("/post-items", {}, items, providers); // empty providers
  9343. ASSERT_TRUE(res);
  9344. ASSERT_EQ(StatusCode::OK_200, res->status);
  9345. }
  9346. providers.push_back({"name3",
  9347. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9348. // test the offset is given correctly at each step
  9349. if (!offset)
  9350. sink.os.write(rand1.data(), 30);
  9351. else if (offset == 30)
  9352. sink.os.write(rand1.data() + 30, 300);
  9353. else if (offset == 330)
  9354. sink.os.write(rand1.data() + 330, 670);
  9355. else if (offset == rand1.size())
  9356. sink.done();
  9357. return true;
  9358. },
  9359. "filename3",
  9360. {}});
  9361. providers.push_back({"name4",
  9362. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9363. // test the offset is given correctly at each step
  9364. if (!offset)
  9365. sink.os.write(rand2.data(), 2000);
  9366. else if (offset == 2000)
  9367. sink.os.write(rand2.data() + 2000, 1);
  9368. else if (offset == 2001)
  9369. sink.os.write(rand2.data() + 2001, 999);
  9370. else if (offset == rand2.size())
  9371. sink.done();
  9372. return true;
  9373. },
  9374. "filename4",
  9375. {}});
  9376. {
  9377. auto res = cli.Post("/post-providers", {}, {}, providers);
  9378. ASSERT_TRUE(res);
  9379. ASSERT_EQ(StatusCode::OK_200, res->status);
  9380. }
  9381. {
  9382. auto res = cli.Post("/post-both", {}, items, providers);
  9383. ASSERT_TRUE(res);
  9384. ASSERT_EQ(StatusCode::OK_200, res->status);
  9385. }
  9386. }
  9387. }
  9388. TEST(MultipartFormDataTest, BadHeader) {
  9389. Server svr;
  9390. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9391. res.set_content("ok", "text/plain");
  9392. });
  9393. thread t = thread([&] { svr.listen(HOST, PORT); });
  9394. auto se = detail::scope_exit([&] {
  9395. svr.stop();
  9396. t.join();
  9397. ASSERT_FALSE(svr.is_running());
  9398. });
  9399. svr.wait_until_ready();
  9400. const std::string body =
  9401. "This is the preamble. It is to be ignored, though it\r\n"
  9402. "is a handy place for composition agents to include an\r\n"
  9403. "explanatory note to non-MIME conformant readers.\r\n"
  9404. "\r\n"
  9405. "\r\n"
  9406. "--simple boundary\r\n"
  9407. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9408. ": BAD...\r\n"
  9409. "\r\n"
  9410. "value1\r\n"
  9411. "--simple boundary\r\n"
  9412. "Content-Disposition: form-data; name=\"field2\"; "
  9413. "filename=\"example.txt\"\r\n"
  9414. "\r\n"
  9415. "value2\r\n"
  9416. "--simple boundary--\r\n"
  9417. "This is the epilogue. It is also to be ignored.\r\n";
  9418. std::string content_type =
  9419. R"(multipart/form-data; boundary="simple boundary")";
  9420. Client cli(HOST, PORT);
  9421. auto res = cli.Post("/post", body, content_type.c_str());
  9422. ASSERT_TRUE(res);
  9423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9424. }
  9425. TEST(MultipartFormDataTest, WithPreamble) {
  9426. Server svr;
  9427. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9428. res.set_content("ok", "text/plain");
  9429. });
  9430. thread t = thread([&] { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. t.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. const std::string body =
  9438. "This is the preamble. It is to be ignored, though it\r\n"
  9439. "is a handy place for composition agents to include an\r\n"
  9440. "explanatory note to non-MIME conformant readers.\r\n"
  9441. "\r\n"
  9442. "\r\n"
  9443. "--simple boundary\r\n"
  9444. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9445. "\r\n"
  9446. "value1\r\n"
  9447. "--simple boundary\r\n"
  9448. "Content-Disposition: form-data; name=\"field2\"; "
  9449. "filename=\"example.txt\"\r\n"
  9450. "\r\n"
  9451. "value2\r\n"
  9452. "--simple boundary--\r\n"
  9453. "This is the epilogue. It is also to be ignored.\r\n";
  9454. std::string content_type =
  9455. R"(multipart/form-data; boundary="simple boundary")";
  9456. Client cli(HOST, PORT);
  9457. auto res = cli.Post("/post", body, content_type.c_str());
  9458. ASSERT_TRUE(res);
  9459. EXPECT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9463. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9464. const ContentReader &content_reader) {
  9465. if (req.is_multipart_form_data()) {
  9466. std::vector<FormData> items;
  9467. content_reader(
  9468. [&](const FormData &file) {
  9469. items.push_back(file);
  9470. return true;
  9471. },
  9472. [&](const char *data, size_t data_length) {
  9473. items.back().content.append(data, data_length);
  9474. return true;
  9475. });
  9476. EXPECT_TRUE(std::string(items[0].name) == "document");
  9477. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9478. EXPECT_TRUE(items[0].filename == "2MB_data");
  9479. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9480. EXPECT_TRUE(items[1].name == "hello");
  9481. EXPECT_TRUE(items[1].content == "world");
  9482. EXPECT_TRUE(items[1].filename == "");
  9483. EXPECT_TRUE(items[1].content_type == "");
  9484. } else {
  9485. std::string body;
  9486. content_reader([&](const char *data, size_t data_length) {
  9487. body.append(data, data_length);
  9488. return true;
  9489. });
  9490. }
  9491. });
  9492. auto port = svr.bind_to_any_port("localhost");
  9493. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9494. auto se = detail::scope_exit([&] {
  9495. svr.stop();
  9496. t.join();
  9497. ASSERT_FALSE(svr.is_running());
  9498. });
  9499. svr.wait_until_ready();
  9500. {
  9501. std::string data(1024 * 1024 * 2, '.');
  9502. std::stringstream buffer;
  9503. buffer << data;
  9504. SSLClient cli("localhost", port);
  9505. cli.enable_server_certificate_verification(false);
  9506. UploadFormDataItems items{
  9507. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9508. {"hello", "world", "", ""},
  9509. };
  9510. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9511. ASSERT_TRUE(res);
  9512. ASSERT_EQ(StatusCode::OK_200, res->status);
  9513. }
  9514. }
  9515. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9516. std::string data(1024 * 1024 * 2, '&');
  9517. std::stringstream buffer;
  9518. buffer << data;
  9519. Client cli("https://localhost:8080");
  9520. UploadFormDataItems items{
  9521. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9522. {"hello", "world", "", ""},
  9523. };
  9524. for (const char &c : " \t\r\n") {
  9525. auto res =
  9526. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9527. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9528. ASSERT_FALSE(res);
  9529. }
  9530. }
  9531. TEST(MultipartFormDataTest, PutFormData) {
  9532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9533. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9534. const ContentReader &content_reader) {
  9535. if (req.is_multipart_form_data()) {
  9536. std::vector<FormData> items;
  9537. content_reader(
  9538. [&](const FormData &file) {
  9539. items.push_back(file);
  9540. return true;
  9541. },
  9542. [&](const char *data, size_t data_length) {
  9543. items.back().content.append(data, data_length);
  9544. return true;
  9545. });
  9546. EXPECT_TRUE(std::string(items[0].name) == "document");
  9547. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9548. EXPECT_TRUE(items[0].filename == "2MB_data");
  9549. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9550. EXPECT_TRUE(items[1].name == "hello");
  9551. EXPECT_TRUE(items[1].content == "world");
  9552. EXPECT_TRUE(items[1].filename == "");
  9553. EXPECT_TRUE(items[1].content_type == "");
  9554. } else {
  9555. std::string body;
  9556. content_reader([&](const char *data, size_t data_length) {
  9557. body.append(data, data_length);
  9558. return true;
  9559. });
  9560. }
  9561. });
  9562. auto port = svr.bind_to_any_port("localhost");
  9563. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. t.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. {
  9571. std::string data(1024 * 1024 * 2, '&');
  9572. std::stringstream buffer;
  9573. buffer << data;
  9574. SSLClient cli("localhost", port);
  9575. cli.enable_server_certificate_verification(false);
  9576. UploadFormDataItems items{
  9577. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9578. {"hello", "world", "", ""},
  9579. };
  9580. auto res = cli.Put("/put", items);
  9581. ASSERT_TRUE(res);
  9582. ASSERT_EQ(StatusCode::OK_200, res->status);
  9583. }
  9584. }
  9585. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9587. svr.Put("/put_customboundary",
  9588. [&](const Request &req, const Response & /*res*/,
  9589. const ContentReader &content_reader) {
  9590. if (req.is_multipart_form_data()) {
  9591. std::vector<FormData> items;
  9592. content_reader(
  9593. [&](const FormData &file) {
  9594. items.push_back(file);
  9595. return true;
  9596. },
  9597. [&](const char *data, size_t data_length) {
  9598. items.back().content.append(data, data_length);
  9599. return true;
  9600. });
  9601. EXPECT_TRUE(std::string(items[0].name) == "document");
  9602. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9603. EXPECT_TRUE(items[0].filename == "2MB_data");
  9604. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9605. EXPECT_TRUE(items[1].name == "hello");
  9606. EXPECT_TRUE(items[1].content == "world");
  9607. EXPECT_TRUE(items[1].filename == "");
  9608. EXPECT_TRUE(items[1].content_type == "");
  9609. } else {
  9610. std::string body;
  9611. content_reader([&](const char *data, size_t data_length) {
  9612. body.append(data, data_length);
  9613. return true;
  9614. });
  9615. }
  9616. });
  9617. auto port = svr.bind_to_any_port("localhost");
  9618. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. {
  9626. std::string data(1024 * 1024 * 2, '&');
  9627. std::stringstream buffer;
  9628. buffer << data;
  9629. SSLClient cli("localhost", port);
  9630. cli.enable_server_certificate_verification(false);
  9631. UploadFormDataItems items{
  9632. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9633. {"hello", "world", "", ""},
  9634. };
  9635. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9636. ASSERT_TRUE(res);
  9637. ASSERT_EQ(StatusCode::OK_200, res->status);
  9638. }
  9639. }
  9640. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9641. std::string data(1024 * 1024 * 2, '&');
  9642. std::stringstream buffer;
  9643. buffer << data;
  9644. Client cli("https://localhost:8080");
  9645. cli.enable_server_certificate_verification(false);
  9646. UploadFormDataItems items{
  9647. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9648. {"hello", "world", "", ""},
  9649. };
  9650. for (const char &c : " \t\r\n") {
  9651. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9652. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9653. ASSERT_FALSE(res);
  9654. }
  9655. }
  9656. TEST(MultipartFormDataTest, AlternateFilename) {
  9657. auto handled = false;
  9658. Server svr;
  9659. svr.Post("/test", [&](const Request &req, Response &res) {
  9660. ASSERT_EQ(2u, req.form.files.size());
  9661. ASSERT_EQ(1u, req.form.fields.size());
  9662. // Test files
  9663. const auto &file1 = req.form.get_file("file1");
  9664. ASSERT_EQ("file1", file1.name);
  9665. ASSERT_EQ("A.txt", file1.filename);
  9666. ASSERT_EQ("text/plain", file1.content_type);
  9667. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9668. const auto &file2 = req.form.get_file("file2");
  9669. ASSERT_EQ("file2", file2.name);
  9670. ASSERT_EQ("a.html", file2.filename);
  9671. ASSERT_EQ("text/html", file2.content_type);
  9672. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9673. file2.content);
  9674. // Test text field
  9675. const auto &text = req.form.get_field("text");
  9676. ASSERT_EQ("text default", text);
  9677. res.set_content("ok", "text/plain");
  9678. handled = true;
  9679. });
  9680. thread t = thread([&] { svr.listen(HOST, PORT); });
  9681. auto se = detail::scope_exit([&] {
  9682. svr.stop();
  9683. t.join();
  9684. ASSERT_FALSE(svr.is_running());
  9685. ASSERT_TRUE(handled);
  9686. });
  9687. svr.wait_until_ready();
  9688. auto req = "POST /test HTTP/1.1\r\n"
  9689. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9690. "Content-Length: 399\r\n"
  9691. "\r\n"
  9692. "----------\r\n"
  9693. "Content-Disposition: form-data; name=\"text\"\r\n"
  9694. "\r\n"
  9695. "text default\r\n"
  9696. "----------\r\n"
  9697. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9698. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9699. "Content-Type: text/plain\r\n"
  9700. "\r\n"
  9701. "Content of a.txt.\r\n"
  9702. "\r\n"
  9703. "----------\r\n"
  9704. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9705. "\"a.html\"\r\n"
  9706. "Content-Type: text/html\r\n"
  9707. "\r\n"
  9708. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9709. "\r\n"
  9710. "------------\r\n";
  9711. ASSERT_TRUE(send_request(1, req));
  9712. }
  9713. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9714. auto handled = false;
  9715. Server svr;
  9716. svr.Post("/test", [&](const Request &req, Response &res) {
  9717. // Case-insensitive "utf-8''" prefix with a long value
  9718. const auto &file = req.form.get_file("file1");
  9719. ASSERT_EQ("file1", file.name);
  9720. std::string expected_filename(2000, 'A');
  9721. ASSERT_EQ(expected_filename, file.filename);
  9722. res.set_content("ok", "text/plain");
  9723. handled = true;
  9724. });
  9725. thread t = thread([&] { svr.listen(HOST, PORT); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. t.join();
  9729. ASSERT_FALSE(svr.is_running());
  9730. ASSERT_TRUE(handled);
  9731. });
  9732. svr.wait_until_ready();
  9733. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9734. // Prior to the fix, this would cause O(N) stack recursion in std::regex
  9735. std::string long_filename(2000, 'A');
  9736. std::string body = "----------\r\n"
  9737. "Content-Disposition: form-data; name=\"file1\"; "
  9738. "filename*=\"Utf-8''" +
  9739. long_filename +
  9740. "\"\r\n"
  9741. "\r\n"
  9742. "hello\r\n"
  9743. "------------\r\n";
  9744. auto req = "POST /test HTTP/1.1\r\n"
  9745. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9746. "Content-Length: " +
  9747. std::to_string(body.size()) + "\r\n\r\n" + body;
  9748. ASSERT_TRUE(send_request(1, req));
  9749. }
  9750. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9751. auto handled = false;
  9752. Server svr;
  9753. svr.Post("/test", [&](const Request &req, Response &) {
  9754. ASSERT_EQ(2u, req.form.fields.size());
  9755. const auto &text1 = req.form.get_field("text1");
  9756. ASSERT_EQ("text1", text1);
  9757. const auto &text2 = req.form.get_field("text2");
  9758. ASSERT_EQ("text2", text2);
  9759. handled = true;
  9760. });
  9761. thread t = thread([&] { svr.listen(HOST, PORT); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. t.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. ASSERT_TRUE(handled);
  9767. });
  9768. svr.wait_until_ready();
  9769. auto req = "POST /test HTTP/1.1\r\n"
  9770. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9771. "Content-Length: 146\r\n"
  9772. "\r\n----------\r\n"
  9773. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9774. "\r\n"
  9775. "text1"
  9776. "\r\n----------\r\n"
  9777. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9778. "\r\n"
  9779. "text2"
  9780. "\r\n------------";
  9781. std::string response;
  9782. ASSERT_TRUE(send_request(1, req, &response));
  9783. ASSERT_EQ("200", response.substr(9, 3));
  9784. }
  9785. TEST(MultipartFormDataTest, ContentLength) {
  9786. auto handled = false;
  9787. Server svr;
  9788. svr.Post("/test", [&](const Request &req, Response &) {
  9789. ASSERT_EQ(2u, req.form.fields.size());
  9790. const auto &text1 = req.form.get_field("text1");
  9791. ASSERT_EQ("text1", text1);
  9792. const auto &text2 = req.form.get_field("text2");
  9793. ASSERT_EQ("text2", text2);
  9794. handled = true;
  9795. });
  9796. thread t = thread([&] { svr.listen(HOST, PORT); });
  9797. auto se = detail::scope_exit([&] {
  9798. svr.stop();
  9799. t.join();
  9800. ASSERT_FALSE(svr.is_running());
  9801. ASSERT_TRUE(handled);
  9802. });
  9803. svr.wait_until_ready();
  9804. auto req = "POST /test HTTP/1.1\r\n"
  9805. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9806. "Content-Length: 167\r\n"
  9807. "\r\n----------\r\n"
  9808. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9809. "Content-Length: 5\r\n"
  9810. "\r\n"
  9811. "text1"
  9812. "\r\n----------\r\n"
  9813. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9814. "\r\n"
  9815. "text2"
  9816. "\r\n------------\r\n";
  9817. std::string response;
  9818. ASSERT_TRUE(send_request(1, req, &response));
  9819. ASSERT_EQ("200", response.substr(9, 3));
  9820. }
  9821. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9822. auto handled = false;
  9823. Server svr;
  9824. svr.Post("/test", [&](const Request &req, Response &) {
  9825. ASSERT_EQ(2u, req.form.fields.size());
  9826. const auto &text1 = req.form.get_field("text1");
  9827. ASSERT_EQ("text1", text1);
  9828. // TODO: Add header access for text fields if needed
  9829. const auto &text2 = req.form.get_field("text2");
  9830. ASSERT_EQ("text2", text2);
  9831. // TODO: Header access for text fields needs to be implemented
  9832. // auto &headers = it->second.headers;
  9833. // ASSERT_EQ(3U, headers.size());
  9834. // auto custom_header = headers.find("x-whatever");
  9835. // ASSERT_TRUE(custom_header != headers.end());
  9836. // ASSERT_NE("customvalue", custom_header->second);
  9837. // ASSERT_EQ("CustomValue", custom_header->second);
  9838. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9839. handled = true;
  9840. });
  9841. thread t = thread([&] { svr.listen(HOST, PORT); });
  9842. auto se = detail::scope_exit([&] {
  9843. svr.stop();
  9844. t.join();
  9845. ASSERT_FALSE(svr.is_running());
  9846. ASSERT_TRUE(handled);
  9847. });
  9848. svr.wait_until_ready();
  9849. auto req = "POST /test HTTP/1.1\r\n"
  9850. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9851. "Content-Length: 232\r\n"
  9852. "\r\n----------\r\n"
  9853. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9854. "Content-Length: 5\r\n"
  9855. "X-Test: 1\r\n"
  9856. "\r\n"
  9857. "text1"
  9858. "\r\n----------\r\n"
  9859. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9860. "Content-Type: text/plain\r\n"
  9861. "X-Whatever: CustomValue\r\n"
  9862. "\r\n"
  9863. "text2"
  9864. "\r\n------------\r\n"
  9865. "That should be disregarded. Not even read";
  9866. std::string response;
  9867. ASSERT_TRUE(send_request(1, req, &response));
  9868. ASSERT_EQ("200", response.substr(9, 3));
  9869. }
  9870. TEST(MultipartFormDataTest, LargeHeader) {
  9871. auto handled = false;
  9872. Server svr;
  9873. svr.Post("/test", [&](const Request &req, Response &) {
  9874. ASSERT_EQ(1u, req.form.fields.size());
  9875. const auto &text = req.form.get_field("name1");
  9876. ASSERT_EQ("text1", text);
  9877. handled = true;
  9878. });
  9879. thread t = thread([&] { svr.listen(HOST, PORT); });
  9880. auto se = detail::scope_exit([&] {
  9881. svr.stop();
  9882. t.join();
  9883. ASSERT_FALSE(svr.is_running());
  9884. ASSERT_TRUE(handled);
  9885. });
  9886. svr.wait_until_ready();
  9887. auto boundary = std::string("cpp-httplib-multipart-data");
  9888. std::string content = "--" + boundary +
  9889. "\r\n"
  9890. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9891. "\r\n"
  9892. "text1\r\n"
  9893. "--" +
  9894. boundary + "--\r\n";
  9895. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9896. "Content-Type: multipart/form-data;boundary=" +
  9897. boundary +
  9898. "\r\n"
  9899. "Content-Length: " +
  9900. std::to_string(content.size()) +
  9901. "\r\n"
  9902. "Dummy-Header: ";
  9903. std::string header_suffix = "\r\n"
  9904. "\r\n";
  9905. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9906. size_t header_dummy_size =
  9907. read_buff_size -
  9908. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9909. auto header_dummy = std::string(header_dummy_size, '@');
  9910. auto req = header_prefix + header_dummy + header_suffix + content;
  9911. std::string response;
  9912. ASSERT_TRUE(send_request(1, req, &response));
  9913. ASSERT_EQ("200", response.substr(9, 3));
  9914. }
  9915. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9916. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9917. // (not chunked Transfer-Encoding) after the streaming refactor.
  9918. auto handled = false;
  9919. Server svr;
  9920. svr.Post("/upload", [&](const Request &req, Response &res) {
  9921. auto cl_it = req.headers.find("Content-Length");
  9922. EXPECT_TRUE(cl_it != req.headers.end());
  9923. auto te_it = req.headers.find("Transfer-Encoding");
  9924. EXPECT_TRUE(te_it == req.headers.end());
  9925. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9926. res.set_content("ok", "text/plain");
  9927. handled = true;
  9928. });
  9929. auto port = svr.bind_to_any_port(HOST);
  9930. auto t = thread([&] { svr.listen_after_bind(); });
  9931. auto se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. t.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. ASSERT_TRUE(handled);
  9936. });
  9937. svr.wait_until_ready();
  9938. UploadFormDataItems items = {
  9939. {"field1", "hello", "", "text/plain"},
  9940. {"file1", "world", "test.txt", "application/octet-stream"},
  9941. };
  9942. Client cli(HOST, port);
  9943. auto res = cli.Post("/upload", {}, items);
  9944. ASSERT_TRUE(res);
  9945. EXPECT_EQ(StatusCode::OK_200, res->status);
  9946. }
  9947. TEST(MultipartFormDataTest, MakeFileProvider) {
  9948. // Verify make_file_provider sends a file's contents correctly.
  9949. const std::string file_content(4096, 'Z');
  9950. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  9951. {
  9952. std::ofstream ofs(tmp_path, std::ios::binary);
  9953. ofs.write(file_content.data(),
  9954. static_cast<std::streamsize>(file_content.size()));
  9955. }
  9956. auto handled = false;
  9957. Server svr;
  9958. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  9959. const ContentReader &content_reader) {
  9960. ASSERT_TRUE(req.is_multipart_form_data());
  9961. std::vector<FormData> items;
  9962. content_reader(
  9963. [&](const FormData &file) {
  9964. items.push_back(file);
  9965. return true;
  9966. },
  9967. [&](const char *data, size_t data_length) {
  9968. items.back().content.append(data, data_length);
  9969. return true;
  9970. });
  9971. ASSERT_EQ(1u, items.size());
  9972. EXPECT_EQ("myfile", items[0].name);
  9973. EXPECT_EQ("data.bin", items[0].filename);
  9974. EXPECT_EQ("application/octet-stream", items[0].content_type);
  9975. EXPECT_EQ(file_content, items[0].content);
  9976. handled = true;
  9977. });
  9978. auto port = svr.bind_to_any_port(HOST);
  9979. auto t = thread([&] { svr.listen_after_bind(); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. t.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. ASSERT_TRUE(handled);
  9985. std::remove(tmp_path.c_str());
  9986. });
  9987. svr.wait_until_ready();
  9988. FormDataProviderItems providers;
  9989. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  9990. "application/octet-stream"));
  9991. Client cli(HOST, port);
  9992. auto res = cli.Post("/upload", {}, {}, providers);
  9993. ASSERT_TRUE(res);
  9994. EXPECT_EQ(StatusCode::OK_200, res->status);
  9995. }
  9996. TEST(MakeFileBodyTest, Basic) {
  9997. const std::string file_content(4096, 'Z');
  9998. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  9999. {
  10000. std::ofstream ofs(tmp_path, std::ios::binary);
  10001. ofs.write(file_content.data(),
  10002. static_cast<std::streamsize>(file_content.size()));
  10003. }
  10004. auto handled = false;
  10005. Server svr;
  10006. svr.Post("/upload", [&](const Request &req, Response &res) {
  10007. EXPECT_EQ(file_content, req.body);
  10008. handled = true;
  10009. res.status = StatusCode::OK_200;
  10010. });
  10011. auto port = svr.bind_to_any_port(HOST);
  10012. auto t = thread([&] { svr.listen_after_bind(); });
  10013. auto se = detail::scope_exit([&] {
  10014. svr.stop();
  10015. t.join();
  10016. ASSERT_FALSE(svr.is_running());
  10017. ASSERT_TRUE(handled);
  10018. std::remove(tmp_path.c_str());
  10019. });
  10020. svr.wait_until_ready();
  10021. auto fb = make_file_body(tmp_path);
  10022. ASSERT_GT(fb.first, 0u);
  10023. Client cli(HOST, port);
  10024. auto res =
  10025. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10026. ASSERT_TRUE(res);
  10027. EXPECT_EQ(StatusCode::OK_200, res->status);
  10028. }
  10029. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10030. static constexpr unsigned int number_of_tasks{1000000};
  10031. std::atomic_uint count{0};
  10032. std::unique_ptr<TaskQueue> task_queue{
  10033. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10034. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10035. auto queued = task_queue->enqueue(
  10036. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10037. EXPECT_TRUE(queued);
  10038. }
  10039. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10040. task_queue->shutdown();
  10041. #else
  10042. EXPECT_NO_THROW(task_queue->shutdown());
  10043. #endif
  10044. EXPECT_EQ(number_of_tasks, count.load());
  10045. }
  10046. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10047. static constexpr unsigned int number_of_tasks{1000000};
  10048. static constexpr unsigned int qlimit{2};
  10049. unsigned int queued_count{0};
  10050. std::atomic_uint count{0};
  10051. std::unique_ptr<TaskQueue> task_queue{
  10052. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10053. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10054. if (task_queue->enqueue(
  10055. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10056. queued_count++;
  10057. }
  10058. }
  10059. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10060. task_queue->shutdown();
  10061. #else
  10062. EXPECT_NO_THROW(task_queue->shutdown());
  10063. #endif
  10064. EXPECT_EQ(queued_count, count.load());
  10065. EXPECT_TRUE(queued_count <= number_of_tasks);
  10066. EXPECT_TRUE(queued_count >= qlimit);
  10067. }
  10068. TEST(TaskQueueTest, MaxQueuedRequests) {
  10069. static constexpr unsigned int qlimit{3};
  10070. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10071. std::condition_variable sem_cv;
  10072. std::mutex sem_mtx;
  10073. int credits = 0;
  10074. bool queued;
  10075. /* Fill up the queue with tasks that will block until we give them credits to
  10076. * complete. */
  10077. for (unsigned int n = 0; n <= qlimit;) {
  10078. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10079. std::unique_lock<std::mutex> lock(sem_mtx);
  10080. while (credits <= 0) {
  10081. sem_cv.wait(lock);
  10082. }
  10083. /* Consume the credit and signal the test code if they are all gone. */
  10084. if (--credits == 0) { sem_cv.notify_one(); }
  10085. });
  10086. if (n < qlimit) {
  10087. /* The first qlimit enqueues must succeed. */
  10088. EXPECT_TRUE(queued);
  10089. } else {
  10090. /* The last one will succeed only when the worker thread
  10091. * starts and dequeues the first blocking task. Although
  10092. * not necessary for the correctness of this test, we sleep for
  10093. * a short while to avoid busy waiting. */
  10094. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10095. }
  10096. if (queued) { n++; }
  10097. }
  10098. /* Further enqueues must fail since the queue is full. */
  10099. for (auto i = 0; i < 4; i++) {
  10100. queued = task_queue->enqueue([] {});
  10101. EXPECT_FALSE(queued);
  10102. }
  10103. /* Give the credits to allow the previous tasks to complete. */
  10104. {
  10105. std::unique_lock<std::mutex> lock(sem_mtx);
  10106. credits += qlimit + 1;
  10107. }
  10108. sem_cv.notify_all();
  10109. /* Wait for all the credits to be consumed. */
  10110. {
  10111. std::unique_lock<std::mutex> lock(sem_mtx);
  10112. while (credits > 0) {
  10113. sem_cv.wait(lock);
  10114. }
  10115. }
  10116. /* Check that we are able again to enqueue at least qlimit tasks. */
  10117. for (unsigned int i = 0; i < qlimit; i++) {
  10118. queued = task_queue->enqueue([] {});
  10119. EXPECT_TRUE(queued);
  10120. }
  10121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10122. task_queue->shutdown();
  10123. #else
  10124. EXPECT_NO_THROW(task_queue->shutdown());
  10125. #endif
  10126. }
  10127. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10128. Server svr;
  10129. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10130. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10131. });
  10132. svr.Get("/hello", [](const Request &req, Response &res) {
  10133. res.set_content(req.get_param_value("key"), "text/plain");
  10134. });
  10135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10136. auto se = detail::scope_exit([&] {
  10137. svr.stop();
  10138. thread.join();
  10139. ASSERT_FALSE(svr.is_running());
  10140. });
  10141. svr.wait_until_ready();
  10142. {
  10143. Client cli(HOST, PORT);
  10144. cli.set_follow_location(true);
  10145. auto res = cli.Get("/");
  10146. ASSERT_TRUE(res);
  10147. EXPECT_EQ(StatusCode::OK_200, res->status);
  10148. EXPECT_EQ("val&key2=val2", res->body);
  10149. }
  10150. }
  10151. #endif
  10152. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10153. Server svr;
  10154. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10155. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10156. });
  10157. svr.Get("/hello", [](const Request &req, Response &res) {
  10158. res.set_content(req.get_param_value("key"), "text/plain");
  10159. });
  10160. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. {
  10168. Client cli(HOST, PORT);
  10169. cli.set_follow_location(true);
  10170. auto res = cli.Get("/");
  10171. ASSERT_TRUE(res);
  10172. EXPECT_EQ(StatusCode::OK_200, res->status);
  10173. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10174. }
  10175. }
  10176. #ifdef CPPHTTPLIB_SSL_ENABLED
  10177. TEST(RedirectTest, Issue2185_Online) {
  10178. SSLClient client("github.com");
  10179. client.set_follow_location(true);
  10180. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10181. "Coollab-Windows.zip");
  10182. ASSERT_TRUE(res);
  10183. EXPECT_EQ(StatusCode::OK_200, res->status);
  10184. EXPECT_EQ(9920427U, res->body.size());
  10185. }
  10186. #endif
  10187. TEST(VulnerabilityTest, CRLFInjection) {
  10188. Server svr;
  10189. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10190. res.set_content("Hello 1", "text/plain");
  10191. });
  10192. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10193. res.set_content("Hello 2", "text/plain");
  10194. });
  10195. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10196. res.set_content("Hello 3", "text/plain");
  10197. });
  10198. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10199. res.set_content("Hello 4", "text/plain");
  10200. });
  10201. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10202. for (const auto &x : req.headers) {
  10203. auto key = x.first;
  10204. EXPECT_STRNE("evil", key.c_str());
  10205. }
  10206. });
  10207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10208. auto se = detail::scope_exit([&] {
  10209. svr.stop();
  10210. thread.join();
  10211. ASSERT_FALSE(svr.is_running());
  10212. });
  10213. svr.wait_until_ready();
  10214. {
  10215. Client cli(HOST, PORT);
  10216. cli.Post("/test1", "A=B",
  10217. "application/x-www-form-urlencoded\r\nevil: hello1");
  10218. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10219. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10220. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10221. }
  10222. }
  10223. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10224. auto server_thread = std::thread([] {
  10225. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10226. default_socket_options(srv);
  10227. sockaddr_in addr{};
  10228. addr.sin_family = AF_INET;
  10229. addr.sin_port = htons(PORT + 1);
  10230. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10231. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10232. ::listen(srv, 1);
  10233. sockaddr_in cli_addr{};
  10234. socklen_t cli_len = sizeof(cli_addr);
  10235. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10236. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10237. std::string buf_all;
  10238. char buf[2048];
  10239. ssize_t n;
  10240. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10241. buf_all.append(buf, static_cast<size_t>(n));
  10242. size_t pos;
  10243. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10244. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10245. auto e = request_block.find("\r\n");
  10246. if (e != std::string::npos) {
  10247. auto request_line = request_block.substr(0, e);
  10248. std::string msg =
  10249. "CRLF injection detected in request line: '" + request_line + "'";
  10250. EXPECT_FALSE(true) << msg;
  10251. }
  10252. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10253. ::send(cli,
  10254. #ifdef _WIN32
  10255. static_cast<const char *>(resp.c_str()),
  10256. static_cast<int>(resp.size()),
  10257. #else
  10258. resp.c_str(), resp.size(),
  10259. #endif
  10260. 0);
  10261. buf_all.erase(0, pos + 4);
  10262. }
  10263. }
  10264. detail::close_socket(cli);
  10265. detail::close_socket(srv);
  10266. });
  10267. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10268. auto cli = Client("127.0.0.1", PORT + 1);
  10269. auto headers = Headers{
  10270. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10271. {"Connection", "keep-alive"}};
  10272. auto res = cli.Get("/hi", headers);
  10273. EXPECT_FALSE(res);
  10274. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10275. server_thread.join();
  10276. }
  10277. TEST(PathParamsTest, StaticMatch) {
  10278. const auto pattern = "/users/all";
  10279. detail::PathParamsMatcher matcher(pattern);
  10280. Request request;
  10281. request.path = "/users/all";
  10282. ASSERT_TRUE(matcher.match(request));
  10283. std::unordered_map<std::string, std::string> expected_params = {};
  10284. EXPECT_EQ(request.path_params, expected_params);
  10285. }
  10286. TEST(PathParamsTest, StaticMismatch) {
  10287. const auto pattern = "/users/all";
  10288. detail::PathParamsMatcher matcher(pattern);
  10289. Request request;
  10290. request.path = "/users/1";
  10291. ASSERT_FALSE(matcher.match(request));
  10292. }
  10293. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10294. const auto pattern = "/users/:id/subscriptions";
  10295. detail::PathParamsMatcher matcher(pattern);
  10296. Request request;
  10297. request.path = "/users/42/subscriptions";
  10298. ASSERT_TRUE(matcher.match(request));
  10299. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10300. EXPECT_EQ(request.path_params, expected_params);
  10301. }
  10302. TEST(PathParamsTest, SingleParamInTheEnd) {
  10303. const auto pattern = "/users/:id";
  10304. detail::PathParamsMatcher matcher(pattern);
  10305. Request request;
  10306. request.path = "/users/24";
  10307. ASSERT_TRUE(matcher.match(request));
  10308. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10309. EXPECT_EQ(request.path_params, expected_params);
  10310. }
  10311. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10312. const auto pattern = "/users/:id/";
  10313. detail::PathParamsMatcher matcher(pattern);
  10314. Request request;
  10315. request.path = "/users/42/";
  10316. ASSERT_TRUE(matcher.match(request));
  10317. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10318. EXPECT_EQ(request.path_params, expected_params);
  10319. }
  10320. TEST(PathParamsTest, EmptyParam) {
  10321. const auto pattern = "/users/:id/";
  10322. detail::PathParamsMatcher matcher(pattern);
  10323. Request request;
  10324. request.path = "/users//";
  10325. ASSERT_TRUE(matcher.match(request));
  10326. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10327. EXPECT_EQ(request.path_params, expected_params);
  10328. }
  10329. TEST(PathParamsTest, FragmentMismatch) {
  10330. const auto pattern = "/users/:id/";
  10331. detail::PathParamsMatcher matcher(pattern);
  10332. Request request;
  10333. request.path = "/admins/24/";
  10334. ASSERT_FALSE(matcher.match(request));
  10335. }
  10336. TEST(PathParamsTest, ExtraFragments) {
  10337. const auto pattern = "/users/:id";
  10338. detail::PathParamsMatcher matcher(pattern);
  10339. Request request;
  10340. request.path = "/users/42/subscriptions";
  10341. ASSERT_FALSE(matcher.match(request));
  10342. }
  10343. TEST(PathParamsTest, MissingTrailingParam) {
  10344. const auto pattern = "/users/:id";
  10345. detail::PathParamsMatcher matcher(pattern);
  10346. Request request;
  10347. request.path = "/users";
  10348. ASSERT_FALSE(matcher.match(request));
  10349. }
  10350. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10351. const auto pattern = "/users/:id/subscriptions";
  10352. detail::PathParamsMatcher matcher(pattern);
  10353. Request request;
  10354. request.path = "/users/subscriptions";
  10355. ASSERT_FALSE(matcher.match(request));
  10356. }
  10357. TEST(PathParamsTest, MultipleParams) {
  10358. const auto pattern = "/users/:userid/subscriptions/:subid";
  10359. detail::PathParamsMatcher matcher(pattern);
  10360. Request request;
  10361. request.path = "/users/42/subscriptions/2";
  10362. ASSERT_TRUE(matcher.match(request));
  10363. std::unordered_map<std::string, std::string> expected_params = {
  10364. {"userid", "42"}, {"subid", "2"}};
  10365. EXPECT_EQ(request.path_params, expected_params);
  10366. }
  10367. TEST(PathParamsTest, SequenceOfParams) {
  10368. const auto pattern = "/values/:x/:y/:z";
  10369. detail::PathParamsMatcher matcher(pattern);
  10370. Request request;
  10371. request.path = "/values/1/2/3";
  10372. ASSERT_TRUE(matcher.match(request));
  10373. std::unordered_map<std::string, std::string> expected_params = {
  10374. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10375. EXPECT_EQ(request.path_params, expected_params);
  10376. }
  10377. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10378. const auto pattern = "/prefix:suffix";
  10379. detail::PathParamsMatcher matcher(pattern);
  10380. Request request;
  10381. request.path = "/prefix:suffix";
  10382. ASSERT_TRUE(matcher.match(request));
  10383. const std::unordered_map<std::string, std::string> expected_params = {};
  10384. EXPECT_EQ(request.path_params, expected_params);
  10385. }
  10386. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10387. // If ipv6 regex working, regex match codepath is taken.
  10388. // else port will default to 80 in Client impl
  10389. int clientImplMagicPort = 80;
  10390. int port = 4321;
  10391. // above ports must be different to avoid false negative
  10392. EXPECT_NE(clientImplMagicPort, port);
  10393. std::string ipV6TestURL = "http://[ff06::c3]";
  10394. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10395. CLIENT_PRIVATE_KEY_FILE);
  10396. EXPECT_EQ(cli.port(), port);
  10397. }
  10398. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10399. auto file_path = "./www/dir/index.html";
  10400. auto dir_path = "./www/dir";
  10401. detail::FileStat stat_file(file_path);
  10402. EXPECT_TRUE(stat_file.is_file());
  10403. EXPECT_FALSE(stat_file.is_dir());
  10404. detail::FileStat stat_dir(dir_path);
  10405. EXPECT_FALSE(stat_dir.is_file());
  10406. EXPECT_TRUE(stat_dir.is_dir());
  10407. }
  10408. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10409. // IPv4 with default HTTP port (80)
  10410. EXPECT_EQ("example.com",
  10411. detail::make_host_and_port_string("example.com", 80, false));
  10412. // IPv4 with default HTTPS port (443)
  10413. EXPECT_EQ("example.com",
  10414. detail::make_host_and_port_string("example.com", 443, true));
  10415. // IPv4 with non-default HTTP port
  10416. EXPECT_EQ("example.com:8080",
  10417. detail::make_host_and_port_string("example.com", 8080, false));
  10418. // IPv4 with non-default HTTPS port
  10419. EXPECT_EQ("example.com:8443",
  10420. detail::make_host_and_port_string("example.com", 8443, true));
  10421. // IPv6 with default HTTP port (80)
  10422. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10423. // IPv6 with default HTTPS port (443)
  10424. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10425. // IPv6 with non-default HTTP port
  10426. EXPECT_EQ("[::1]:8080",
  10427. detail::make_host_and_port_string("::1", 8080, false));
  10428. // IPv6 with non-default HTTPS port
  10429. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10430. // IPv6 full address with default port
  10431. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10432. detail::make_host_and_port_string(
  10433. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10434. // IPv6 full address with non-default port
  10435. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10436. detail::make_host_and_port_string(
  10437. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10438. // IPv6 localhost with non-default port
  10439. EXPECT_EQ("[::1]:3000",
  10440. detail::make_host_and_port_string("::1", 3000, false));
  10441. // IPv6 with zone ID (link-local address) with default port
  10442. EXPECT_EQ("[fe80::1%eth0]",
  10443. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10444. // IPv6 with zone ID (link-local address) with non-default port
  10445. EXPECT_EQ("[fe80::1%eth0]:8080",
  10446. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10447. // Edge case: Port 443 with is_ssl=false (should add port)
  10448. EXPECT_EQ("example.com:443",
  10449. detail::make_host_and_port_string("example.com", 443, false));
  10450. // Edge case: Port 80 with is_ssl=true (should add port)
  10451. EXPECT_EQ("example.com:80",
  10452. detail::make_host_and_port_string("example.com", 80, true));
  10453. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10454. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10455. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10456. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10457. // Security fix: Already bracketed IPv6 should not get double brackets
  10458. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10459. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10460. EXPECT_EQ("[::1]:8080",
  10461. detail::make_host_and_port_string("[::1]", 8080, false));
  10462. EXPECT_EQ("[2001:db8::1]:8080",
  10463. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10464. EXPECT_EQ("[fe80::1%eth0]",
  10465. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10466. EXPECT_EQ("[fe80::1%eth0]:8080",
  10467. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10468. // Edge case: Empty host (should return as-is)
  10469. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10470. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10471. // This is a known limitation but shouldn't crash
  10472. EXPECT_EQ("[host:name]",
  10473. detail::make_host_and_port_string("host:name", 80, false));
  10474. // Port number edge cases (no validation, but should not crash)
  10475. EXPECT_EQ("example.com:0",
  10476. detail::make_host_and_port_string("example.com", 0, false));
  10477. EXPECT_EQ("example.com:-1",
  10478. detail::make_host_and_port_string("example.com", -1, false));
  10479. EXPECT_EQ("example.com:65535",
  10480. detail::make_host_and_port_string("example.com", 65535, false));
  10481. EXPECT_EQ("example.com:65536",
  10482. detail::make_host_and_port_string("example.com", 65536, false));
  10483. }
  10484. #ifdef CPPHTTPLIB_SSL_ENABLED
  10485. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10486. httplib::SSLClient cli("roblox.com", 443);
  10487. cli.set_follow_location(true);
  10488. auto res = cli.Get("/");
  10489. ASSERT_TRUE(res);
  10490. EXPECT_EQ(StatusCode::OK_200, res->status);
  10491. }
  10492. #endif
  10493. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10494. Server svr;
  10495. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10496. EXPECT_EQ(res.status, 400);
  10497. });
  10498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10499. auto se = detail::scope_exit([&] {
  10500. svr.stop();
  10501. thread.join();
  10502. ASSERT_FALSE(svr.is_running());
  10503. });
  10504. svr.wait_until_ready();
  10505. Client cli(HOST, PORT);
  10506. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10507. }
  10508. TEST(InvalidHeaderCharsTest, is_field_name) {
  10509. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10510. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10511. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10512. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10513. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10514. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10515. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10516. EXPECT_FALSE(detail::fields::is_field_name(""));
  10517. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10518. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10519. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10520. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10521. }
  10522. TEST(InvalidHeaderCharsTest, is_field_value) {
  10523. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10524. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10525. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10526. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10527. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10528. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10529. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10530. EXPECT_TRUE(detail::fields::is_field_value(""));
  10531. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10532. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10533. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10534. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10535. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10536. }
  10537. TEST(InvalidHeaderCharsTest, OnServer) {
  10538. Server svr;
  10539. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10540. std::string header = "Not Set";
  10541. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10542. res.set_header(header, "value");
  10543. res.set_content("Page Content Page Content", "text/plain");
  10544. });
  10545. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10546. std::string header = "Not Set";
  10547. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10548. res.set_header("X-Test", header);
  10549. res.set_content("Page Content Page Content", "text/plain");
  10550. });
  10551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10552. auto se = detail::scope_exit([&] {
  10553. svr.stop();
  10554. thread.join();
  10555. ASSERT_FALSE(svr.is_running());
  10556. });
  10557. svr.wait_until_ready();
  10558. Client cli(HOST, PORT);
  10559. {
  10560. auto res = cli.Get(
  10561. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10562. ASSERT_TRUE(res);
  10563. EXPECT_EQ("Page Content Page Content", res->body);
  10564. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10565. }
  10566. {
  10567. auto res = cli.Get(
  10568. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10569. ASSERT_TRUE(res);
  10570. EXPECT_EQ("Page Content Page Content", res->body);
  10571. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10572. }
  10573. }
  10574. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10575. auto handled = false;
  10576. Server svr;
  10577. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10578. thread t = thread([&] { svr.listen(HOST, PORT); });
  10579. auto se = detail::scope_exit([&] {
  10580. svr.stop();
  10581. t.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. ASSERT_FALSE(handled);
  10584. });
  10585. svr.wait_until_ready();
  10586. auto req = "POST /test HTTP/1.1\r\n"
  10587. "Content-Length: x\r\n"
  10588. "\r\n";
  10589. std::string response;
  10590. ASSERT_TRUE(send_request(1, req, &response));
  10591. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10592. response.substr(0, response.find("\r\n")));
  10593. }
  10594. #ifndef _WIN32
  10595. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10596. static constexpr char reject[] = "Unauthorized";
  10597. static constexpr char accept[] = "Upload accepted";
  10598. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10599. Server svr;
  10600. svr.set_expect_100_continue_handler(
  10601. [](const Request & /*req*/, Response &res) {
  10602. res.status = StatusCode::Unauthorized_401;
  10603. res.set_content(reject, "text/plain");
  10604. return res.status;
  10605. });
  10606. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10607. res.set_content(accept, "text/plain");
  10608. });
  10609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10610. auto se = detail::scope_exit([&] {
  10611. svr.stop();
  10612. thread.join();
  10613. ASSERT_FALSE(svr.is_running());
  10614. });
  10615. svr.wait_until_ready();
  10616. {
  10617. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10618. curl_easy_init(), &curl_easy_cleanup};
  10619. ASSERT_NE(curl, nullptr);
  10620. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10621. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10622. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10623. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10624. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10625. &curl_slist_free_all};
  10626. ASSERT_NE(list, nullptr);
  10627. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10628. struct read_data {
  10629. size_t read_size;
  10630. size_t total_size;
  10631. } data = {0, total_size};
  10632. using read_callback_t =
  10633. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10634. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10635. void *userdata) -> size_t {
  10636. read_data *data = (read_data *)userdata;
  10637. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10638. std::fill_n(ptr, size * nmemb, 'A');
  10639. data->read_size += size * nmemb;
  10640. return size * nmemb;
  10641. };
  10642. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10643. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10644. std::vector<char> buffer;
  10645. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10646. using write_callback_t =
  10647. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10648. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10649. void *userdata) -> size_t {
  10650. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10651. buffer->reserve(buffer->size() + size * nmemb + 1);
  10652. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10653. return size * nmemb;
  10654. };
  10655. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10656. {
  10657. const auto res = curl_easy_perform(curl.get());
  10658. ASSERT_EQ(res, CURLE_OK);
  10659. }
  10660. {
  10661. auto response_code = long{};
  10662. const auto res =
  10663. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10664. ASSERT_EQ(res, CURLE_OK);
  10665. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10666. }
  10667. {
  10668. auto dl = curl_off_t{};
  10669. const auto res =
  10670. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10671. ASSERT_EQ(res, CURLE_OK);
  10672. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10673. }
  10674. {
  10675. buffer.push_back('\0');
  10676. ASSERT_STRCASEEQ(buffer.data(), reject);
  10677. }
  10678. }
  10679. }
  10680. #endif
  10681. template <typename S, typename C>
  10682. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10683. svr.Get("/stream", [&](const Request &, Response &res) {
  10684. auto data = new std::string("01234567890123456789");
  10685. res.set_content_provider(
  10686. data->size(), "text/plain",
  10687. [&, data](size_t offset, size_t length, DataSink &sink) {
  10688. const size_t DATA_CHUNK_SIZE = 4;
  10689. const auto &d = *data;
  10690. std::this_thread::sleep_for(std::chrono::seconds(1));
  10691. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10692. return true;
  10693. },
  10694. [data](bool success) {
  10695. EXPECT_FALSE(success);
  10696. delete data;
  10697. });
  10698. });
  10699. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10700. auto i = new size_t(0);
  10701. res.set_content_provider(
  10702. "text/plain",
  10703. [i](size_t, DataSink &sink) {
  10704. if (*i < 5) {
  10705. std::this_thread::sleep_for(std::chrono::seconds(1));
  10706. sink.write("abcd", 4);
  10707. (*i)++;
  10708. } else {
  10709. sink.done();
  10710. }
  10711. return true;
  10712. },
  10713. [i](bool success) {
  10714. EXPECT_FALSE(success);
  10715. delete i;
  10716. });
  10717. });
  10718. svr.Get("/chunked", [&](const Request &, Response &res) {
  10719. auto i = new size_t(0);
  10720. res.set_chunked_content_provider(
  10721. "text/plain",
  10722. [i](size_t, DataSink &sink) {
  10723. if (*i < 5) {
  10724. std::this_thread::sleep_for(std::chrono::seconds(1));
  10725. sink.os << "abcd";
  10726. (*i)++;
  10727. } else {
  10728. sink.done();
  10729. }
  10730. return true;
  10731. },
  10732. [i](bool success) {
  10733. EXPECT_FALSE(success);
  10734. delete i;
  10735. });
  10736. });
  10737. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10738. auto se = detail::scope_exit([&] {
  10739. svr.stop();
  10740. listen_thread.join();
  10741. ASSERT_FALSE(svr.is_running());
  10742. });
  10743. svr.wait_until_ready();
  10744. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10745. {
  10746. auto start = std::chrono::steady_clock::now();
  10747. auto res = cli.Get("/stream");
  10748. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10749. std::chrono::steady_clock::now() - start)
  10750. .count();
  10751. ASSERT_FALSE(res);
  10752. EXPECT_EQ(Error::Read, res.error());
  10753. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10754. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10755. }
  10756. {
  10757. auto start = std::chrono::steady_clock::now();
  10758. auto res = cli.Get("/stream_without_length");
  10759. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10760. std::chrono::steady_clock::now() - start)
  10761. .count();
  10762. ASSERT_FALSE(res);
  10763. EXPECT_EQ(Error::Read, res.error());
  10764. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10765. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10766. }
  10767. {
  10768. auto start = std::chrono::steady_clock::now();
  10769. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10770. EXPECT_EQ("abcd", string(data, data_length));
  10771. return true;
  10772. });
  10773. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10774. std::chrono::steady_clock::now() - start)
  10775. .count();
  10776. ASSERT_FALSE(res);
  10777. EXPECT_EQ(Error::Read, res.error());
  10778. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10779. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10780. }
  10781. }
  10782. TEST(MaxTimeoutTest, ContentStream) {
  10783. time_t timeout = 2000;
  10784. time_t threshold = 200;
  10785. Server svr;
  10786. Client cli("localhost", PORT);
  10787. max_timeout_test(svr, cli, timeout, threshold);
  10788. }
  10789. #ifdef CPPHTTPLIB_SSL_ENABLED
  10790. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10791. time_t timeout = 2000;
  10792. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10794. SSLClient cli("localhost", PORT);
  10795. cli.enable_server_certificate_verification(false);
  10796. max_timeout_test(svr, cli, timeout, threshold);
  10797. }
  10798. #endif
  10799. class EventDispatcher {
  10800. public:
  10801. EventDispatcher() {}
  10802. bool wait_event(DataSink *sink) {
  10803. unique_lock<mutex> lk(m_);
  10804. int id = id_;
  10805. // Wait with timeout to prevent hanging if client disconnects
  10806. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10807. [&] { return cid_ == id; })) {
  10808. return false; // Timeout occurred
  10809. }
  10810. sink->write(message_.data(), message_.size());
  10811. return true;
  10812. }
  10813. void send_event(const string &message) {
  10814. lock_guard<mutex> lk(m_);
  10815. cid_ = id_++;
  10816. message_ = message;
  10817. cv_.notify_all();
  10818. }
  10819. private:
  10820. mutex m_;
  10821. condition_variable cv_;
  10822. atomic_int id_{0};
  10823. atomic_int cid_{-1};
  10824. string message_;
  10825. };
  10826. TEST(ClientInThreadTest, Issue2068) {
  10827. EventDispatcher ed;
  10828. Server svr;
  10829. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10830. res.set_chunked_content_provider("text/event-stream",
  10831. [&](size_t /*offset*/, DataSink &sink) {
  10832. return ed.wait_event(&sink);
  10833. });
  10834. });
  10835. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10836. svr.wait_until_ready();
  10837. thread event_thread([&] {
  10838. int id = 0;
  10839. while (svr.is_running()) {
  10840. this_thread::sleep_for(chrono::milliseconds(500));
  10841. std::stringstream ss;
  10842. ss << "data: " << id << "\n\n";
  10843. ed.send_event(ss.str());
  10844. id++;
  10845. }
  10846. });
  10847. auto se = detail::scope_exit([&] {
  10848. svr.stop();
  10849. listen_thread.join();
  10850. event_thread.join();
  10851. ASSERT_FALSE(svr.is_running());
  10852. });
  10853. {
  10854. auto client = detail::make_unique<Client>(HOST, PORT);
  10855. client->set_read_timeout(std::chrono::minutes(10));
  10856. std::atomic<bool> stop{false};
  10857. std::thread t([&] {
  10858. client->Get("/event1",
  10859. [&](const char *, size_t) -> bool { return !stop; });
  10860. });
  10861. std::this_thread::sleep_for(std::chrono::seconds(2));
  10862. stop = true;
  10863. client->stop();
  10864. t.join();
  10865. // Reset client after thread has finished
  10866. client.reset();
  10867. }
  10868. }
  10869. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10870. Server svr;
  10871. svr.Get("/", [](const Request &req, Response &res) {
  10872. EXPECT_EQ(2U, req.trailers.size());
  10873. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10874. // Denied
  10875. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10876. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10877. // Accepted
  10878. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10879. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10880. EXPECT_TRUE(req.has_trailer("X-World"));
  10881. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10882. res.set_content("ok", "text/plain");
  10883. });
  10884. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10885. auto se = detail::scope_exit([&] {
  10886. svr.stop();
  10887. t.join();
  10888. ASSERT_FALSE(svr.is_running());
  10889. });
  10890. svr.wait_until_ready();
  10891. const std::string req = "GET / HTTP/1.1\r\n"
  10892. "Transfer-Encoding: chunked\r\n"
  10893. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10894. "\r\n"
  10895. "0\r\n"
  10896. "Content-Length: 10\r\n"
  10897. "Host: internal.local\r\n"
  10898. "Content-Type: malicious/content\r\n"
  10899. "Cookie: any\r\n"
  10900. "Set-Cookie: any\r\n"
  10901. "X-Forwarded-For: attacker.com\r\n"
  10902. "X-Real-Ip: 1.1.1.1\r\n"
  10903. "X-Hello: hello\r\n"
  10904. "X-World: world\r\n"
  10905. "\r\n";
  10906. std::string res;
  10907. ASSERT_TRUE(send_request(1, req, &res));
  10908. }
  10909. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10910. Server svr;
  10911. std::string observed_remote_addr;
  10912. std::string observed_xff;
  10913. svr.Get("/ip", [&](const Request &req, Response &res) {
  10914. observed_remote_addr = req.remote_addr;
  10915. observed_xff = req.get_header_value("X-Forwarded-For");
  10916. res.set_content("ok", "text/plain");
  10917. });
  10918. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. t.join();
  10922. ASSERT_FALSE(svr.is_running());
  10923. });
  10924. svr.wait_until_ready();
  10925. Client cli(HOST, PORT);
  10926. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10927. ASSERT_TRUE(res);
  10928. EXPECT_EQ(StatusCode::OK_200, res->status);
  10929. EXPECT_EQ(observed_xff, "203.0.113.66");
  10930. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10931. observed_remote_addr == "127.0.0.1");
  10932. }
  10933. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10934. Server svr;
  10935. svr.set_trusted_proxies({"203.0.113.66"});
  10936. std::string observed_remote_addr;
  10937. std::string observed_xff;
  10938. svr.Get("/ip", [&](const Request &req, Response &res) {
  10939. observed_remote_addr = req.remote_addr;
  10940. observed_xff = req.get_header_value("X-Forwarded-For");
  10941. res.set_content("ok", "text/plain");
  10942. });
  10943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10944. auto se = detail::scope_exit([&] {
  10945. svr.stop();
  10946. t.join();
  10947. ASSERT_FALSE(svr.is_running());
  10948. });
  10949. svr.wait_until_ready();
  10950. Client cli(HOST, PORT);
  10951. auto res = cli.Get("/ip");
  10952. ASSERT_TRUE(res);
  10953. EXPECT_EQ(StatusCode::OK_200, res->status);
  10954. EXPECT_EQ(observed_xff, "");
  10955. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10956. observed_remote_addr == "127.0.0.1");
  10957. }
  10958. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10959. Server svr;
  10960. svr.set_trusted_proxies({"203.0.113.66"});
  10961. std::string observed_remote_addr;
  10962. std::string observed_xff;
  10963. svr.Get("/ip", [&](const Request &req, Response &res) {
  10964. observed_remote_addr = req.remote_addr;
  10965. observed_xff = req.get_header_value("X-Forwarded-For");
  10966. res.set_content("ok", "text/plain");
  10967. });
  10968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10969. auto se = detail::scope_exit([&] {
  10970. svr.stop();
  10971. t.join();
  10972. ASSERT_FALSE(svr.is_running());
  10973. });
  10974. svr.wait_until_ready();
  10975. Client cli(HOST, PORT);
  10976. auto res =
  10977. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10978. ASSERT_TRUE(res);
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10981. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10982. }
  10983. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10984. Server svr;
  10985. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10986. std::string observed_remote_addr;
  10987. std::string observed_xff;
  10988. svr.Get("/ip", [&](const Request &req, Response &res) {
  10989. observed_remote_addr = req.remote_addr;
  10990. observed_xff = req.get_header_value("X-Forwarded-For");
  10991. res.set_content("ok", "text/plain");
  10992. });
  10993. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10994. auto se = detail::scope_exit([&] {
  10995. svr.stop();
  10996. t.join();
  10997. ASSERT_FALSE(svr.is_running());
  10998. });
  10999. svr.wait_until_ready();
  11000. Client cli(HOST, PORT);
  11001. auto res = cli.Get(
  11002. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11003. ASSERT_TRUE(res);
  11004. EXPECT_EQ(StatusCode::OK_200, res->status);
  11005. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11006. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11007. }
  11008. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11009. Server svr;
  11010. svr.set_trusted_proxies({"192.0.2.45"});
  11011. std::string observed_remote_addr;
  11012. std::string observed_xff;
  11013. svr.Get("/ip", [&](const Request &req, Response &res) {
  11014. observed_remote_addr = req.remote_addr;
  11015. observed_xff = req.get_header_value("X-Forwarded-For");
  11016. res.set_content("ok", "text/plain");
  11017. });
  11018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11019. auto se = detail::scope_exit([&] {
  11020. svr.stop();
  11021. t.join();
  11022. ASSERT_FALSE(svr.is_running());
  11023. });
  11024. svr.wait_until_ready();
  11025. Client cli(HOST, PORT);
  11026. auto res =
  11027. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11028. ASSERT_TRUE(res);
  11029. EXPECT_EQ(StatusCode::OK_200, res->status);
  11030. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11031. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11032. }
  11033. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11034. Server svr;
  11035. svr.set_trusted_proxies({"192.0.2.45"});
  11036. std::string observed_remote_addr;
  11037. std::string observed_xff;
  11038. svr.Get("/ip", [&](const Request &req, Response &res) {
  11039. observed_remote_addr = req.remote_addr;
  11040. observed_xff = req.get_header_value("X-Forwarded-For");
  11041. res.set_content("ok", "text/plain");
  11042. });
  11043. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11044. auto se = detail::scope_exit([&] {
  11045. svr.stop();
  11046. t.join();
  11047. ASSERT_FALSE(svr.is_running());
  11048. });
  11049. svr.wait_until_ready();
  11050. Client cli(HOST, PORT);
  11051. auto res = cli.Get(
  11052. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11053. ASSERT_TRUE(res);
  11054. EXPECT_EQ(StatusCode::OK_200, res->status);
  11055. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11056. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11057. }
  11058. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11059. Server svr;
  11060. svr.set_trusted_proxies({"192.0.2.45"});
  11061. std::string observed_remote_addr;
  11062. std::string observed_xff;
  11063. svr.Get("/ip", [&](const Request &req, Response &res) {
  11064. observed_remote_addr = req.remote_addr;
  11065. observed_xff = req.get_header_value("X-Forwarded-For");
  11066. res.set_content("ok", "text/plain");
  11067. });
  11068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. std::string raw_req =
  11076. "GET /ip HTTP/1.1\r\n"
  11077. "Host: localhost\r\n"
  11078. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11079. "Connection: close\r\n"
  11080. "\r\n";
  11081. std::string out;
  11082. ASSERT_TRUE(send_request(5, raw_req, &out));
  11083. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11084. // Header parser trims surrounding whitespace of the header value
  11085. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11086. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11087. }
  11088. #ifndef _WIN32
  11089. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11090. Server svr;
  11091. svr.Post("/post", [&](const Request &req, Response &res) {
  11092. res.set_content(req.body, "text/plain");
  11093. });
  11094. svr.Put("/put", [&](const Request &req, Response &res) {
  11095. res.set_content(req.body, "text/plain");
  11096. });
  11097. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11098. res.set_content(req.body, "text/plain");
  11099. });
  11100. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11101. res.set_content(req.body, "text/plain");
  11102. });
  11103. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11104. auto se = detail::scope_exit([&] {
  11105. svr.stop();
  11106. t.join();
  11107. ASSERT_FALSE(svr.is_running());
  11108. });
  11109. svr.wait_until_ready();
  11110. std::string resp;
  11111. // POST without Content-Length
  11112. ASSERT_TRUE(send_request(5,
  11113. "POST /post HTTP/1.1\r\n"
  11114. "Host: localhost\r\n"
  11115. "Connection: close\r\n"
  11116. "\r\n",
  11117. &resp));
  11118. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11119. // PUT without Content-Length
  11120. resp.clear();
  11121. ASSERT_TRUE(send_request(5,
  11122. "PUT /put HTTP/1.1\r\n"
  11123. "Host: localhost\r\n"
  11124. "Connection: close\r\n"
  11125. "\r\n",
  11126. &resp));
  11127. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11128. // PATCH without Content-Length
  11129. resp.clear();
  11130. ASSERT_TRUE(send_request(5,
  11131. "PATCH /patch HTTP/1.1\r\n"
  11132. "Host: localhost\r\n"
  11133. "Connection: close\r\n"
  11134. "\r\n",
  11135. &resp));
  11136. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11137. // DELETE without Content-Length
  11138. resp.clear();
  11139. ASSERT_TRUE(send_request(5,
  11140. "DELETE /delete HTTP/1.1\r\n"
  11141. "Host: localhost\r\n"
  11142. "Connection: close\r\n"
  11143. "\r\n",
  11144. &resp));
  11145. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11146. }
  11147. #endif
  11148. //==============================================================================
  11149. // open_stream() Tests
  11150. //==============================================================================
  11151. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11152. std::string result;
  11153. char buf[8192];
  11154. ssize_t n;
  11155. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11156. result.append(buf, static_cast<size_t>(n));
  11157. }
  11158. return result;
  11159. }
  11160. // Mock stream for unit tests
  11161. class MockStream : public Stream {
  11162. public:
  11163. std::string data;
  11164. size_t pos = 0;
  11165. ssize_t error_after = -1; // -1 = no error
  11166. explicit MockStream(const std::string &d, ssize_t err = -1)
  11167. : data(d), error_after(err) {}
  11168. bool is_readable() const override { return true; }
  11169. bool wait_readable() const override { return true; }
  11170. bool wait_writable() const override { return true; }
  11171. ssize_t read(char *ptr, size_t size) override {
  11172. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11173. if (pos >= data.size()) return 0;
  11174. size_t limit =
  11175. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11176. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11177. std::memcpy(ptr, data.data() + pos, to_read);
  11178. pos += to_read;
  11179. return static_cast<ssize_t>(to_read);
  11180. }
  11181. ssize_t write(const char *, size_t) override { return -1; }
  11182. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11183. ip = "127.0.0.1";
  11184. port = 0;
  11185. }
  11186. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11187. ip = "127.0.0.1";
  11188. port = 0;
  11189. }
  11190. socket_t socket() const override { return INVALID_SOCKET; }
  11191. time_t duration() const override { return 0; }
  11192. };
  11193. TEST(StreamHandleTest, Basic) {
  11194. ClientImpl::StreamHandle handle;
  11195. EXPECT_FALSE(handle.is_valid());
  11196. handle.response = detail::make_unique<Response>();
  11197. handle.error = Error::Connection;
  11198. EXPECT_FALSE(handle.is_valid());
  11199. handle.error = Error::Success;
  11200. EXPECT_TRUE(handle.is_valid());
  11201. }
  11202. TEST(BodyReaderTest, Basic) {
  11203. MockStream stream("Hello, World!");
  11204. detail::BodyReader reader;
  11205. reader.stream = &stream;
  11206. reader.content_length = 13;
  11207. char buf[32];
  11208. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11209. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11210. EXPECT_TRUE(reader.eof);
  11211. }
  11212. TEST(BodyReaderTest, NoStream) {
  11213. detail::BodyReader reader;
  11214. char buf[32];
  11215. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11216. EXPECT_EQ(Error::Connection, reader.last_error);
  11217. }
  11218. TEST(BodyReaderTest, Error) {
  11219. MockStream stream("Hello, World!", 5);
  11220. detail::BodyReader reader;
  11221. reader.stream = &stream;
  11222. reader.content_length = 13;
  11223. char buf[32];
  11224. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11225. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11226. EXPECT_EQ(Error::Read, reader.last_error);
  11227. }
  11228. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11229. // Mock-based StreamHandle tests relying on private internals are removed.
  11230. class OpenStreamTest : public ::testing::Test {
  11231. protected:
  11232. void SetUp() override {
  11233. svr_.Get("/hello", [](const Request &, Response &res) {
  11234. res.set_content("Hello World!", "text/plain");
  11235. });
  11236. svr_.Get("/large", [](const Request &, Response &res) {
  11237. res.set_content(std::string(10000, 'X'), "text/plain");
  11238. });
  11239. svr_.Get("/chunked", [](const Request &, Response &res) {
  11240. res.set_chunked_content_provider("text/plain",
  11241. [](size_t offset, DataSink &sink) {
  11242. if (offset < 15) {
  11243. sink.write("chunk", 5);
  11244. return true;
  11245. }
  11246. sink.done();
  11247. return true;
  11248. });
  11249. });
  11250. svr_.Get("/compressible", [](const Request &, Response &res) {
  11251. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11252. DataSink &sink) {
  11253. if (offset < 100 * 1024) {
  11254. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11255. sink.write(chunk.data(), chunk.size());
  11256. return true;
  11257. }
  11258. sink.done();
  11259. return true;
  11260. });
  11261. });
  11262. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11263. [](const Request & /*req*/, Response &res) {
  11264. auto i = new int(0);
  11265. res.set_header("Trailer", "Content-Length, X-Allowed");
  11266. res.set_chunked_content_provider(
  11267. "text/plain",
  11268. [i](size_t /*offset*/, DataSink &sink) {
  11269. switch (*i) {
  11270. case 0: sink.os << "123"; break;
  11271. case 1: sink.os << "456"; break;
  11272. case 2: sink.os << "789"; break;
  11273. case 3: {
  11274. sink.done_with_trailer(
  11275. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11276. } break;
  11277. }
  11278. (*i)++;
  11279. return true;
  11280. },
  11281. [i](bool success) {
  11282. EXPECT_TRUE(success);
  11283. delete i;
  11284. });
  11285. });
  11286. // Echo headers endpoint for header-related tests
  11287. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11288. std::string body;
  11289. for (const auto &h : req.headers) {
  11290. body.append(h.first);
  11291. body.push_back(':');
  11292. body.append(h.second);
  11293. body.push_back('\n');
  11294. }
  11295. res.set_content(body, "text/plain");
  11296. });
  11297. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11298. std::string body;
  11299. for (const auto &h : req.headers) {
  11300. body.append(h.first);
  11301. body.push_back(':');
  11302. body.append(h.second);
  11303. body.push_back('\n');
  11304. }
  11305. res.set_content(body, "text/plain");
  11306. });
  11307. port_ = svr_.bind_to_any_port("127.0.0.1");
  11308. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11309. svr_.wait_until_ready();
  11310. }
  11311. void TearDown() override {
  11312. svr_.stop();
  11313. if (thread_.joinable()) thread_.join();
  11314. }
  11315. Server svr_;
  11316. std::thread thread_;
  11317. int port_ = 0;
  11318. };
  11319. TEST_F(OpenStreamTest, Basic) {
  11320. Client cli("127.0.0.1", port_);
  11321. auto handle = cli.open_stream("GET", "/hello");
  11322. EXPECT_TRUE(handle.is_valid());
  11323. EXPECT_EQ("Hello World!", read_all(handle));
  11324. }
  11325. TEST_F(OpenStreamTest, SmallBuffer) {
  11326. Client cli("127.0.0.1", port_);
  11327. auto handle = cli.open_stream("GET", "/hello");
  11328. std::string result;
  11329. char buf[4];
  11330. ssize_t n;
  11331. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11332. result.append(buf, static_cast<size_t>(n));
  11333. EXPECT_EQ("Hello World!", result);
  11334. }
  11335. TEST_F(OpenStreamTest, DefaultHeaders) {
  11336. Client cli("127.0.0.1", port_);
  11337. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11338. {
  11339. auto handle = cli.open_stream("GET", "/echo-headers");
  11340. ASSERT_TRUE(handle.is_valid());
  11341. auto body = read_all(handle);
  11342. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11343. std::string::npos);
  11344. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11345. std::string::npos);
  11346. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11347. }
  11348. // open_stream POST with body and no explicit content_type should NOT add
  11349. // text/plain Content-Type (behavior differs from non-streaming path), but
  11350. // should include Content-Length
  11351. {
  11352. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11353. ASSERT_TRUE(handle.is_valid());
  11354. auto body = read_all(handle);
  11355. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11356. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11357. }
  11358. // open_stream POST with explicit Content-Type should preserve it
  11359. {
  11360. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11361. {{"Content-Type", "application/custom"}},
  11362. "{}", "application/custom");
  11363. ASSERT_TRUE(handle.is_valid());
  11364. auto body = read_all(handle);
  11365. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11366. }
  11367. // User-specified User-Agent must not be overwritten for stream API
  11368. {
  11369. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11370. {{"User-Agent", "MyAgent/1.2"}});
  11371. ASSERT_TRUE(handle.is_valid());
  11372. auto body = read_all(handle);
  11373. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11374. }
  11375. }
  11376. TEST_F(OpenStreamTest, Large) {
  11377. Client cli("127.0.0.1", port_);
  11378. auto handle = cli.open_stream("GET", "/large");
  11379. EXPECT_EQ(10000u, read_all(handle).size());
  11380. }
  11381. TEST_F(OpenStreamTest, ConnectionError) {
  11382. Client cli("127.0.0.1", 9999);
  11383. auto handle = cli.open_stream("GET", "/hello");
  11384. EXPECT_FALSE(handle.is_valid());
  11385. }
  11386. TEST_F(OpenStreamTest, Chunked) {
  11387. Client cli("127.0.0.1", port_);
  11388. auto handle = cli.open_stream("GET", "/chunked");
  11389. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11390. "Transfer-Encoding") == "chunked");
  11391. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11392. }
  11393. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11394. Client cli("127.0.0.1", port_);
  11395. auto handle =
  11396. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11397. ASSERT_TRUE(handle.is_valid());
  11398. // Consume body to allow trailers to be received/parsed
  11399. auto body = read_all(handle);
  11400. // Explicitly parse trailers (ensure trailers are available for assertion)
  11401. handle.parse_trailers_if_needed();
  11402. EXPECT_EQ(std::string("123456789"), body);
  11403. // The response should include a Trailer header declaring both names
  11404. ASSERT_TRUE(handle.response);
  11405. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11406. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11407. handle.response->get_header_value("Trailer"));
  11408. // Prohibited trailer must not be present
  11409. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11410. // Allowed trailer should be present
  11411. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11412. EXPECT_EQ(std::string("yes"),
  11413. handle.response->get_trailer_value("X-Allowed"));
  11414. // Verify trailers are NOT present as regular headers
  11415. EXPECT_EQ(std::string(""),
  11416. handle.response->get_header_value("Content-Length"));
  11417. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11418. }
  11419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11420. TEST_F(OpenStreamTest, Gzip) {
  11421. Client cli("127.0.0.1", port_);
  11422. auto handle = cli.open_stream("GET", "/compressible", {},
  11423. {{"Accept-Encoding", "gzip"}});
  11424. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11425. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11426. }
  11427. #endif
  11428. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11429. TEST_F(OpenStreamTest, Brotli) {
  11430. Client cli("127.0.0.1", port_);
  11431. auto handle =
  11432. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11433. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11434. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11435. }
  11436. #endif
  11437. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11438. TEST_F(OpenStreamTest, Zstd) {
  11439. Client cli("127.0.0.1", port_);
  11440. auto handle = cli.open_stream("GET", "/compressible", {},
  11441. {{"Accept-Encoding", "zstd"}});
  11442. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11443. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11444. }
  11445. #endif
  11446. #ifdef CPPHTTPLIB_SSL_ENABLED
  11447. class SSLOpenStreamTest : public ::testing::Test {
  11448. protected:
  11449. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11450. void SetUp() override {
  11451. svr_.Get("/hello", [](const Request &, Response &res) {
  11452. res.set_content("Hello SSL World!", "text/plain");
  11453. });
  11454. svr_.Get("/chunked", [](const Request &, Response &res) {
  11455. res.set_chunked_content_provider("text/plain",
  11456. [](size_t offset, DataSink &sink) {
  11457. if (offset < 15) {
  11458. sink.write("chunk", 5);
  11459. return true;
  11460. }
  11461. sink.done();
  11462. return true;
  11463. });
  11464. });
  11465. svr_.Post("/echo", [](const Request &req, Response &res) {
  11466. res.set_content(req.body, req.get_header_value("Content-Type"));
  11467. });
  11468. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11469. std::string body = req.body;
  11470. res.set_chunked_content_provider(
  11471. "text/plain", [body](size_t offset, DataSink &sink) {
  11472. if (offset < body.size()) {
  11473. sink.write(body.data() + offset, body.size() - offset);
  11474. }
  11475. sink.done();
  11476. return true;
  11477. });
  11478. });
  11479. port_ = svr_.bind_to_any_port("127.0.0.1");
  11480. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11481. svr_.wait_until_ready();
  11482. }
  11483. void TearDown() override {
  11484. svr_.stop();
  11485. if (thread_.joinable()) thread_.join();
  11486. }
  11487. SSLServer svr_;
  11488. std::thread thread_;
  11489. int port_ = 0;
  11490. };
  11491. TEST_F(SSLOpenStreamTest, Basic) {
  11492. SSLClient cli("127.0.0.1", port_);
  11493. cli.enable_server_certificate_verification(false);
  11494. auto handle = cli.open_stream("GET", "/hello");
  11495. ASSERT_TRUE(handle.is_valid());
  11496. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11497. }
  11498. TEST_F(SSLOpenStreamTest, Chunked) {
  11499. SSLClient cli("127.0.0.1", port_);
  11500. cli.enable_server_certificate_verification(false);
  11501. auto handle = cli.open_stream("GET", "/chunked");
  11502. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11503. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11504. "Transfer-Encoding") == "chunked");
  11505. auto body = read_all(handle);
  11506. EXPECT_EQ("chunkchunkchunk", body);
  11507. }
  11508. TEST_F(SSLOpenStreamTest, Post) {
  11509. SSLClient cli("127.0.0.1", port_);
  11510. cli.enable_server_certificate_verification(false);
  11511. auto handle =
  11512. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11513. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11514. EXPECT_EQ(200, handle.response->status);
  11515. auto body = read_all(handle);
  11516. EXPECT_EQ("Hello SSL POST", body);
  11517. }
  11518. TEST_F(SSLOpenStreamTest, PostChunked) {
  11519. SSLClient cli("127.0.0.1", port_);
  11520. cli.enable_server_certificate_verification(false);
  11521. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11522. "Chunked SSL Data", "text/plain");
  11523. ASSERT_TRUE(handle.is_valid());
  11524. EXPECT_EQ(200, handle.response->status);
  11525. auto body = read_all(handle);
  11526. EXPECT_EQ("Chunked SSL Data", body);
  11527. }
  11528. #endif // CPPHTTPLIB_SSL_ENABLED
  11529. //==============================================================================
  11530. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11531. // results for various scenarios.
  11532. //==============================================================================
  11533. TEST(ParityTest, GetVsOpenStream) {
  11534. Server svr;
  11535. const std::string path = "/parity";
  11536. const std::string content = "Parity test content: hello world";
  11537. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11538. res.set_content(content, "text/plain");
  11539. });
  11540. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11541. auto se = detail::scope_exit([&] {
  11542. svr.stop();
  11543. t.join();
  11544. ASSERT_FALSE(svr.is_running());
  11545. });
  11546. svr.wait_until_ready();
  11547. Client cli(HOST, PORT);
  11548. // Non-stream path
  11549. auto r1 = cli.Get(path);
  11550. ASSERT_TRUE(r1);
  11551. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11552. // Stream path
  11553. auto h = cli.open_stream("GET", path);
  11554. ASSERT_TRUE(h.is_valid());
  11555. EXPECT_EQ(r1->body, read_all(h));
  11556. }
  11557. // Helper to compress data with provided compressor type T
  11558. template <typename Compressor>
  11559. static std::string compress_payload_for_parity(const std::string &in) {
  11560. std::string out;
  11561. Compressor compressor;
  11562. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11563. [&](const char *data, size_t n) {
  11564. out.append(data, n);
  11565. return true;
  11566. });
  11567. EXPECT_TRUE(ok);
  11568. return out;
  11569. }
  11570. // Helper function for compression parity tests
  11571. template <typename Compressor>
  11572. static void test_compression_parity(const std::string &original,
  11573. const std::string &path,
  11574. const std::string &encoding) {
  11575. const std::string compressed =
  11576. compress_payload_for_parity<Compressor>(original);
  11577. Server svr;
  11578. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11579. res.set_content(compressed, "application/octet-stream");
  11580. res.set_header("Content-Encoding", encoding);
  11581. });
  11582. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11583. auto se = detail::scope_exit([&] {
  11584. svr.stop();
  11585. t.join();
  11586. ASSERT_FALSE(svr.is_running());
  11587. });
  11588. svr.wait_until_ready();
  11589. Client cli(HOST, PORT);
  11590. // Non-streaming
  11591. {
  11592. auto res = cli.Get(path);
  11593. ASSERT_TRUE(res);
  11594. EXPECT_EQ(StatusCode::OK_200, res->status);
  11595. EXPECT_EQ(original, res->body);
  11596. }
  11597. // Streaming
  11598. {
  11599. auto h = cli.open_stream("GET", path);
  11600. ASSERT_TRUE(h.is_valid());
  11601. EXPECT_EQ(original, read_all(h));
  11602. }
  11603. }
  11604. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11605. TEST(ParityTest, Gzip) {
  11606. test_compression_parity<detail::gzip_compressor>(
  11607. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11608. }
  11609. #endif
  11610. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11611. TEST(ParityTest, Brotli) {
  11612. test_compression_parity<detail::brotli_compressor>(
  11613. "Hello, brotli parity test payload", "/parity-br", "br");
  11614. }
  11615. #endif
  11616. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11617. TEST(ParityTest, Zstd) {
  11618. test_compression_parity<detail::zstd_compressor>(
  11619. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11620. }
  11621. #endif
  11622. //==============================================================================
  11623. // New Stream API Tests
  11624. //==============================================================================
  11625. inline std::string read_body(httplib::stream::Result &result) {
  11626. std::string body;
  11627. while (result.next()) {
  11628. body.append(result.data(), result.size());
  11629. }
  11630. return body;
  11631. }
  11632. TEST(ClientConnectionTest, Basic) {
  11633. httplib::ClientConnection conn;
  11634. EXPECT_FALSE(conn.is_open());
  11635. conn.sock = 1;
  11636. EXPECT_TRUE(conn.is_open());
  11637. httplib::ClientConnection conn2(std::move(conn));
  11638. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11639. conn2.sock = INVALID_SOCKET;
  11640. }
  11641. // Unified test server for all stream::* tests
  11642. class StreamApiTest : public ::testing::Test {
  11643. protected:
  11644. void SetUp() override {
  11645. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11646. res.set_content("Hello World!", "text/plain");
  11647. });
  11648. svr_.Get("/echo-params",
  11649. [](const httplib::Request &req, httplib::Response &res) {
  11650. std::string r;
  11651. for (const auto &p : req.params) {
  11652. if (!r.empty()) r += "&";
  11653. r += p.first + "=" + p.second;
  11654. }
  11655. res.set_content(r, "text/plain");
  11656. });
  11657. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11658. res.set_content(req.body, req.get_header_value("Content-Type"));
  11659. });
  11660. svr_.Post("/echo-headers",
  11661. [](const httplib::Request &req, httplib::Response &res) {
  11662. std::string r;
  11663. for (const auto &h : req.headers)
  11664. r += h.first + ": " + h.second + "\n";
  11665. res.set_content(r, "text/plain");
  11666. });
  11667. svr_.Post("/echo-params",
  11668. [](const httplib::Request &req, httplib::Response &res) {
  11669. std::string r = "params:";
  11670. for (const auto &p : req.params)
  11671. r += p.first + "=" + p.second + ";";
  11672. res.set_content(r + " body:" + req.body, "text/plain");
  11673. });
  11674. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11675. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11676. });
  11677. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11678. res.set_content("PUT:" + req.body, "text/plain");
  11679. });
  11680. svr_.Patch("/echo",
  11681. [](const httplib::Request &req, httplib::Response &res) {
  11682. res.set_content("PATCH:" + req.body, "text/plain");
  11683. });
  11684. svr_.Delete(
  11685. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11686. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11687. "text/plain");
  11688. });
  11689. svr_.Get("/head-test",
  11690. [](const httplib::Request &, httplib::Response &res) {
  11691. res.set_content("body for HEAD", "text/plain");
  11692. });
  11693. svr_.Options("/options",
  11694. [](const httplib::Request &, httplib::Response &res) {
  11695. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11696. });
  11697. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11698. svr_.wait_until_ready();
  11699. }
  11700. void TearDown() override {
  11701. svr_.stop();
  11702. if (thread_.joinable()) thread_.join();
  11703. }
  11704. httplib::Server svr_;
  11705. std::thread thread_;
  11706. };
  11707. // stream::Get tests
  11708. TEST_F(StreamApiTest, GetBasic) {
  11709. httplib::Client cli(HOST, PORT);
  11710. auto result = httplib::stream::Get(cli, "/hello");
  11711. ASSERT_TRUE(result.is_valid());
  11712. EXPECT_EQ(200, result.status());
  11713. EXPECT_EQ("Hello World!", read_body(result));
  11714. }
  11715. TEST_F(StreamApiTest, GetWithParams) {
  11716. httplib::Client cli(HOST, PORT);
  11717. httplib::Params params{{"foo", "bar"}};
  11718. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11719. ASSERT_TRUE(result.is_valid());
  11720. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11721. }
  11722. TEST_F(StreamApiTest, GetConnectionError) {
  11723. httplib::Client cli(HOST, 9999);
  11724. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11725. }
  11726. TEST_F(StreamApiTest, Get404) {
  11727. httplib::Client cli(HOST, PORT);
  11728. auto result = httplib::stream::Get(cli, "/nonexistent");
  11729. EXPECT_TRUE(result.is_valid());
  11730. EXPECT_EQ(404, result.status());
  11731. }
  11732. // stream::Post tests
  11733. TEST_F(StreamApiTest, PostBasic) {
  11734. httplib::Client cli(HOST, PORT);
  11735. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11736. "application/json");
  11737. ASSERT_TRUE(result.is_valid());
  11738. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11739. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11740. }
  11741. TEST_F(StreamApiTest, PostWithHeaders) {
  11742. httplib::Client cli(HOST, PORT);
  11743. httplib::Headers headers{{"X-Custom", "value"}};
  11744. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11745. "text/plain");
  11746. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11747. }
  11748. TEST_F(StreamApiTest, PostWithParams) {
  11749. httplib::Client cli(HOST, PORT);
  11750. httplib::Params params{{"k", "v"}};
  11751. auto result =
  11752. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11753. auto body = read_body(result);
  11754. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11755. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11756. }
  11757. TEST_F(StreamApiTest, PostLarge) {
  11758. httplib::Client cli(HOST, PORT);
  11759. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11760. size_t total = 0;
  11761. while (result.next()) {
  11762. total += result.size();
  11763. }
  11764. EXPECT_EQ(100u * 1024u, total);
  11765. }
  11766. // stream::Put/Patch tests
  11767. TEST_F(StreamApiTest, PutAndPatch) {
  11768. httplib::Client cli(HOST, PORT);
  11769. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11770. EXPECT_EQ("PUT:test", read_body(put));
  11771. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11772. EXPECT_EQ("PATCH:test", read_body(patch));
  11773. }
  11774. // stream::Delete tests
  11775. TEST_F(StreamApiTest, Delete) {
  11776. httplib::Client cli(HOST, PORT);
  11777. auto del1 = httplib::stream::Delete(cli, "/resource");
  11778. EXPECT_EQ("Deleted", read_body(del1));
  11779. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11780. EXPECT_EQ("Deleted:data", read_body(del2));
  11781. }
  11782. // stream::Head/Options tests
  11783. TEST_F(StreamApiTest, HeadAndOptions) {
  11784. httplib::Client cli(HOST, PORT);
  11785. auto head = httplib::stream::Head(cli, "/head-test");
  11786. EXPECT_TRUE(head.is_valid());
  11787. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11788. auto opts = httplib::stream::Options(cli, "/options");
  11789. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11790. }
  11791. // SSL stream::* tests
  11792. #ifdef CPPHTTPLIB_SSL_ENABLED
  11793. class SSLStreamApiTest : public ::testing::Test {
  11794. protected:
  11795. void SetUp() override {
  11796. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11797. res.set_content("Hello SSL!", "text/plain");
  11798. });
  11799. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11800. res.set_content(req.body, "text/plain");
  11801. });
  11802. port_ = svr_.bind_to_any_port("127.0.0.1");
  11803. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11804. svr_.wait_until_ready();
  11805. }
  11806. void TearDown() override {
  11807. svr_.stop();
  11808. if (thread_.joinable()) thread_.join();
  11809. }
  11810. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11811. std::thread thread_;
  11812. int port_ = 0;
  11813. };
  11814. TEST_F(SSLStreamApiTest, GetAndPost) {
  11815. httplib::SSLClient cli("127.0.0.1", port_);
  11816. cli.enable_server_certificate_verification(false);
  11817. auto get = httplib::stream::Get(cli, "/hello");
  11818. EXPECT_EQ("Hello SSL!", read_body(get));
  11819. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11820. EXPECT_EQ("test", read_body(post));
  11821. }
  11822. #endif
  11823. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11824. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11825. // BodyReader
  11826. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11827. // Test that read timeout during streaming is detected
  11828. // Use a large content-length response where server delays mid-stream
  11829. Server svr;
  11830. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11831. // Send a large response with delay in the middle
  11832. res.set_content_provider(
  11833. 1000, // content_length
  11834. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11835. if (offset < 100) {
  11836. // Send first 100 bytes immediately
  11837. std::string data(100, 'A');
  11838. sink.write(data.c_str(), data.size());
  11839. return true;
  11840. }
  11841. // Then delay longer than client timeout
  11842. std::this_thread::sleep_for(std::chrono::seconds(3));
  11843. std::string data(900, 'B');
  11844. sink.write(data.c_str(), data.size());
  11845. return true;
  11846. });
  11847. });
  11848. auto port = 8091;
  11849. std::thread t([&]() { svr.listen("localhost", port); });
  11850. svr.wait_until_ready();
  11851. Client cli("localhost", port);
  11852. cli.set_read_timeout(1, 0); // 1 second timeout
  11853. auto handle = cli.open_stream("GET", "/slow-stream");
  11854. ASSERT_TRUE(handle.is_valid());
  11855. char buf[256];
  11856. ssize_t total = 0;
  11857. ssize_t n;
  11858. bool got_error = false;
  11859. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11860. total += n;
  11861. }
  11862. if (n < 0) {
  11863. got_error = true;
  11864. // Should be timeout or read error
  11865. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11866. handle.get_read_error() == Error::Read)
  11867. << "Actual error: " << to_string(handle.get_read_error());
  11868. }
  11869. // Either we got an error, or we got less data than expected
  11870. EXPECT_TRUE(got_error || total < 1000)
  11871. << "Expected timeout but got all " << total << " bytes";
  11872. svr.stop();
  11873. t.join();
  11874. }
  11875. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11876. // Test connection closed detection via BodyReader
  11877. Server svr;
  11878. std::atomic<bool> close_now{false};
  11879. svr.Get("/will-close", [&](const Request &, Response &res) {
  11880. res.set_content_provider(
  11881. 10000, // Large content_length that we won't fully send
  11882. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11883. if (offset < 100) {
  11884. std::string data(100, 'X');
  11885. sink.write(data.c_str(), data.size());
  11886. return true;
  11887. }
  11888. // Wait for signal then abort
  11889. while (!close_now) {
  11890. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11891. }
  11892. return false; // Abort - server will close connection
  11893. });
  11894. });
  11895. auto port = 8092;
  11896. std::thread t([&]() { svr.listen("localhost", port); });
  11897. svr.wait_until_ready();
  11898. Client cli("localhost", port);
  11899. auto handle = cli.open_stream("GET", "/will-close");
  11900. ASSERT_TRUE(handle.is_valid());
  11901. char buf[256];
  11902. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11903. EXPECT_GT(n, 0) << "First read should succeed";
  11904. // Signal server to close
  11905. close_now = true;
  11906. // Keep reading until error or EOF
  11907. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11908. // Keep reading
  11909. }
  11910. // Should get an error since content_length wasn't satisfied
  11911. if (n < 0) {
  11912. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11913. handle.get_read_error() == Error::Read)
  11914. << "Actual error: " << to_string(handle.get_read_error());
  11915. }
  11916. svr.stop();
  11917. t.join();
  11918. }
  11919. #ifdef CPPHTTPLIB_SSL_ENABLED
  11920. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11921. // Test that read timeout during SSL streaming is detected
  11922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11923. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11924. res.set_content_provider(
  11925. 1000, "text/plain",
  11926. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11927. if (offset < 100) {
  11928. std::string data(100, 'A');
  11929. sink.write(data.c_str(), data.size());
  11930. return true;
  11931. }
  11932. std::this_thread::sleep_for(std::chrono::seconds(3));
  11933. std::string data(900, 'B');
  11934. sink.write(data.c_str(), data.size());
  11935. return true;
  11936. });
  11937. });
  11938. auto port = 8093;
  11939. std::thread t([&]() { svr.listen("localhost", port); });
  11940. svr.wait_until_ready();
  11941. SSLClient cli("localhost", port);
  11942. cli.enable_server_certificate_verification(false);
  11943. cli.set_read_timeout(1, 0); // 1 second timeout
  11944. auto handle = cli.open_stream("GET", "/slow-stream");
  11945. ASSERT_TRUE(handle.is_valid());
  11946. char buf[256];
  11947. ssize_t total = 0;
  11948. ssize_t n;
  11949. bool got_error = false;
  11950. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11951. total += n;
  11952. }
  11953. if (n < 0) {
  11954. got_error = true;
  11955. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11956. handle.get_read_error() == Error::Read)
  11957. << "Actual error: " << to_string(handle.get_read_error());
  11958. }
  11959. EXPECT_TRUE(got_error || total < 1000)
  11960. << "Expected timeout but got all " << total << " bytes";
  11961. svr.stop();
  11962. t.join();
  11963. }
  11964. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11965. // Test SSL connection closed detection
  11966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11967. std::atomic<bool> close_now{false};
  11968. svr.Get("/will-close", [&](const Request &, Response &res) {
  11969. res.set_content_provider(
  11970. 10000, "text/plain",
  11971. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11972. if (offset < 100) {
  11973. std::string data(100, 'X');
  11974. sink.write(data.c_str(), data.size());
  11975. return true;
  11976. }
  11977. while (!close_now) {
  11978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11979. }
  11980. return false;
  11981. });
  11982. });
  11983. auto port = 8094;
  11984. std::thread t([&]() { svr.listen("localhost", port); });
  11985. svr.wait_until_ready();
  11986. SSLClient cli("localhost", port);
  11987. cli.enable_server_certificate_verification(false);
  11988. auto handle = cli.open_stream("GET", "/will-close");
  11989. ASSERT_TRUE(handle.is_valid());
  11990. char buf[256];
  11991. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11992. EXPECT_GT(n, 0);
  11993. // Signal server to close
  11994. close_now = true;
  11995. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11996. // Keep reading
  11997. }
  11998. if (n < 0) {
  11999. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12000. handle.get_read_error() == Error::Read)
  12001. << "Actual error: " << to_string(handle.get_read_error());
  12002. }
  12003. svr.stop();
  12004. t.join();
  12005. }
  12006. #endif
  12007. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12008. using namespace httplib;
  12009. // Create a test file
  12010. const char *fname = "etag_testfile.txt";
  12011. const char *content = "etag-content";
  12012. {
  12013. std::ofstream ofs(fname);
  12014. ofs << content;
  12015. ASSERT_TRUE(ofs.good());
  12016. }
  12017. Server svr;
  12018. svr.set_mount_point("/static", ".");
  12019. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12020. svr.wait_until_ready();
  12021. Client cli(HOST, PORT);
  12022. // First request: should get 200 with ETag header
  12023. auto res1 = cli.Get("/static/etag_testfile.txt");
  12024. ASSERT_TRUE(res1);
  12025. ASSERT_EQ(200, res1->status);
  12026. ASSERT_TRUE(res1->has_header("ETag"));
  12027. std::string etag = res1->get_header_value("ETag");
  12028. EXPECT_FALSE(etag.empty());
  12029. // Verify ETag format: W/"hex-hex"
  12030. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12031. EXPECT_EQ('W', etag[0]);
  12032. EXPECT_EQ('/', etag[1]);
  12033. EXPECT_EQ('"', etag[2]);
  12034. EXPECT_EQ('"', etag.back());
  12035. // Exact match: expect 304 Not Modified
  12036. Headers h2 = {{"If-None-Match", etag}};
  12037. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12038. ASSERT_TRUE(res2);
  12039. EXPECT_EQ(304, res2->status);
  12040. // Wildcard match: expect 304 Not Modified
  12041. Headers h3 = {{"If-None-Match", "*"}};
  12042. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12043. ASSERT_TRUE(res3);
  12044. EXPECT_EQ(304, res3->status);
  12045. // Non-matching ETag: expect 200
  12046. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12047. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12048. ASSERT_TRUE(res4);
  12049. EXPECT_EQ(200, res4->status);
  12050. // Multiple ETags with one matching: expect 304
  12051. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12052. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12053. ASSERT_TRUE(res5);
  12054. EXPECT_EQ(304, res5->status);
  12055. svr.stop();
  12056. t.join();
  12057. std::remove(fname);
  12058. }
  12059. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12060. using namespace httplib;
  12061. Server svr;
  12062. svr.set_mount_point("/static", ".");
  12063. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12064. svr.wait_until_ready();
  12065. Client cli(HOST, PORT);
  12066. // Send If-None-Match: * to a non-existent file
  12067. Headers h = {{"If-None-Match", "*"}};
  12068. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12069. ASSERT_TRUE(res);
  12070. EXPECT_EQ(404, res->status);
  12071. svr.stop();
  12072. t.join();
  12073. }
  12074. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12075. using namespace httplib;
  12076. // Create a test file
  12077. const char *fname = "etag_boundary_testfile.txt";
  12078. const char *content = "boundary-test";
  12079. {
  12080. std::ofstream ofs(fname);
  12081. ofs << content;
  12082. ASSERT_TRUE(ofs.good());
  12083. }
  12084. Server svr;
  12085. svr.set_mount_point("/static", ".");
  12086. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12087. svr.wait_until_ready();
  12088. Client cli(HOST, PORT);
  12089. // Get the actual ETag
  12090. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12091. ASSERT_TRUE(res1);
  12092. ASSERT_EQ(200, res1->status);
  12093. ASSERT_TRUE(res1->has_header("ETag"));
  12094. std::string etag = res1->get_header_value("ETag");
  12095. // Test 1: Very long ETag value (longer than actual ETag)
  12096. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12097. Headers h1 = {{"If-None-Match", "W/"
  12098. "\"very-long-etag-value-that-is-much-longer-"
  12099. "than-the-actual-etag-value\""}};
  12100. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12101. ASSERT_TRUE(res2);
  12102. EXPECT_EQ(200, res2->status); // Should not match
  12103. // Test 2: Long string followed by wildcard
  12104. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12105. // string)
  12106. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12107. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12108. ASSERT_TRUE(res3);
  12109. EXPECT_EQ(304, res3->status); // Should match on "*"
  12110. // Test 3: Wildcard followed by long string
  12111. // Should match on "*" immediately and return 304
  12112. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12113. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12114. ASSERT_TRUE(res4);
  12115. EXPECT_EQ(304, res4->status); // Should match on "*"
  12116. // Test 4: Multiple long non-matching values
  12117. // Should NOT match and return 200 (test that all comparisons are safe)
  12118. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12119. "W/\"second-long-non-matching-value\", "
  12120. "W/\"third-long-non-matching-value\""}};
  12121. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12122. ASSERT_TRUE(res5);
  12123. EXPECT_EQ(200, res5->status); // Should not match
  12124. // Test 5: Single character that is not "*" (edge case)
  12125. Headers h5 = {{"If-None-Match", "X"}};
  12126. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12127. ASSERT_TRUE(res6);
  12128. EXPECT_EQ(200, res6->status); // Should not match
  12129. svr.stop();
  12130. t.join();
  12131. std::remove(fname);
  12132. }
  12133. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12134. using namespace httplib;
  12135. // Create a test file
  12136. const char *fname = "ims_testfile.txt";
  12137. const char *content = "if-modified-since-test";
  12138. {
  12139. std::ofstream ofs(fname);
  12140. ofs << content;
  12141. ASSERT_TRUE(ofs.good());
  12142. }
  12143. Server svr;
  12144. svr.set_mount_point("/static", ".");
  12145. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12146. svr.wait_until_ready();
  12147. Client cli(HOST, PORT);
  12148. // First request: should get 200 with Last-Modified header
  12149. auto res1 = cli.Get("/static/ims_testfile.txt");
  12150. ASSERT_TRUE(res1);
  12151. ASSERT_EQ(200, res1->status);
  12152. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12153. std::string last_modified = res1->get_header_value("Last-Modified");
  12154. EXPECT_FALSE(last_modified.empty());
  12155. // If-Modified-Since with same time: expect 304
  12156. Headers h2 = {{"If-Modified-Since", last_modified}};
  12157. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12158. ASSERT_TRUE(res2);
  12159. EXPECT_EQ(304, res2->status);
  12160. // If-Modified-Since with future time: expect 304
  12161. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12162. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12163. ASSERT_TRUE(res3);
  12164. EXPECT_EQ(304, res3->status);
  12165. // If-Modified-Since with past time: expect 200
  12166. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12167. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12168. ASSERT_TRUE(res4);
  12169. EXPECT_EQ(200, res4->status);
  12170. // If-None-Match takes precedence over If-Modified-Since
  12171. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12172. ASSERT_TRUE(res1->has_header("ETag"));
  12173. std::string etag = res1->get_header_value("ETag");
  12174. Headers h5 = {{"If-None-Match", etag},
  12175. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12176. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12177. ASSERT_TRUE(res5);
  12178. EXPECT_EQ(304, res5->status);
  12179. svr.stop();
  12180. t.join();
  12181. std::remove(fname);
  12182. }
  12183. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12184. using namespace httplib;
  12185. Server svr;
  12186. // Endpoint that returns compressible content
  12187. svr.Get("/compressible", [](const Request &, Response &res) {
  12188. // Return a large enough body to trigger compression
  12189. std::string body(1000, 'a');
  12190. res.set_content(body, "text/plain");
  12191. });
  12192. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12193. svr.wait_until_ready();
  12194. Client cli(HOST, PORT);
  12195. // Request with gzip support: should get Vary header when compressed
  12196. cli.set_compress(true);
  12197. auto res1 = cli.Get("/compressible");
  12198. ASSERT_TRUE(res1);
  12199. EXPECT_EQ(200, res1->status);
  12200. // If Content-Encoding is set, Vary should also be set
  12201. if (res1->has_header("Content-Encoding")) {
  12202. EXPECT_TRUE(res1->has_header("Vary"));
  12203. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12204. }
  12205. // Request without Accept-Encoding header: should not have compression
  12206. Headers h_no_compress;
  12207. auto res2 = cli.Get("/compressible", h_no_compress);
  12208. ASSERT_TRUE(res2);
  12209. EXPECT_EQ(200, res2->status);
  12210. // Verify Vary header is present when compression is applied
  12211. // (the exact behavior depends on server configuration)
  12212. svr.stop();
  12213. t.join();
  12214. }
  12215. TEST(ETagTest, IfRangeWithETag) {
  12216. using namespace httplib;
  12217. // Create a test file with known content
  12218. const char *fname = "if_range_testfile.txt";
  12219. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12220. {
  12221. std::ofstream ofs(fname);
  12222. ofs << content;
  12223. ASSERT_TRUE(ofs.good());
  12224. }
  12225. Server svr;
  12226. svr.set_mount_point("/static", ".");
  12227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12228. svr.wait_until_ready();
  12229. Client cli(HOST, PORT);
  12230. // First request: get ETag
  12231. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12232. ASSERT_TRUE(res1);
  12233. ASSERT_EQ(200, res1->status);
  12234. ASSERT_TRUE(res1->has_header("ETag"));
  12235. std::string etag = res1->get_header_value("ETag");
  12236. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12237. // Since our server generates weak ETags (W/"..."), If-Range with our
  12238. // ETag should NOT result in partial content - it should return full content.
  12239. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12240. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12241. ASSERT_TRUE(res2);
  12242. // Weak ETag in If-Range -> full content (200), not partial (206)
  12243. EXPECT_EQ(200, res2->status);
  12244. EXPECT_EQ(content, res2->body);
  12245. EXPECT_FALSE(res2->has_header("Content-Range"));
  12246. // Range request with non-matching If-Range (ETag): should get 200 (full
  12247. // content)
  12248. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12249. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12250. ASSERT_TRUE(res3);
  12251. EXPECT_EQ(200, res3->status);
  12252. EXPECT_EQ(content, res3->body);
  12253. EXPECT_FALSE(res3->has_header("Content-Range"));
  12254. // Range request with strong ETag (hypothetical - our server doesn't generate
  12255. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12256. // should return full content)
  12257. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12258. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12259. ASSERT_TRUE(res4);
  12260. EXPECT_EQ(200, res4->status);
  12261. EXPECT_EQ(content, res4->body);
  12262. EXPECT_FALSE(res4->has_header("Content-Range"));
  12263. svr.stop();
  12264. t.join();
  12265. std::remove(fname);
  12266. }
  12267. TEST(ETagTest, IfRangeWithDate) {
  12268. using namespace httplib;
  12269. // Create a test file
  12270. const char *fname = "if_range_date_testfile.txt";
  12271. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12272. {
  12273. std::ofstream ofs(fname);
  12274. ofs << content;
  12275. ASSERT_TRUE(ofs.good());
  12276. }
  12277. Server svr;
  12278. svr.set_mount_point("/static", ".");
  12279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12280. svr.wait_until_ready();
  12281. Client cli(HOST, PORT);
  12282. // First request: get Last-Modified
  12283. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12284. ASSERT_TRUE(res1);
  12285. ASSERT_EQ(200, res1->status);
  12286. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12287. std::string last_modified = res1->get_header_value("Last-Modified");
  12288. // Range request with matching If-Range (date): should get 206
  12289. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12290. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12291. ASSERT_TRUE(res2);
  12292. EXPECT_EQ(206, res2->status);
  12293. EXPECT_EQ("FGHIJ", res2->body);
  12294. // Range request with old If-Range date: should get 200 (full content)
  12295. Headers h3 = {{"Range", "bytes=5-9"},
  12296. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12297. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12298. ASSERT_TRUE(res3);
  12299. EXPECT_EQ(200, res3->status);
  12300. EXPECT_EQ(content, res3->body);
  12301. // Range request with future If-Range date: should get 206
  12302. Headers h4 = {{"Range", "bytes=0-4"},
  12303. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12304. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12305. ASSERT_TRUE(res4);
  12306. EXPECT_EQ(206, res4->status);
  12307. EXPECT_EQ("ABCDE", res4->body);
  12308. svr.stop();
  12309. t.join();
  12310. std::remove(fname);
  12311. }
  12312. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12313. using namespace httplib;
  12314. const char *fname = "etag_malformed.txt";
  12315. const char *content = "malformed-etag";
  12316. {
  12317. std::ofstream ofs(fname);
  12318. ofs << content;
  12319. ASSERT_TRUE(ofs.good());
  12320. }
  12321. Server svr;
  12322. svr.set_mount_point("/static", ".");
  12323. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12324. svr.wait_until_ready();
  12325. Client cli(HOST, PORT);
  12326. // baseline: should get 200 and an ETag
  12327. auto res1 = cli.Get("/static/etag_malformed.txt");
  12328. ASSERT_TRUE(res1);
  12329. ASSERT_EQ(200, res1->status);
  12330. ASSERT_TRUE(res1->has_header("ETag"));
  12331. // Malformed ETag value (missing quotes) should be treated as non-matching
  12332. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12333. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12334. ASSERT_TRUE(res_bad);
  12335. EXPECT_EQ(200, res_bad->status);
  12336. // Whitespace-only header value should be considered invalid / non-matching
  12337. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12338. "Host: localhost\r\n"
  12339. "If-None-Match: \r\n"
  12340. "Connection: close\r\n"
  12341. "\r\n";
  12342. std::string out;
  12343. ASSERT_TRUE(send_request(5, raw_req, &out));
  12344. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12345. svr.stop();
  12346. t.join();
  12347. std::remove(fname);
  12348. }
  12349. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12350. using namespace httplib;
  12351. const char *fname = "ims_invalid_format.txt";
  12352. const char *content = "ims-bad-format";
  12353. {
  12354. std::ofstream ofs(fname);
  12355. ofs << content;
  12356. ASSERT_TRUE(ofs.good());
  12357. }
  12358. Server svr;
  12359. svr.set_mount_point("/static", ".");
  12360. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12361. svr.wait_until_ready();
  12362. Client cli(HOST, PORT);
  12363. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12364. ASSERT_TRUE(res1);
  12365. ASSERT_EQ(200, res1->status);
  12366. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12367. // If-Modified-Since with invalid format should not result in 304
  12368. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12369. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12370. ASSERT_TRUE(res_bad);
  12371. EXPECT_EQ(200, res_bad->status);
  12372. // If-Range with invalid date format should be treated as mismatch -> full
  12373. // content (200)
  12374. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12375. {"If-Range", "invalid-date"}};
  12376. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12377. ASSERT_TRUE(res_ifrange);
  12378. EXPECT_EQ(200, res_ifrange->status);
  12379. svr.stop();
  12380. t.join();
  12381. std::remove(fname);
  12382. }
  12383. TEST(ETagTest, IfRangeWithMalformedETag) {
  12384. using namespace httplib;
  12385. const char *fname = "ifrange_malformed.txt";
  12386. const std::string content = "0123456789";
  12387. {
  12388. std::ofstream ofs(fname);
  12389. ofs << content;
  12390. ASSERT_TRUE(ofs.good());
  12391. }
  12392. Server svr;
  12393. svr.set_mount_point("/static", ".");
  12394. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12395. svr.wait_until_ready();
  12396. Client cli(HOST, PORT);
  12397. // First request: get ETag
  12398. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12399. ASSERT_TRUE(res1);
  12400. ASSERT_EQ(200, res1->status);
  12401. ASSERT_TRUE(res1->has_header("ETag"));
  12402. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12403. // full content (200)
  12404. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12405. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12406. ASSERT_TRUE(res2);
  12407. EXPECT_EQ(200, res2->status);
  12408. EXPECT_EQ(content, res2->body);
  12409. svr.stop();
  12410. t.join();
  12411. std::remove(fname);
  12412. }
  12413. TEST(ETagTest, ExtremeLargeDateValues) {
  12414. using namespace httplib;
  12415. const char *fname = "ims_extreme_date.txt";
  12416. const char *content = "ims-extreme-date";
  12417. {
  12418. std::ofstream ofs(fname);
  12419. ofs << content;
  12420. ASSERT_TRUE(ofs.good());
  12421. }
  12422. Server svr;
  12423. svr.set_mount_point("/static", ".");
  12424. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12425. svr.wait_until_ready();
  12426. Client cli(HOST, PORT);
  12427. auto res1 = cli.Get(std::string("/static/") + fname);
  12428. ASSERT_TRUE(res1);
  12429. ASSERT_EQ(200, res1->status);
  12430. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12431. // Extremely large year that may overflow date parsing routines.
  12432. Headers h_large_date = {
  12433. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12434. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12435. ASSERT_TRUE(res_bad);
  12436. // Expect server to treat this as invalid/mismatch and return full content
  12437. EXPECT_EQ(200, res_bad->status);
  12438. // If-Range with extremely large date should be treated as mismatch -> full
  12439. // content (200)
  12440. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12441. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12442. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12443. ASSERT_TRUE(res_ifrange);
  12444. EXPECT_EQ(200, res_ifrange->status);
  12445. svr.stop();
  12446. t.join();
  12447. std::remove(fname);
  12448. }
  12449. TEST(ETagTest, NegativeFileModificationTime) {
  12450. using namespace httplib;
  12451. const char *fname = "ims_negative_mtime.txt";
  12452. const std::string content = "negative-mtime";
  12453. {
  12454. std::ofstream ofs(fname);
  12455. ofs << content;
  12456. ASSERT_TRUE(ofs.good());
  12457. }
  12458. // Try to set file mtime to a negative value. This may fail on some
  12459. // platforms/filesystems; if it fails, the test will still verify server
  12460. // behaves safely by performing a regular conditional request.
  12461. #if defined(__APPLE__) || defined(__linux__)
  12462. bool set_negative = false;
  12463. do {
  12464. struct timeval times[2];
  12465. // access time: now
  12466. times[0].tv_sec = time(nullptr);
  12467. times[0].tv_usec = 0;
  12468. // modification time: negative (e.g., -1)
  12469. times[1].tv_sec = -1;
  12470. times[1].tv_usec = 0;
  12471. if (utimes(fname, times) == 0) { set_negative = true; }
  12472. } while (0);
  12473. #else
  12474. bool set_negative = false;
  12475. #endif
  12476. Server svr;
  12477. svr.set_mount_point("/static", ".");
  12478. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12479. svr.wait_until_ready();
  12480. Client cli(HOST, PORT);
  12481. auto res1 = cli.Get(std::string("/static/") + fname);
  12482. ASSERT_TRUE(res1);
  12483. ASSERT_EQ(200, res1->status);
  12484. bool has_last_modified = res1->has_header("Last-Modified");
  12485. std::string last_modified;
  12486. if (has_last_modified) {
  12487. last_modified = res1->get_header_value("Last-Modified");
  12488. }
  12489. if (set_negative) {
  12490. // If we successfully set a negative mtime, ensure server returns a
  12491. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12492. // with an old date and ensure server handles it without crash.
  12493. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12494. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12495. ASSERT_TRUE(res2);
  12496. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12497. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12498. } else {
  12499. // Could not set negative mtime on this platform; fall back to verifying
  12500. // that normal invalid/malformed dates are treated safely (non-304).
  12501. Headers h_bad_date = {
  12502. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12503. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12504. ASSERT_TRUE(res_bad);
  12505. EXPECT_EQ(200, res_bad->status);
  12506. }
  12507. svr.stop();
  12508. t.join();
  12509. std::remove(fname);
  12510. }
  12511. //==============================================================================
  12512. // SSE Parsing Tests
  12513. //==============================================================================
  12514. class SSEParsingTest : public ::testing::Test {
  12515. protected:
  12516. // Test helper that mimics SSE parsing behavior
  12517. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12518. int &retry_ms) {
  12519. // Blank line signals end of event
  12520. if (line.empty() || line == "\r") { return true; }
  12521. // Lines starting with ':' are comments (ignored)
  12522. if (!line.empty() && line[0] == ':') { return false; }
  12523. // Find the colon separator
  12524. auto colon_pos = line.find(':');
  12525. if (colon_pos == std::string::npos) {
  12526. // Line with no colon is treated as field name with empty value
  12527. return false;
  12528. }
  12529. std::string field = line.substr(0, colon_pos);
  12530. std::string value;
  12531. // Value starts after colon, skip optional single space
  12532. if (colon_pos + 1 < line.size()) {
  12533. size_t value_start = colon_pos + 1;
  12534. if (line[value_start] == ' ') { value_start++; }
  12535. value = line.substr(value_start);
  12536. // Remove trailing \r if present
  12537. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12538. }
  12539. // Handle known fields
  12540. if (field == "event") {
  12541. msg.event = value;
  12542. } else if (field == "data") {
  12543. // Multiple data lines are concatenated with newlines
  12544. if (!msg.data.empty()) { msg.data += "\n"; }
  12545. msg.data += value;
  12546. } else if (field == "id") {
  12547. // Empty id is valid (clears the last event ID)
  12548. msg.id = value;
  12549. } else if (field == "retry") {
  12550. // Parse retry interval in milliseconds
  12551. {
  12552. int v = 0;
  12553. auto res =
  12554. detail::from_chars(value.data(), value.data() + value.size(), v);
  12555. if (res.ec == std::errc{}) { retry_ms = v; }
  12556. }
  12557. }
  12558. // Unknown fields are ignored per SSE spec
  12559. return false;
  12560. }
  12561. };
  12562. // Test: Single-line data
  12563. TEST_F(SSEParsingTest, SingleLineData) {
  12564. sse::SSEMessage msg;
  12565. int retry_ms = 3000;
  12566. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12567. EXPECT_EQ(msg.data, "hello");
  12568. EXPECT_EQ(msg.event, "message");
  12569. // Blank line ends event
  12570. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12571. }
  12572. // Test: Multi-line data
  12573. TEST_F(SSEParsingTest, MultiLineData) {
  12574. sse::SSEMessage msg;
  12575. int retry_ms = 3000;
  12576. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12577. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12578. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12579. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12580. }
  12581. // Test: Custom event types
  12582. TEST_F(SSEParsingTest, CustomEventType) {
  12583. sse::SSEMessage msg;
  12584. int retry_ms = 3000;
  12585. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12586. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12587. EXPECT_EQ(msg.event, "update");
  12588. EXPECT_EQ(msg.data, "payload");
  12589. }
  12590. // Test: Event ID handling
  12591. TEST_F(SSEParsingTest, EventIdHandling) {
  12592. sse::SSEMessage msg;
  12593. int retry_ms = 3000;
  12594. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12595. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12596. EXPECT_EQ(msg.id, "12345");
  12597. }
  12598. // Test: Empty event ID (clears last event ID)
  12599. TEST_F(SSEParsingTest, EmptyEventId) {
  12600. sse::SSEMessage msg;
  12601. msg.id = "previous";
  12602. int retry_ms = 3000;
  12603. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12604. EXPECT_EQ(msg.id, "");
  12605. }
  12606. // Test: Retry field parsing
  12607. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12608. sse::SSEMessage msg;
  12609. int retry_ms = 3000;
  12610. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12611. EXPECT_EQ(retry_ms, 5000);
  12612. }
  12613. // Test: Invalid retry value
  12614. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12615. sse::SSEMessage msg;
  12616. int retry_ms = 3000;
  12617. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12618. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12619. }
  12620. // Test: Comments (lines starting with :)
  12621. TEST_F(SSEParsingTest, CommentsIgnored) {
  12622. sse::SSEMessage msg;
  12623. int retry_ms = 3000;
  12624. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12625. EXPECT_EQ(msg.data, "");
  12626. EXPECT_EQ(msg.event, "message");
  12627. }
  12628. // Test: Colon in value
  12629. TEST_F(SSEParsingTest, ColonInValue) {
  12630. sse::SSEMessage msg;
  12631. int retry_ms = 3000;
  12632. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12633. EXPECT_EQ(msg.data, "hello:world:test");
  12634. }
  12635. // Test: Line with no colon (field name only)
  12636. TEST_F(SSEParsingTest, FieldNameOnly) {
  12637. sse::SSEMessage msg;
  12638. int retry_ms = 3000;
  12639. // According to SSE spec, this is treated as field name with empty value
  12640. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12641. // Since we don't recognize "data" without colon, data should be empty
  12642. EXPECT_EQ(msg.data, "");
  12643. }
  12644. // Test: Trailing \r handling
  12645. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12646. sse::SSEMessage msg;
  12647. int retry_ms = 3000;
  12648. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12649. EXPECT_EQ(msg.data, "hello");
  12650. }
  12651. // Test: Unknown fields ignored
  12652. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12653. sse::SSEMessage msg;
  12654. int retry_ms = 3000;
  12655. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12656. EXPECT_EQ(msg.data, "");
  12657. EXPECT_EQ(msg.event, "message");
  12658. }
  12659. // Test: Space after colon is optional
  12660. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12661. sse::SSEMessage msg1, msg2;
  12662. int retry_ms = 3000;
  12663. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12664. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12665. EXPECT_EQ(msg1.data, "hello");
  12666. EXPECT_EQ(msg2.data, "hello");
  12667. }
  12668. // Test: SSEMessage clear
  12669. TEST_F(SSEParsingTest, MessageClear) {
  12670. sse::SSEMessage msg;
  12671. msg.event = "custom";
  12672. msg.data = "some data";
  12673. msg.id = "123";
  12674. msg.clear();
  12675. EXPECT_EQ(msg.event, "message");
  12676. EXPECT_EQ(msg.data, "");
  12677. EXPECT_EQ(msg.id, "");
  12678. }
  12679. // Test: Complete event parsing
  12680. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12681. sse::SSEMessage msg;
  12682. int retry_ms = 3000;
  12683. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12684. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12685. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12686. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12687. // Blank line ends event
  12688. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12689. EXPECT_EQ(msg.event, "notification");
  12690. EXPECT_EQ(msg.id, "evt-42");
  12691. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12692. EXPECT_EQ(retry_ms, 1000);
  12693. }
  12694. //==============================================================================
  12695. // Integration Tests with Server
  12696. //==============================================================================
  12697. class SSEIntegrationTest : public ::testing::Test {
  12698. protected:
  12699. void SetUp() override {
  12700. stop_server_.store(false);
  12701. events_.clear();
  12702. server_ = httplib::detail::make_unique<Server>();
  12703. setup_server();
  12704. start_server();
  12705. }
  12706. void TearDown() override {
  12707. stop_server_.store(true);
  12708. event_cv_.notify_all();
  12709. server_->stop();
  12710. if (server_thread_.joinable()) { server_thread_.join(); }
  12711. }
  12712. void setup_server() {
  12713. // Simple SSE endpoint
  12714. server_->Get("/events", [this](const Request &req, Response &res) {
  12715. auto last_id = req.get_header_value("Last-Event-ID");
  12716. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12717. res.set_chunked_content_provider(
  12718. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12719. std::unique_lock<std::mutex> lock(event_mutex_);
  12720. if (event_cv_.wait_for(
  12721. lock, std::chrono::milliseconds(200), [this] {
  12722. return !events_.empty() || stop_server_.load();
  12723. })) {
  12724. if (stop_server_.load()) { return false; }
  12725. if (!events_.empty()) {
  12726. std::string event = events_.front();
  12727. events_.erase(events_.begin());
  12728. sink.write(event.data(), event.size());
  12729. return true;
  12730. }
  12731. }
  12732. return !stop_server_.load();
  12733. });
  12734. });
  12735. // Endpoint that returns error
  12736. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12737. res.status = 500;
  12738. res.set_content("Internal Server Error", "text/plain");
  12739. });
  12740. // Endpoint for custom event types
  12741. server_->Get("/custom-events", [](const Request &, Response &res) {
  12742. res.set_chunked_content_provider(
  12743. "text/event-stream", [](size_t offset, DataSink &sink) {
  12744. if (offset == 0) {
  12745. std::string event = "event: update\ndata: updated\n\n"
  12746. "event: delete\ndata: deleted\n\n";
  12747. sink.write(event.data(), event.size());
  12748. }
  12749. return false; // End stream after sending
  12750. });
  12751. });
  12752. }
  12753. void start_server() {
  12754. port_ = server_->bind_to_any_port(HOST);
  12755. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12756. // Wait for server to start
  12757. while (!server_->is_running()) {
  12758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12759. }
  12760. }
  12761. int get_port() const { return port_; }
  12762. void send_event(const std::string &event) {
  12763. std::lock_guard<std::mutex> lock(event_mutex_);
  12764. events_.push_back(event);
  12765. event_cv_.notify_all();
  12766. }
  12767. std::unique_ptr<Server> server_;
  12768. std::thread server_thread_;
  12769. std::mutex event_mutex_;
  12770. std::condition_variable event_cv_;
  12771. std::vector<std::string> events_;
  12772. std::atomic<bool> stop_server_{false};
  12773. std::string last_received_event_id_;
  12774. int port_ = 0;
  12775. };
  12776. // Test: Successful connection and on_open callback
  12777. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12778. // Add a simple endpoint that sends one event and closes
  12779. server_->Get("/simple-event", [](const Request &, Response &res) {
  12780. res.set_chunked_content_provider(
  12781. "text/event-stream", [](size_t offset, DataSink &sink) {
  12782. if (offset == 0) {
  12783. std::string event = "data: hello\n\n";
  12784. sink.write(event.data(), event.size());
  12785. }
  12786. return false; // Close stream after sending
  12787. });
  12788. });
  12789. Client client("localhost", get_port());
  12790. sse::SSEClient sse(client, "/simple-event");
  12791. std::atomic<bool> open_called{false};
  12792. std::atomic<bool> message_received{false};
  12793. sse.on_open([&open_called]() { open_called.store(true); });
  12794. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12795. if (msg.data == "hello") { message_received.store(true); }
  12796. });
  12797. sse.set_reconnect_interval(100);
  12798. sse.set_max_reconnect_attempts(1);
  12799. // Start async
  12800. sse.start_async();
  12801. // Wait for message to be processed
  12802. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12803. sse.stop();
  12804. EXPECT_TRUE(open_called.load());
  12805. EXPECT_TRUE(message_received.load());
  12806. }
  12807. // Test: on_message callback
  12808. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12809. // Endpoint that sends multiple events then closes
  12810. server_->Get("/multi-event", [](const Request &, Response &res) {
  12811. res.set_chunked_content_provider(
  12812. "text/event-stream", [](size_t offset, DataSink &sink) {
  12813. if (offset == 0) {
  12814. std::string events = "data: message1\n\ndata: message2\n\n";
  12815. sink.write(events.data(), events.size());
  12816. }
  12817. return false;
  12818. });
  12819. });
  12820. Client client("localhost", get_port());
  12821. sse::SSEClient sse(client, "/multi-event");
  12822. std::vector<std::string> received_messages;
  12823. std::mutex messages_mutex;
  12824. sse.on_message([&](const sse::SSEMessage &msg) {
  12825. std::lock_guard<std::mutex> lock(messages_mutex);
  12826. received_messages.push_back(msg.data);
  12827. });
  12828. sse.set_reconnect_interval(100);
  12829. sse.set_max_reconnect_attempts(1);
  12830. sse.start_async();
  12831. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12832. sse.stop();
  12833. std::lock_guard<std::mutex> lock(messages_mutex);
  12834. EXPECT_GE(received_messages.size(), 2u);
  12835. if (received_messages.size() >= 2) {
  12836. EXPECT_EQ(received_messages[0], "message1");
  12837. EXPECT_EQ(received_messages[1], "message2");
  12838. }
  12839. }
  12840. // Test: on_event for specific types
  12841. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12842. Client client("localhost", get_port());
  12843. sse::SSEClient sse(client, "/custom-events");
  12844. std::atomic<bool> update_received{false};
  12845. std::atomic<bool> delete_received{false};
  12846. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12847. if (msg.data == "updated") { update_received.store(true); }
  12848. });
  12849. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12850. if (msg.data == "deleted") { delete_received.store(true); }
  12851. });
  12852. sse.set_max_reconnect_attempts(1);
  12853. sse.start_async();
  12854. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12855. sse.stop();
  12856. EXPECT_TRUE(update_received.load());
  12857. EXPECT_TRUE(delete_received.load());
  12858. }
  12859. // Test: on_error callback on connection failure
  12860. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12861. // Connect to a non-existent port
  12862. Client client("localhost", 59999);
  12863. sse::SSEClient sse(client, "/events");
  12864. std::atomic<bool> error_called{false};
  12865. Error received_error = Error::Success;
  12866. sse.on_error([&](Error err) {
  12867. error_called.store(true);
  12868. received_error = err;
  12869. });
  12870. sse.set_reconnect_interval(50);
  12871. sse.set_max_reconnect_attempts(1);
  12872. sse.start_async();
  12873. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12874. sse.stop();
  12875. EXPECT_TRUE(error_called.load());
  12876. EXPECT_NE(received_error, Error::Success);
  12877. }
  12878. // Test: Last-Event-ID header sent on reconnect
  12879. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12880. // Endpoint that sends event with ID
  12881. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12882. res.set_chunked_content_provider(
  12883. "text/event-stream", [](size_t offset, DataSink &sink) {
  12884. if (offset == 0) {
  12885. std::string event = "id: evt-123\ndata: test\n\n";
  12886. sink.write(event.data(), event.size());
  12887. }
  12888. return false;
  12889. });
  12890. });
  12891. Client client("localhost", get_port());
  12892. sse::SSEClient sse(client, "/event-with-id");
  12893. std::atomic<bool> id_received{false};
  12894. sse.on_message([&](const sse::SSEMessage &msg) {
  12895. if (!msg.id.empty()) { id_received.store(true); }
  12896. });
  12897. sse.set_reconnect_interval(100);
  12898. sse.set_max_reconnect_attempts(1);
  12899. sse.start_async();
  12900. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12901. sse.stop();
  12902. EXPECT_TRUE(id_received.load());
  12903. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12904. }
  12905. // Test: Manual stop
  12906. TEST_F(SSEIntegrationTest, ManualStop) {
  12907. // Endpoint that sends one event and stays open briefly
  12908. std::atomic<bool> handler_running{true};
  12909. server_->Get("/stay-open", [&handler_running](const Request &,
  12910. Response &res) {
  12911. res.set_chunked_content_provider(
  12912. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12913. if (offset == 0) {
  12914. std::string event = "data: connected\n\n";
  12915. sink.write(event.data(), event.size());
  12916. }
  12917. // Keep connection open while handler_running is true
  12918. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12919. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12920. }
  12921. return false;
  12922. });
  12923. });
  12924. Client client("localhost", get_port());
  12925. sse::SSEClient sse(client, "/stay-open");
  12926. std::atomic<bool> connected{false};
  12927. sse.on_open([&connected]() { connected.store(true); });
  12928. sse.set_reconnect_interval(100);
  12929. sse.set_max_reconnect_attempts(1);
  12930. sse.start_async();
  12931. // Wait for connection to establish
  12932. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12933. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12934. }
  12935. EXPECT_TRUE(connected.load());
  12936. EXPECT_TRUE(sse.is_connected());
  12937. // Signal handler to stop
  12938. handler_running.store(false);
  12939. // Stop SSE client
  12940. sse.stop();
  12941. EXPECT_FALSE(sse.is_connected());
  12942. }
  12943. // Test: SSEClient with custom headers
  12944. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12945. // Setup a server endpoint that checks for custom header
  12946. std::atomic<bool> header_received{false};
  12947. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12948. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12949. header_received.store(true);
  12950. }
  12951. res.set_chunked_content_provider("text/event-stream",
  12952. [](size_t, DataSink &) { return false; });
  12953. });
  12954. Client client("localhost", get_port());
  12955. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12956. sse::SSEClient sse(client, "/header-check", headers);
  12957. sse.set_max_reconnect_attempts(1);
  12958. sse.start_async();
  12959. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12960. sse.stop();
  12961. EXPECT_TRUE(header_received.load());
  12962. }
  12963. // Test: Reconnect interval configuration
  12964. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12965. Client client("localhost", get_port());
  12966. sse::SSEClient sse(client, "/events");
  12967. auto &result = sse.set_reconnect_interval(500);
  12968. // Builder pattern should return reference to self
  12969. EXPECT_EQ(&result, &sse);
  12970. }
  12971. // Test: Max reconnect attempts
  12972. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12973. // Connect to non-existent port to force reconnects
  12974. Client client("localhost", 59998);
  12975. sse::SSEClient sse(client, "/events");
  12976. std::atomic<int> error_count{0};
  12977. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12978. sse.set_reconnect_interval(50);
  12979. sse.set_max_reconnect_attempts(2);
  12980. auto start = std::chrono::steady_clock::now();
  12981. sse.start(); // Blocking call
  12982. auto end = std::chrono::steady_clock::now();
  12983. // Should have stopped after 2 failed attempts
  12984. EXPECT_GE(error_count.load(), 2);
  12985. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12986. auto duration =
  12987. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12988. #ifdef _WIN32
  12989. // Windows is much slower for socket connection failures
  12990. EXPECT_LT(duration.count(), 7000);
  12991. #else
  12992. EXPECT_LT(duration.count(), 1000);
  12993. #endif
  12994. }
  12995. // Test: Multi-line data in integration
  12996. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12997. // Endpoint with multi-line data
  12998. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12999. res.set_chunked_content_provider(
  13000. "text/event-stream", [](size_t offset, DataSink &sink) {
  13001. if (offset == 0) {
  13002. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13003. sink.write(event.data(), event.size());
  13004. }
  13005. return false;
  13006. });
  13007. });
  13008. Client client("localhost", get_port());
  13009. sse::SSEClient sse(client, "/multiline-data");
  13010. std::string received_data;
  13011. std::mutex data_mutex;
  13012. sse.on_message([&](const sse::SSEMessage &msg) {
  13013. std::lock_guard<std::mutex> lock(data_mutex);
  13014. received_data = msg.data;
  13015. });
  13016. sse.set_reconnect_interval(100);
  13017. sse.set_max_reconnect_attempts(1);
  13018. sse.start_async();
  13019. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13020. sse.stop();
  13021. std::lock_guard<std::mutex> lock(data_mutex);
  13022. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13023. }
  13024. // Test: Auto-reconnect after server disconnection
  13025. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13026. std::atomic<int> connection_count{0};
  13027. std::atomic<int> message_count{0};
  13028. // Endpoint that sends one event and closes, forcing reconnect
  13029. server_->Get("/reconnect-test",
  13030. [&connection_count](const Request &, Response &res) {
  13031. connection_count.fetch_add(1);
  13032. res.set_chunked_content_provider(
  13033. "text/event-stream", [](size_t offset, DataSink &sink) {
  13034. if (offset == 0) {
  13035. std::string event = "data: hello\n\n";
  13036. sink.write(event.data(), event.size());
  13037. }
  13038. return false; // Close connection after sending
  13039. });
  13040. });
  13041. Client client("localhost", get_port());
  13042. sse::SSEClient sse(client, "/reconnect-test");
  13043. sse.on_message([&message_count](const sse::SSEMessage &) {
  13044. message_count.fetch_add(1);
  13045. });
  13046. sse.set_reconnect_interval(100);
  13047. sse.set_max_reconnect_attempts(3);
  13048. sse.start_async();
  13049. // Wait long enough for multiple reconnects
  13050. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13051. sse.stop();
  13052. // Should have connected multiple times (initial + reconnects)
  13053. EXPECT_GE(connection_count.load(), 2);
  13054. // Should have received messages from multiple connections
  13055. EXPECT_GE(message_count.load(), 2);
  13056. }
  13057. // Test: Last-Event-ID sent on reconnect
  13058. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13059. std::atomic<int> connection_count{0};
  13060. std::vector<std::string> received_last_event_ids;
  13061. std::mutex id_mutex;
  13062. // Endpoint that checks Last-Event-ID header and sends event with ID
  13063. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13064. int conn = connection_count.fetch_add(1);
  13065. // Capture the Last-Event-ID header from each connection
  13066. {
  13067. std::lock_guard<std::mutex> lock(id_mutex);
  13068. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13069. }
  13070. res.set_chunked_content_provider(
  13071. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13072. if (offset == 0) {
  13073. std::string event =
  13074. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13075. sink.write(event.data(), event.size());
  13076. }
  13077. return false;
  13078. });
  13079. });
  13080. Client client("localhost", get_port());
  13081. sse::SSEClient sse(client, "/reconnect-with-id");
  13082. sse.set_reconnect_interval(100);
  13083. sse.set_max_reconnect_attempts(3);
  13084. sse.start_async();
  13085. // Wait for at least 2 connections
  13086. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13087. sse.stop();
  13088. // Verify behavior
  13089. std::lock_guard<std::mutex> lock(id_mutex);
  13090. EXPECT_GE(received_last_event_ids.size(), 2u);
  13091. // First connection should have no Last-Event-ID
  13092. if (!received_last_event_ids.empty()) {
  13093. EXPECT_EQ(received_last_event_ids[0], "");
  13094. }
  13095. // Second connection should have Last-Event-ID from first connection
  13096. if (received_last_event_ids.size() >= 2) {
  13097. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13098. }
  13099. }
  13100. TEST(Issue2318Test, EmptyHostString) {
  13101. {
  13102. httplib::Client cli_empty("", PORT);
  13103. auto res = cli_empty.Get("/");
  13104. ASSERT_FALSE(res);
  13105. EXPECT_EQ(httplib::Error::Connection, res.error());
  13106. }
  13107. {
  13108. httplib::Client cli(" ", PORT);
  13109. auto res = cli.Get("/");
  13110. ASSERT_FALSE(res);
  13111. EXPECT_EQ(httplib::Error::Connection, res.error());
  13112. }
  13113. }
  13114. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13115. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13116. Server svr;
  13117. // Set a small payload limit (1KB)
  13118. svr.set_payload_max_length(1024);
  13119. svr.Post("/test", [&](const Request &req, Response &res) {
  13120. res.set_content("Body size: " + std::to_string(req.body.size()),
  13121. "text/plain");
  13122. });
  13123. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13124. auto se = detail::scope_exit([&] {
  13125. svr.stop();
  13126. listen_thread.join();
  13127. });
  13128. svr.wait_until_ready();
  13129. // Create data that compresses well but exceeds limit when decompressed
  13130. // 8KB of repeated null bytes compresses to a very small size
  13131. std::string original_data(8 * 1024, '\0');
  13132. // Compress the data using gzip
  13133. std::string compressed_data;
  13134. detail::gzip_compressor compressor;
  13135. compressor.compress(original_data.data(), original_data.size(), true,
  13136. [&](const char *data, size_t size) {
  13137. compressed_data.append(data, size);
  13138. return true;
  13139. });
  13140. // Verify compression worked (compressed should be much smaller)
  13141. ASSERT_LT(compressed_data.size(), original_data.size());
  13142. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13143. // Send compressed data with Content-Encoding: gzip
  13144. Client cli(HOST, PORT);
  13145. Headers headers = {{"Content-Encoding", "gzip"}};
  13146. auto res =
  13147. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13148. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13149. ASSERT_TRUE(res);
  13150. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13151. }
  13152. #endif
  13153. // ============================================================================
  13154. // OpenSSL-Specific Tests
  13155. // ============================================================================
  13156. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13157. X509 *readCertificate(const std::string &strFileName) {
  13158. std::ifstream inStream(strFileName);
  13159. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13160. std::istreambuf_iterator<char>());
  13161. if (strCertPEM.empty()) return (nullptr);
  13162. BIO *pbCert = BIO_new(BIO_s_mem());
  13163. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13164. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13165. BIO_free(pbCert);
  13166. return (pCert);
  13167. }
  13168. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13169. std::ifstream inStream(strFileName);
  13170. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13171. std::istreambuf_iterator<char>());
  13172. if (strPrivateKeyPEM.empty()) return (nullptr);
  13173. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13174. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13175. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13176. BIO_free(pbPrivKey);
  13177. return (pPrivateKey);
  13178. }
  13179. TEST(BindServerTest, UpdateCerts) {
  13180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13181. int port = svr.bind_to_any_port("0.0.0.0");
  13182. ASSERT_TRUE(svr.is_valid());
  13183. ASSERT_TRUE(port > 0);
  13184. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13185. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13186. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13187. ASSERT_TRUE(cert != nullptr);
  13188. ASSERT_TRUE(ca_cert != nullptr);
  13189. ASSERT_TRUE(key != nullptr);
  13190. X509_STORE *cert_store = X509_STORE_new();
  13191. X509_STORE_add_cert(cert_store, ca_cert);
  13192. // svr.update_certs(cert, key, cert_store); // deprecated
  13193. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13194. CLIENT_CA_CERT_FILE);
  13195. ASSERT_TRUE(svr.is_valid());
  13196. svr.stop();
  13197. X509_STORE_free(cert_store);
  13198. X509_free(cert);
  13199. X509_free(ca_cert);
  13200. EVP_PKEY_free(key);
  13201. }
  13202. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13203. // client CA list correctly for TLS handshake
  13204. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13205. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13206. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13207. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13208. ASSERT_TRUE(cert != nullptr);
  13209. ASSERT_TRUE(ca_cert != nullptr);
  13210. ASSERT_TRUE(key != nullptr);
  13211. X509_STORE *cert_store = X509_STORE_new();
  13212. X509_STORE_add_cert(cert_store, ca_cert);
  13213. // Use X509-based constructor (deprecated but should still work correctly)
  13214. #pragma GCC diagnostic push
  13215. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13216. SSLServer svr(cert, key, cert_store);
  13217. #pragma GCC diagnostic pop
  13218. ASSERT_TRUE(svr.is_valid());
  13219. // Verify that client CA list is set in SSL_CTX
  13220. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13221. ASSERT_TRUE(ssl_ctx != nullptr);
  13222. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13223. ASSERT_TRUE(ca_list != nullptr);
  13224. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13225. X509_free(cert);
  13226. X509_free(ca_cert);
  13227. EVP_PKEY_free(key);
  13228. }
  13229. // Test that update_certs() updates client CA list correctly
  13230. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13231. // Start with file-based constructor
  13232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13233. ASSERT_TRUE(svr.is_valid());
  13234. // Initially no client CA list should be set
  13235. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13236. ASSERT_TRUE(ssl_ctx != nullptr);
  13237. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13238. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13239. EXPECT_EQ(0, count_before);
  13240. // Now update with client CA (PEM string)
  13241. std::string cert_pem, key_pem, ca_pem;
  13242. read_file(SERVER_CERT_FILE, cert_pem);
  13243. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13244. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13245. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13246. ASSERT_TRUE(svr.is_valid());
  13247. // Now client CA list should be set
  13248. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13249. ASSERT_TRUE(ca_list_after != nullptr);
  13250. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13251. }
  13252. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13253. // Test that the file-path SSLServer constructor properly sets the client CA
  13254. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13256. ASSERT_TRUE(svr.is_valid());
  13257. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13258. ASSERT_TRUE(ssl_ctx != nullptr);
  13259. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13260. ASSERT_TRUE(ca_list != nullptr);
  13261. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13262. }
  13263. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13264. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13265. // prepare large data
  13266. std::random_device seed_gen;
  13267. std::mt19937 random(seed_gen());
  13268. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13269. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13270. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13271. // server
  13272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13273. ASSERT_TRUE(svr.is_valid());
  13274. svr.Post("/binary", [&](const Request &req, Response &res) {
  13275. EXPECT_EQ(large_size_byte, req.body.size());
  13276. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13277. res.set_content(req.body, "application/octet-stream");
  13278. });
  13279. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13280. auto se = detail::scope_exit([&] {
  13281. svr.stop();
  13282. listen_thread.join();
  13283. ASSERT_FALSE(svr.is_running());
  13284. });
  13285. svr.wait_until_ready();
  13286. // client POST
  13287. SSLClient cli("localhost", PORT);
  13288. cli.enable_server_certificate_verification(false);
  13289. cli.set_read_timeout(std::chrono::seconds(100));
  13290. cli.set_write_timeout(std::chrono::seconds(100));
  13291. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13292. large_size_byte, "application/octet-stream");
  13293. // compare
  13294. EXPECT_EQ(StatusCode::OK_200, res->status);
  13295. EXPECT_EQ(large_size_byte, res->body.size());
  13296. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13297. }
  13298. #endif
  13299. // ============================================================================
  13300. // MbedTLS-Specific Tests
  13301. // ============================================================================
  13302. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13303. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13304. using namespace httplib::tls;
  13305. // Track if callback was invoked
  13306. bool callback_invoked = false;
  13307. // The callback receives void* ctx which is actually MbedTlsContext*
  13308. // We can access the mbedtls_ssl_config via the context
  13309. auto setup_callback = [&callback_invoked](void *ctx) {
  13310. callback_invoked = true;
  13311. // Cast to MbedTlsContext* to access the ssl config
  13312. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13313. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13314. // Use static variables to hold certificate data (simplified for test)
  13315. static mbedtls_x509_crt own_cert;
  13316. static mbedtls_pk_context own_key;
  13317. static mbedtls_x509_crt ca_chain;
  13318. static bool initialized = false;
  13319. if (!initialized) {
  13320. mbedtls_x509_crt_init(&own_cert);
  13321. mbedtls_pk_init(&own_key);
  13322. mbedtls_x509_crt_init(&ca_chain);
  13323. // Load server certificate
  13324. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13325. return false;
  13326. }
  13327. // Load server private key
  13328. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13329. #if MBEDTLS_VERSION_MAJOR >= 3
  13330. ,
  13331. mbedtls_ctr_drbg_random, nullptr
  13332. #endif
  13333. ) != 0) {
  13334. return false;
  13335. }
  13336. // Load CA chain for client verification
  13337. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13338. return false;
  13339. }
  13340. initialized = true;
  13341. }
  13342. // Configure the SSL config
  13343. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13344. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13345. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13346. // Set minimum TLS version using mbedTLS native API
  13347. #if MBEDTLS_VERSION_MAJOR >= 3
  13348. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13349. #else
  13350. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13351. MBEDTLS_SSL_MINOR_VERSION_3);
  13352. #endif
  13353. return true;
  13354. };
  13355. SSLServer svr(setup_callback);
  13356. ASSERT_TRUE(svr.is_valid());
  13357. ASSERT_TRUE(callback_invoked);
  13358. svr.Get("/test", [&](const Request &req, Response &res) {
  13359. res.set_content("test", "text/plain");
  13360. auto cert = req.peer_cert();
  13361. ASSERT_TRUE(static_cast<bool>(cert));
  13362. auto common_name = cert.subject_cn();
  13363. EXPECT_EQ("Common Name", common_name);
  13364. });
  13365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13366. auto se = detail::scope_exit([&] {
  13367. svr.stop();
  13368. t.join();
  13369. ASSERT_FALSE(svr.is_running());
  13370. });
  13371. svr.wait_until_ready();
  13372. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13373. cli.enable_server_certificate_verification(false);
  13374. cli.set_connection_timeout(30);
  13375. auto res = cli.Get("/test");
  13376. ASSERT_TRUE(res);
  13377. ASSERT_EQ(StatusCode::OK_200, res->status);
  13378. }
  13379. #endif
  13380. // WebSocket Tests
  13381. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13382. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13383. // defining the meaning of these bits has been negotiated.
  13384. auto make_frame = [](uint8_t first_byte) {
  13385. std::string frame;
  13386. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13387. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13388. frame += "Hello";
  13389. return frame;
  13390. };
  13391. // RSV1 set (0x40)
  13392. {
  13393. detail::BufferStream strm;
  13394. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13395. ws::Opcode opcode;
  13396. std::string payload;
  13397. bool fin;
  13398. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13399. false, 1024));
  13400. }
  13401. // RSV2 set (0x20)
  13402. {
  13403. detail::BufferStream strm;
  13404. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13405. ws::Opcode opcode;
  13406. std::string payload;
  13407. bool fin;
  13408. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13409. false, 1024));
  13410. }
  13411. // RSV3 set (0x10)
  13412. {
  13413. detail::BufferStream strm;
  13414. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13415. ws::Opcode opcode;
  13416. std::string payload;
  13417. bool fin;
  13418. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13419. false, 1024));
  13420. }
  13421. // No RSV bits set - should succeed
  13422. {
  13423. detail::BufferStream strm;
  13424. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13425. ws::Opcode opcode;
  13426. std::string payload;
  13427. bool fin;
  13428. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13429. false, 1024));
  13430. EXPECT_EQ(ws::Opcode::Text, opcode);
  13431. EXPECT_EQ("Hello", payload);
  13432. EXPECT_TRUE(fin);
  13433. }
  13434. }
  13435. TEST(WebSocketTest, ControlFrameValidation) {
  13436. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13437. // payload length <= 125.
  13438. // Ping with FIN=0 - must be rejected
  13439. {
  13440. detail::BufferStream strm;
  13441. std::string frame;
  13442. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13443. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13444. strm.write(frame.data(), frame.size());
  13445. ws::Opcode opcode;
  13446. std::string payload;
  13447. bool fin;
  13448. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13449. false, 1024));
  13450. }
  13451. // Close with FIN=0 - must be rejected
  13452. {
  13453. detail::BufferStream strm;
  13454. std::string frame;
  13455. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13456. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13457. strm.write(frame.data(), frame.size());
  13458. ws::Opcode opcode;
  13459. std::string payload;
  13460. bool fin;
  13461. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13462. false, 1024));
  13463. }
  13464. // Ping with payload_len=126 (extended length) - must be rejected
  13465. {
  13466. detail::BufferStream strm;
  13467. std::string frame;
  13468. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13469. frame += static_cast<char>(126); // payload_len=126 (>125)
  13470. frame += static_cast<char>(0x00); // extended length high byte
  13471. frame += static_cast<char>(126); // extended length low byte
  13472. frame += std::string(126, 'x');
  13473. strm.write(frame.data(), frame.size());
  13474. ws::Opcode opcode;
  13475. std::string payload;
  13476. bool fin;
  13477. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13478. false, 1024));
  13479. }
  13480. // Ping with FIN=1 and payload_len=125 - should succeed
  13481. {
  13482. detail::BufferStream strm;
  13483. std::string frame;
  13484. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13485. frame += static_cast<char>(125); // payload_len=125
  13486. frame += std::string(125, 'x');
  13487. strm.write(frame.data(), frame.size());
  13488. ws::Opcode opcode;
  13489. std::string payload;
  13490. bool fin;
  13491. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13492. false, 1024));
  13493. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13494. EXPECT_EQ(125u, payload.size());
  13495. EXPECT_TRUE(fin);
  13496. }
  13497. }
  13498. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13499. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13500. // length MUST be 0.
  13501. // MSB set - must be rejected
  13502. {
  13503. detail::BufferStream strm;
  13504. std::string frame;
  13505. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13506. frame += static_cast<char>(127); // 64-bit extended length
  13507. frame += static_cast<char>(0x80); // MSB set (invalid)
  13508. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13509. strm.write(frame.data(), frame.size());
  13510. ws::Opcode opcode;
  13511. std::string payload;
  13512. bool fin;
  13513. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13514. false, 1024));
  13515. }
  13516. // MSB clear - should pass length parsing (will be rejected by max_len,
  13517. // but that's a different check; use a small length to verify)
  13518. {
  13519. detail::BufferStream strm;
  13520. std::string frame;
  13521. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13522. frame += static_cast<char>(127); // 64-bit extended length
  13523. frame += std::string(7, '\0'); // high bytes = 0
  13524. frame += static_cast<char>(0x03); // length = 3
  13525. frame += "abc";
  13526. strm.write(frame.data(), frame.size());
  13527. ws::Opcode opcode;
  13528. std::string payload;
  13529. bool fin;
  13530. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13531. false, 1024));
  13532. EXPECT_EQ(ws::Opcode::Text, opcode);
  13533. EXPECT_EQ("abc", payload);
  13534. }
  13535. }
  13536. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13537. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13538. // Valid UTF-8
  13539. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13540. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13541. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13542. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13543. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13544. // Invalid UTF-8
  13545. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13546. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13547. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13548. EXPECT_FALSE(
  13549. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13550. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13551. }
  13552. TEST(WebSocketTest, ConnectAndDisconnect) {
  13553. Server svr;
  13554. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13555. std::string msg;
  13556. while (ws.read(msg)) {}
  13557. });
  13558. auto port = svr.bind_to_any_port(HOST);
  13559. std::thread t([&]() { svr.listen_after_bind(); });
  13560. svr.wait_until_ready();
  13561. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13562. ASSERT_TRUE(client.connect());
  13563. EXPECT_TRUE(client.is_open());
  13564. client.close();
  13565. EXPECT_FALSE(client.is_open());
  13566. svr.stop();
  13567. t.join();
  13568. }
  13569. TEST(WebSocketTest, ValidURL) {
  13570. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13571. EXPECT_TRUE(ws1.is_valid());
  13572. ws::WebSocketClient ws2("ws://example.com/path");
  13573. EXPECT_TRUE(ws2.is_valid());
  13574. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13575. EXPECT_TRUE(ws3.is_valid());
  13576. #ifdef CPPHTTPLIB_SSL_ENABLED
  13577. ws::WebSocketClient wss1("wss://example.com/path");
  13578. EXPECT_TRUE(wss1.is_valid());
  13579. ws::WebSocketClient wss2("wss://example.com:443/path");
  13580. EXPECT_TRUE(wss2.is_valid());
  13581. #endif
  13582. }
  13583. TEST(WebSocketTest, InvalidURL) {
  13584. // No scheme
  13585. ws::WebSocketClient ws1("localhost:8080/path");
  13586. EXPECT_FALSE(ws1.is_valid());
  13587. // No path
  13588. ws::WebSocketClient ws2("ws://localhost:8080");
  13589. EXPECT_FALSE(ws2.is_valid());
  13590. // Empty string
  13591. ws::WebSocketClient ws3("");
  13592. EXPECT_FALSE(ws3.is_valid());
  13593. // Missing host
  13594. ws::WebSocketClient ws4("ws://:8080/path");
  13595. EXPECT_FALSE(ws4.is_valid());
  13596. }
  13597. TEST(WebSocketTest, UnsupportedScheme) {
  13598. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13599. ws::WebSocketClient ws1("http://localhost:8080/path");
  13600. EXPECT_FALSE(ws1.is_valid());
  13601. ws::WebSocketClient ws2("https://localhost:8080/path");
  13602. EXPECT_FALSE(ws2.is_valid());
  13603. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13604. EXPECT_FALSE(ws3.is_valid());
  13605. #else
  13606. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13607. std::invalid_argument);
  13608. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13609. std::invalid_argument);
  13610. #endif
  13611. }
  13612. TEST(WebSocketTest, ConnectWhenInvalid) {
  13613. ws::WebSocketClient ws("not a valid url");
  13614. EXPECT_FALSE(ws.is_valid());
  13615. EXPECT_FALSE(ws.connect());
  13616. }
  13617. TEST(WebSocketTest, DefaultPort) {
  13618. ws::WebSocketClient ws1("ws://example.com/path");
  13619. EXPECT_TRUE(ws1.is_valid());
  13620. // ws:// defaults to port 80 (verified by successful parse)
  13621. #ifdef CPPHTTPLIB_SSL_ENABLED
  13622. ws::WebSocketClient ws2("wss://example.com/path");
  13623. EXPECT_TRUE(ws2.is_valid());
  13624. // wss:// defaults to port 443 (verified by successful parse)
  13625. #endif
  13626. }
  13627. TEST(WebSocketTest, IPv6LiteralAddress) {
  13628. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13629. EXPECT_TRUE(ws1.is_valid());
  13630. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13631. EXPECT_TRUE(ws2.is_valid());
  13632. }
  13633. TEST(WebSocketTest, ComplexPath) {
  13634. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13635. EXPECT_TRUE(ws1.is_valid());
  13636. ws::WebSocketClient ws2("ws://localhost:8080/");
  13637. EXPECT_TRUE(ws2.is_valid());
  13638. }
  13639. class WebSocketIntegrationTest : public ::testing::Test {
  13640. protected:
  13641. void SetUp() override {
  13642. server_ = httplib::detail::make_unique<Server>();
  13643. setup_server();
  13644. start_server();
  13645. }
  13646. void TearDown() override {
  13647. server_->stop();
  13648. if (server_thread_.joinable()) { server_thread_.join(); }
  13649. }
  13650. void setup_server() {
  13651. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13652. std::string msg;
  13653. ws::ReadResult ret;
  13654. while ((ret = ws.read(msg))) {
  13655. if (ret == ws::Binary) {
  13656. ws.send(msg.data(), msg.size());
  13657. } else {
  13658. ws.send(msg);
  13659. }
  13660. }
  13661. });
  13662. server_->WebSocket("/ws-echo-string",
  13663. [](const Request &, ws::WebSocket &ws) {
  13664. std::string msg;
  13665. while (ws.read(msg)) {
  13666. ws.send("echo: " + msg);
  13667. }
  13668. });
  13669. server_->WebSocket(
  13670. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13671. // Echo back request metadata
  13672. ws.send("path:" + req.path);
  13673. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13674. std::string msg;
  13675. while (ws.read(msg)) {}
  13676. });
  13677. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13678. std::string msg;
  13679. ws.read(msg); // wait for a message
  13680. ws.close();
  13681. });
  13682. server_->WebSocket("/ws-close-status",
  13683. [](const Request &, ws::WebSocket &ws) {
  13684. std::string msg;
  13685. ws.read(msg); // wait for a message
  13686. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13687. });
  13688. server_->WebSocket(
  13689. "/ws-subprotocol",
  13690. [](const Request &, ws::WebSocket &ws) {
  13691. std::string msg;
  13692. while (ws.read(msg)) {
  13693. ws.send(msg);
  13694. }
  13695. },
  13696. [](const std::vector<std::string> &protocols) -> std::string {
  13697. for (const auto &p : protocols) {
  13698. if (p == "graphql-ws") { return p; }
  13699. }
  13700. return "";
  13701. });
  13702. }
  13703. void start_server() {
  13704. port_ = server_->bind_to_any_port(HOST);
  13705. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13706. server_->wait_until_ready();
  13707. }
  13708. std::unique_ptr<Server> server_;
  13709. std::thread server_thread_;
  13710. int port_ = 0;
  13711. };
  13712. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13714. "/ws-echo");
  13715. ASSERT_TRUE(client.connect());
  13716. ASSERT_TRUE(client.is_open());
  13717. ASSERT_TRUE(client.send("Hello WebSocket"));
  13718. std::string msg;
  13719. EXPECT_EQ(ws::Text, client.read(msg));
  13720. EXPECT_EQ("Hello WebSocket", msg);
  13721. client.close();
  13722. }
  13723. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13725. "/ws-echo");
  13726. ASSERT_TRUE(client.connect());
  13727. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13728. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13729. std::string msg;
  13730. EXPECT_EQ(ws::Binary, client.read(msg));
  13731. EXPECT_EQ(binary_data, msg);
  13732. client.close();
  13733. }
  13734. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13736. "/ws-echo");
  13737. ASSERT_TRUE(client.connect());
  13738. for (int i = 0; i < 10; i++) {
  13739. auto text = "message " + std::to_string(i);
  13740. ASSERT_TRUE(client.send(text));
  13741. std::string msg;
  13742. ASSERT_TRUE(client.read(msg));
  13743. EXPECT_EQ(text, msg);
  13744. }
  13745. client.close();
  13746. }
  13747. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13749. "/ws-close");
  13750. ASSERT_TRUE(client.connect());
  13751. // Send a message to trigger the server to close
  13752. ASSERT_TRUE(client.send("trigger close"));
  13753. // The server will close, so read should return false
  13754. std::string msg;
  13755. EXPECT_FALSE(client.read(msg));
  13756. EXPECT_FALSE(client.is_open());
  13757. }
  13758. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13760. "/ws-echo");
  13761. ASSERT_TRUE(client.connect());
  13762. // 128KB message
  13763. std::string large_data(128 * 1024, 'X');
  13764. ASSERT_TRUE(client.send(large_data));
  13765. std::string msg;
  13766. ASSERT_TRUE(client.read(msg));
  13767. EXPECT_EQ(large_data, msg);
  13768. client.close();
  13769. }
  13770. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13771. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13772. "/ws-echo");
  13773. ASSERT_TRUE(client.connect());
  13774. const int num_threads = 4;
  13775. std::vector<std::thread> threads;
  13776. std::atomic<int> send_count{0};
  13777. for (int t = 0; t < num_threads; t++) {
  13778. threads.emplace_back([&client, &send_count, t]() {
  13779. for (int i = 0; i < 5; i++) {
  13780. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13781. if (client.send(text)) { send_count++; }
  13782. }
  13783. });
  13784. }
  13785. for (auto &th : threads) {
  13786. th.join();
  13787. }
  13788. int received = 0;
  13789. std::string msg;
  13790. while (received < send_count.load()) {
  13791. if (!client.read(msg)) { break; }
  13792. received++;
  13793. }
  13794. EXPECT_EQ(send_count.load(), received);
  13795. client.close();
  13796. }
  13797. TEST_F(WebSocketIntegrationTest, ReadString) {
  13798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13799. "/ws-echo-string");
  13800. ASSERT_TRUE(client.connect());
  13801. ASSERT_TRUE(client.send("hello"));
  13802. std::string msg;
  13803. ASSERT_TRUE(client.read(msg));
  13804. EXPECT_EQ("echo: hello", msg);
  13805. ASSERT_TRUE(client.send("world"));
  13806. ASSERT_TRUE(client.read(msg));
  13807. EXPECT_EQ("echo: world", msg);
  13808. client.close();
  13809. }
  13810. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13811. Headers headers = {{"X-Test-Header", "test-value"}};
  13812. ws::WebSocketClient client(
  13813. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13814. ASSERT_TRUE(client.connect());
  13815. std::string msg;
  13816. ASSERT_TRUE(client.read(msg));
  13817. EXPECT_EQ("path:/ws-request-info", msg);
  13818. ASSERT_TRUE(client.read(msg));
  13819. EXPECT_EQ("header:test-value", msg);
  13820. client.close();
  13821. }
  13822. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13824. "/ws-echo");
  13825. client.set_read_timeout(1, 0); // 1 second
  13826. ASSERT_TRUE(client.connect());
  13827. // Don't send anything — server echo handler waits for a message,
  13828. // so read() should time out and return false.
  13829. std::string msg;
  13830. EXPECT_FALSE(client.read(msg));
  13831. }
  13832. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13834. "/ws-echo");
  13835. client.set_read_timeout(5, 0);
  13836. ASSERT_TRUE(client.connect());
  13837. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13838. // The server should reject it and close the connection.
  13839. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13840. client.send(oversized);
  13841. // The server's read() should have failed due to payload limit,
  13842. // so our read() should return false (connection closed).
  13843. std::string msg;
  13844. EXPECT_FALSE(client.read(msg));
  13845. }
  13846. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13847. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13848. "/ws-echo");
  13849. client.set_read_timeout(10, 0);
  13850. ASSERT_TRUE(client.connect());
  13851. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13852. // This should succeed.
  13853. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13854. ASSERT_TRUE(client.send(at_limit));
  13855. std::string msg;
  13856. ASSERT_TRUE(client.read(msg));
  13857. EXPECT_EQ(at_limit.size(), msg.size());
  13858. client.close();
  13859. }
  13860. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13861. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13862. "/nonexistent");
  13863. EXPECT_FALSE(client.connect());
  13864. EXPECT_FALSE(client.is_open());
  13865. }
  13866. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13868. "/ws-echo");
  13869. ASSERT_TRUE(client.connect());
  13870. ASSERT_TRUE(client.send(""));
  13871. std::string msg;
  13872. EXPECT_EQ(ws::Text, client.read(msg));
  13873. EXPECT_EQ("", msg);
  13874. client.close();
  13875. }
  13876. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13877. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13878. "/ws-echo");
  13879. // First connection
  13880. ASSERT_TRUE(client.connect());
  13881. ASSERT_TRUE(client.send("first"));
  13882. std::string msg;
  13883. ASSERT_TRUE(client.read(msg));
  13884. EXPECT_EQ("first", msg);
  13885. client.close();
  13886. EXPECT_FALSE(client.is_open());
  13887. // Reconnect using the same client object
  13888. ASSERT_TRUE(client.connect());
  13889. ASSERT_TRUE(client.is_open());
  13890. ASSERT_TRUE(client.send("second"));
  13891. ASSERT_TRUE(client.read(msg));
  13892. EXPECT_EQ("second", msg);
  13893. client.close();
  13894. }
  13895. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13897. "/ws-close-status");
  13898. ASSERT_TRUE(client.connect());
  13899. // Trigger the server to close with GoingAway status
  13900. ASSERT_TRUE(client.send("trigger"));
  13901. // read() should return false after receiving the close frame
  13902. std::string msg;
  13903. EXPECT_FALSE(client.read(msg));
  13904. EXPECT_FALSE(client.is_open());
  13905. }
  13906. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13908. "/ws-echo");
  13909. ASSERT_TRUE(client.connect());
  13910. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13911. EXPECT_FALSE(client.is_open());
  13912. }
  13913. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13914. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13915. ws::WebSocketClient client(
  13916. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13917. ASSERT_TRUE(client.connect());
  13918. // Server should have selected graphql-ws
  13919. EXPECT_EQ("graphql-ws", client.subprotocol());
  13920. client.close();
  13921. }
  13922. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13923. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13924. ws::WebSocketClient client(
  13925. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13926. ASSERT_TRUE(client.connect());
  13927. // Server should not have selected any subprotocol
  13928. EXPECT_TRUE(client.subprotocol().empty());
  13929. client.close();
  13930. }
  13931. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13932. // Connect without requesting any subprotocol
  13933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13934. "/ws-subprotocol");
  13935. ASSERT_TRUE(client.connect());
  13936. EXPECT_TRUE(client.subprotocol().empty());
  13937. client.close();
  13938. }
  13939. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13940. Server svr;
  13941. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13942. if (!req.has_header("Authorization")) {
  13943. res.status = StatusCode::Unauthorized_401;
  13944. res.set_content("Unauthorized", "text/plain");
  13945. return Server::HandlerResponse::Handled;
  13946. }
  13947. return Server::HandlerResponse::Unhandled;
  13948. });
  13949. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13950. std::string msg;
  13951. while (ws.read(msg)) {
  13952. ws.send(msg);
  13953. }
  13954. });
  13955. auto port = svr.bind_to_any_port("localhost");
  13956. std::thread t([&]() { svr.listen_after_bind(); });
  13957. svr.wait_until_ready();
  13958. // Without Authorization header - should be rejected before upgrade
  13959. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13960. EXPECT_FALSE(client1.connect());
  13961. // With Authorization header - should succeed
  13962. Headers headers = {{"Authorization", "Bearer token123"}};
  13963. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13964. headers);
  13965. ASSERT_TRUE(client2.connect());
  13966. ASSERT_TRUE(client2.send("hello"));
  13967. std::string msg;
  13968. ASSERT_TRUE(client2.read(msg));
  13969. EXPECT_EQ("hello", msg);
  13970. client2.close();
  13971. svr.stop();
  13972. t.join();
  13973. }
  13974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13975. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13976. protected:
  13977. void SetUp() override {
  13978. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13979. SERVER_PRIVATE_KEY_FILE);
  13980. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13981. std::string msg;
  13982. ws::ReadResult ret;
  13983. while ((ret = ws.read(msg))) {
  13984. if (ret == ws::Binary) {
  13985. ws.send(msg.data(), msg.size());
  13986. } else {
  13987. ws.send(msg);
  13988. }
  13989. }
  13990. });
  13991. port_ = server_->bind_to_any_port(HOST);
  13992. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13993. server_->wait_until_ready();
  13994. }
  13995. void TearDown() override {
  13996. server_->stop();
  13997. if (server_thread_.joinable()) { server_thread_.join(); }
  13998. }
  13999. std::unique_ptr<SSLServer> server_;
  14000. std::thread server_thread_;
  14001. int port_ = 0;
  14002. };
  14003. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14004. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14005. "/ws-echo");
  14006. client.enable_server_certificate_verification(false);
  14007. ASSERT_TRUE(client.connect());
  14008. ASSERT_TRUE(client.is_open());
  14009. ASSERT_TRUE(client.send("Hello WSS"));
  14010. std::string msg;
  14011. EXPECT_EQ(ws::Text, client.read(msg));
  14012. EXPECT_EQ("Hello WSS", msg);
  14013. client.close();
  14014. }
  14015. #endif