test.cc 467 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227
  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. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) {
  74. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  75. return;
  76. #else
  77. throw std::runtime_error("File not found: " + path);
  78. #endif
  79. }
  80. fs.seekg(0, std::ios_base::end);
  81. auto size = fs.tellg();
  82. fs.seekg(0);
  83. out.resize(static_cast<size_t>(size));
  84. fs.read(&out[0], static_cast<std::streamsize>(size));
  85. }
  86. void performance_test(const char *host) {
  87. Server svr;
  88. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  89. res.set_content("Benchmark Response", "text/plain");
  90. });
  91. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  92. auto se = detail::scope_exit([&] {
  93. svr.stop();
  94. listen_thread.join();
  95. ASSERT_FALSE(svr.is_running());
  96. });
  97. svr.wait_until_ready();
  98. Client cli(host, PORT);
  99. // Warm-up request to establish connection and resolve DNS
  100. auto warmup_res = cli.Get("/benchmark");
  101. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  102. // Run multiple trials and collect timings
  103. const int num_trials = 20;
  104. std::vector<int64_t> timings;
  105. timings.reserve(num_trials);
  106. for (int i = 0; i < num_trials; i++) {
  107. auto start = std::chrono::high_resolution_clock::now();
  108. auto res = cli.Get("/benchmark");
  109. auto end = std::chrono::high_resolution_clock::now();
  110. auto elapsed =
  111. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  112. .count();
  113. // Assertions after timing measurement to avoid overhead
  114. ASSERT_TRUE(res);
  115. EXPECT_EQ(StatusCode::OK_200, res->status);
  116. timings.push_back(elapsed);
  117. }
  118. // Calculate 25th percentile (lower quartile)
  119. std::sort(timings.begin(), timings.end());
  120. auto p25 = timings[num_trials / 4];
  121. // Format timings for output
  122. std::ostringstream timings_str;
  123. timings_str << "[";
  124. for (size_t i = 0; i < timings.size(); i++) {
  125. if (i > 0) timings_str << ", ";
  126. timings_str << timings[i];
  127. }
  128. timings_str << "]";
  129. // Localhost HTTP GET should be fast even in CI environments
  130. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  131. << "ms (Issue #1777). Timings: " << timings_str.str();
  132. }
  133. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  134. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  135. class UnixSocketTest : public ::testing::Test {
  136. protected:
  137. void TearDown() override { std::remove(pathname_.c_str()); }
  138. void client_GET(const std::string &addr) {
  139. httplib::Client cli{addr};
  140. cli.set_address_family(AF_UNIX);
  141. ASSERT_TRUE(cli.is_valid());
  142. const auto &result = cli.Get(pattern_);
  143. ASSERT_TRUE(result) << "error: " << result.error();
  144. const auto &resp = result.value();
  145. EXPECT_EQ(resp.status, StatusCode::OK_200);
  146. EXPECT_EQ(resp.body, content_);
  147. }
  148. const std::string pathname_{"./httplib-server.sock"};
  149. const std::string pattern_{"/hi"};
  150. const std::string content_{"Hello World!"};
  151. };
  152. TEST_F(UnixSocketTest, pathname) {
  153. httplib::Server svr;
  154. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. }
  169. #if defined(__linux__) || \
  170. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  171. TEST_F(UnixSocketTest, PeerPid) {
  172. httplib::Server svr;
  173. std::string remote_port_val;
  174. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  175. res.set_content(content_, "text/plain");
  176. remote_port_val = std::to_string(req.remote_port);
  177. });
  178. std::thread t{[&] {
  179. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  180. }};
  181. auto se = detail::scope_exit([&] {
  182. svr.stop();
  183. t.join();
  184. ASSERT_FALSE(svr.is_running());
  185. });
  186. svr.wait_until_ready();
  187. ASSERT_TRUE(svr.is_running());
  188. client_GET(pathname_);
  189. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  190. }
  191. #endif
  192. #ifdef __linux__
  193. TEST_F(UnixSocketTest, abstract) {
  194. constexpr char svr_path[]{"\x00httplib-server.sock"};
  195. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  196. httplib::Server svr;
  197. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  198. res.set_content(content_, "text/plain");
  199. });
  200. std::thread t{[&] {
  201. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  202. }};
  203. auto se = detail::scope_exit([&] {
  204. svr.stop();
  205. t.join();
  206. ASSERT_FALSE(svr.is_running());
  207. });
  208. svr.wait_until_ready();
  209. ASSERT_TRUE(svr.is_running());
  210. client_GET(abstract_addr);
  211. }
  212. #endif
  213. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  214. httplib::Server svr;
  215. std::string received_host_header;
  216. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  217. // Capture the Host header sent by the client
  218. auto host_iter = req.headers.find("Host");
  219. if (host_iter != req.headers.end()) {
  220. received_host_header = host_iter->second;
  221. }
  222. res.set_content(content_, "text/plain");
  223. });
  224. std::thread t{[&] {
  225. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  226. }};
  227. auto se = detail::scope_exit([&] {
  228. svr.stop();
  229. t.join();
  230. ASSERT_FALSE(svr.is_running());
  231. });
  232. svr.wait_until_ready();
  233. ASSERT_TRUE(svr.is_running());
  234. // Test that Host header is automatically set to "localhost" for Unix socket
  235. // connections
  236. httplib::Client cli{pathname_};
  237. cli.set_address_family(AF_UNIX);
  238. ASSERT_TRUE(cli.is_valid());
  239. const auto &result = cli.Get(pattern_);
  240. ASSERT_TRUE(result) << "error: " << result.error();
  241. const auto &resp = result.value();
  242. EXPECT_EQ(resp.status, StatusCode::OK_200);
  243. EXPECT_EQ(resp.body, content_);
  244. // Verify that Host header was automatically set to "localhost"
  245. EXPECT_EQ(received_host_header, "localhost");
  246. }
  247. #ifndef _WIN32
  248. TEST(SocketStream, wait_writable_UNIX) {
  249. int fds[2];
  250. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  251. const auto asSocketStream = [&](socket_t fd,
  252. std::function<bool(Stream &)> func) {
  253. return detail::process_client_socket(
  254. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  255. };
  256. asSocketStream(fds[0], [&](Stream &s0) {
  257. EXPECT_EQ(s0.socket(), fds[0]);
  258. EXPECT_TRUE(s0.wait_writable());
  259. EXPECT_EQ(0, close(fds[1]));
  260. EXPECT_FALSE(s0.wait_writable());
  261. return true;
  262. });
  263. EXPECT_EQ(0, close(fds[0]));
  264. }
  265. TEST(SocketStream, wait_writable_INET) {
  266. sockaddr_in addr;
  267. memset(&addr, 0, sizeof(addr));
  268. addr.sin_family = AF_INET;
  269. addr.sin_port = htons(PORT + 1);
  270. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  271. int disconnected_svr_sock = -1;
  272. std::thread svr{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, listen(s, 1));
  277. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  281. std::thread cli{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, close(s));
  286. }};
  287. cli.join();
  288. svr.join();
  289. ASSERT_NE(disconnected_svr_sock, -1);
  290. const auto asSocketStream = [&](socket_t fd,
  291. std::function<bool(Stream &)> func) {
  292. return detail::process_client_socket(
  293. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  294. };
  295. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  296. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  297. EXPECT_FALSE(ss.wait_writable());
  298. return true;
  299. });
  300. ASSERT_EQ(0, close(disconnected_svr_sock));
  301. }
  302. #endif // #ifndef _WIN32
  303. TEST(ClientTest, MoveConstructible) {
  304. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  305. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  306. }
  307. TEST(ClientTest, MoveAssignable) {
  308. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  309. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  310. }
  311. #ifdef _WIN32
  312. TEST(StartupTest, WSAStartup) {
  313. WSADATA wsaData;
  314. int ret = WSAStartup(0x0002, &wsaData);
  315. ASSERT_EQ(0, ret);
  316. }
  317. #endif
  318. TEST(DecodePathTest, PercentCharacter) {
  319. EXPECT_EQ(
  320. decode_path_component(
  321. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  322. U8("descrip=Gastos áéíóúñÑ 6"));
  323. }
  324. TEST(DecodePathTest, PercentCharacterNUL) {
  325. string expected;
  326. expected.push_back('x');
  327. expected.push_back('\0');
  328. expected.push_back('x');
  329. EXPECT_EQ(decode_path_component("x%00x"), expected);
  330. }
  331. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'()";
  333. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  334. }
  335. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  336. string reservedCharacters = ";,/?:@&=+$";
  337. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  338. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  339. }
  340. TEST(ClientQueryOrder, PreserveOrder) {
  341. // This test reproduces Issue #2259: client may reorder query parameters
  342. // when sending a GET request. The expected behavior is that the client
  343. // preserves the original query string order when the caller supplied it
  344. // as part of the path.
  345. Server svr;
  346. svr.Get("/", [&](const Request &req, Response &res) {
  347. // Echo back the raw target so the test can assert ordering
  348. res.set_content(req.target, "text/plain");
  349. });
  350. std::thread t{[&] { svr.listen(HOST, PORT); }};
  351. auto se = detail::scope_exit([&] {
  352. svr.stop();
  353. t.join();
  354. ASSERT_FALSE(svr.is_running());
  355. });
  356. svr.wait_until_ready();
  357. Client cli(HOST, PORT);
  358. ASSERT_TRUE(cli.is_valid());
  359. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  360. auto res = cli.Get(original);
  361. ASSERT_TRUE(res);
  362. // Expect the echoed target to exactly match the original path (order
  363. // preserved)
  364. EXPECT_EQ(res->body, original);
  365. }
  366. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  367. string chineseCharacters = U8("中国語");
  368. string russianCharacters = U8("дом");
  369. string brazilianCharacters = U8("óculos");
  370. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  371. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  372. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  373. "%D0%B4%D0%BE%D0%BC");
  374. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  375. }
  376. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  377. string unescapedCharacters = "-_.!~*'()";
  378. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  379. }
  380. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  381. string reservedCharacters = ";,/?:@&=+$";
  382. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  383. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  384. }
  385. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  386. string chineseCharacters = U8("中国語");
  387. string russianCharacters = U8("дом");
  388. string brazilianCharacters = U8("óculos");
  389. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  390. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  391. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  392. "%D0%B4%D0%BE%D0%BC");
  393. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  394. }
  395. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  396. // Issue #2082 use case: encoding path component with ampersand
  397. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  398. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  399. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  400. }
  401. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  402. string unescapedCharacters = "-_.!~*'()";
  403. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  404. }
  405. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  406. string reservedCharacters = ";,/?:@&=+$#";
  407. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  408. }
  409. TEST(EncodeUriTest, TestUTF8Characters) {
  410. string chineseCharacters = U8("中国語");
  411. string russianCharacters = U8("дом");
  412. string brazilianCharacters = U8("óculos");
  413. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  414. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  415. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriTest, TestCompleteUri) {
  419. string uri =
  420. "https://example.com/path/to/resource?query=value&param=test#fragment";
  421. EXPECT_EQ(
  422. httplib::encode_uri(uri),
  423. "https://example.com/path/to/resource?query=value&param=test#fragment");
  424. }
  425. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  426. string uri =
  427. "https://example.com/path with spaces/file name.html?q=hello world";
  428. EXPECT_EQ(httplib::encode_uri(uri),
  429. "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world");
  431. }
  432. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  433. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  434. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  435. }
  436. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  441. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  442. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  443. string encodedBrazilian = "%C3%B3culos";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  445. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  446. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  447. }
  448. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  449. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  451. "Piri Tommy Villiers - on & on");
  452. }
  453. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  454. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  455. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  456. }
  457. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  458. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  459. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  460. }
  461. TEST(DecodeUriTest, TestUTF8Characters) {
  462. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  463. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  464. string encodedBrazilian = "%C3%B3culos";
  465. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  466. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  467. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  468. }
  469. TEST(DecodeUriTest, TestCompleteUri) {
  470. string encodedUri = "https://example.com/path%20with%20spaces/"
  471. "file%20name.html?q=hello%20world";
  472. EXPECT_EQ(
  473. httplib::decode_uri(encodedUri),
  474. "https://example.com/path with spaces/file name.html?q=hello world");
  475. }
  476. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  477. string original =
  478. "https://example.com/path with spaces/file name.html?q=hello world";
  479. string encoded = httplib::encode_uri(original);
  480. string decoded = httplib::decode_uri(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  484. string original = "Piri Tommy Villiers - on & on";
  485. string encoded = httplib::encode_uri_component(original);
  486. string decoded = httplib::decode_uri_component(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(TrimTests, TrimStringTests) {
  490. EXPECT_EQ("abc", detail::trim_copy("abc"));
  491. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  492. EXPECT_TRUE(detail::trim_copy("").empty());
  493. }
  494. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  495. // Simple case without quality values
  496. std::vector<std::string> result1;
  497. EXPECT_TRUE(detail::parse_accept_header(
  498. "text/html,application/json,text/plain", result1));
  499. EXPECT_EQ(result1.size(), 3U);
  500. EXPECT_EQ(result1[0], "text/html");
  501. EXPECT_EQ(result1[1], "application/json");
  502. EXPECT_EQ(result1[2], "text/plain");
  503. // With quality values
  504. std::vector<std::string> result2;
  505. EXPECT_TRUE(detail::parse_accept_header(
  506. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  507. EXPECT_EQ(result2.size(), 3U);
  508. EXPECT_EQ(result2[0], "application/json"); // highest q value
  509. EXPECT_EQ(result2[1], "text/html");
  510. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  511. }
  512. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  513. // Mixed with and without quality values
  514. std::vector<std::string> result;
  515. EXPECT_TRUE(detail::parse_accept_header(
  516. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  517. EXPECT_EQ(result.size(), 3U);
  518. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  519. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  520. EXPECT_EQ(result[2], "application/json"); // q=0.5
  521. }
  522. TEST(ParseAcceptHeaderTest, EdgeCases) {
  523. // Empty header
  524. std::vector<std::string> empty_result;
  525. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  526. EXPECT_TRUE(empty_result.empty());
  527. // Single type
  528. std::vector<std::string> single_result;
  529. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  530. EXPECT_EQ(single_result.size(), 1U);
  531. EXPECT_EQ(single_result[0], "application/json");
  532. // Wildcard types
  533. std::vector<std::string> wildcard_result;
  534. EXPECT_TRUE(detail::parse_accept_header(
  535. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  536. EXPECT_EQ(wildcard_result.size(), 3U);
  537. EXPECT_EQ(wildcard_result[0], "application/json");
  538. EXPECT_EQ(wildcard_result[1], "text/*");
  539. EXPECT_EQ(wildcard_result[2], "*/*");
  540. }
  541. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  542. // Common browser Accept header
  543. std::vector<std::string> browser_result;
  544. EXPECT_TRUE(
  545. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  546. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  547. browser_result));
  548. EXPECT_EQ(browser_result.size(), 6U);
  549. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  550. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  551. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  552. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  553. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  554. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  555. // API client header
  556. std::vector<std::string> api_result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  559. api_result));
  560. EXPECT_EQ(api_result.size(), 3U);
  561. EXPECT_EQ(api_result[0], "application/json");
  562. EXPECT_EQ(api_result[1], "application/xml");
  563. EXPECT_EQ(api_result[2], "text/plain");
  564. }
  565. TEST(ParseAcceptHeaderTest, SpecialCases) {
  566. // Quality value with 3 decimal places
  567. std::vector<std::string> decimal_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  570. EXPECT_EQ(decimal_result.size(), 2U);
  571. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  572. EXPECT_EQ(decimal_result[1], "text/html");
  573. // Zero quality (should still be included but with lowest priority)
  574. std::vector<std::string> zero_q_result;
  575. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  576. zero_q_result));
  577. EXPECT_EQ(zero_q_result.size(), 2U);
  578. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  579. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  580. // No spaces around commas
  581. std::vector<std::string> no_space_result;
  582. EXPECT_TRUE(detail::parse_accept_header(
  583. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  584. no_space_result));
  585. EXPECT_EQ(no_space_result.size(), 3U);
  586. EXPECT_EQ(no_space_result[0], "text/html");
  587. EXPECT_EQ(no_space_result[1], "application/json");
  588. EXPECT_EQ(no_space_result[2], "text/plain");
  589. }
  590. TEST(ParseAcceptHeaderTest, InvalidCases) {
  591. std::vector<std::string> result;
  592. // Invalid quality value (> 1.0)
  593. EXPECT_FALSE(
  594. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  595. // Invalid quality value (< 0.0)
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  598. // Invalid quality value (not a number)
  599. EXPECT_FALSE(detail::parse_accept_header(
  600. "text/html;q=invalid,application/json", result));
  601. // Empty quality value
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=,application/json", result));
  604. // Invalid media type format (no slash and not wildcard)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("invalidtype,application/json", result));
  607. // Empty media type
  608. result.clear();
  609. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  610. // Only commas
  611. result.clear();
  612. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  613. // Valid cases should still work
  614. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "*/*");
  617. EXPECT_TRUE(detail::parse_accept_header("*", result));
  618. EXPECT_EQ(result.size(), 1U);
  619. EXPECT_EQ(result[0], "*");
  620. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "text/*");
  623. }
  624. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  625. Server svr;
  626. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  627. EXPECT_EQ(req.accept_content_types.size(), 3U);
  628. EXPECT_EQ(req.accept_content_types[0], "application/json");
  629. EXPECT_EQ(req.accept_content_types[1], "text/html");
  630. EXPECT_EQ(req.accept_content_types[2], "*/*");
  631. res.set_content("ok", "text/plain");
  632. });
  633. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  634. EXPECT_TRUE(false);
  635. res.set_content("bad request", "text/plain");
  636. });
  637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  638. auto se = detail::scope_exit([&] {
  639. svr.stop();
  640. listen_thread.join();
  641. ASSERT_FALSE(svr.is_running());
  642. });
  643. svr.wait_until_ready();
  644. Client cli("localhost", PORT);
  645. {
  646. auto res =
  647. cli.Get("/accept_ok",
  648. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::OK_200, res->status);
  651. }
  652. {
  653. auto res = cli.Get("/accept_bad_request",
  654. {{"Accept", "text/html;q=abc,application/json"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  657. }
  658. }
  659. TEST(DivideTest, DivideStringTests) {
  660. auto divide = [](const std::string &str, char d) {
  661. std::string lhs;
  662. std::string rhs;
  663. detail::divide(str, d,
  664. [&](const char *lhs_data, std::size_t lhs_size,
  665. const char *rhs_data, std::size_t rhs_size) {
  666. lhs.assign(lhs_data, lhs_size);
  667. rhs.assign(rhs_data, rhs_size);
  668. });
  669. return std::make_pair(std::move(lhs), std::move(rhs));
  670. };
  671. {
  672. const auto res = divide("", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide("=", '=');
  678. EXPECT_EQ(res.first, "");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide(" ", '=');
  683. EXPECT_EQ(res.first, " ");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("a=", '=');
  693. EXPECT_EQ(res.first, "a");
  694. EXPECT_EQ(res.second, "");
  695. }
  696. {
  697. const auto res = divide("=b", '=');
  698. EXPECT_EQ(res.first, "");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b");
  705. }
  706. {
  707. const auto res = divide("a=b=", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=");
  710. }
  711. {
  712. const auto res = divide("a=b=c", '=');
  713. EXPECT_EQ(res.first, "a");
  714. EXPECT_EQ(res.second, "b=c");
  715. }
  716. }
  717. TEST(SplitTest, ParseQueryString) {
  718. string s = "key1=val1&key2=val2&key3=val3";
  719. Params dic;
  720. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  721. [&](const char *b, const char *e) {
  722. string key, val;
  723. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  724. if (key.empty()) {
  725. key.assign(b2, e2);
  726. } else {
  727. val.assign(b2, e2);
  728. }
  729. });
  730. dic.emplace(key, val);
  731. });
  732. EXPECT_EQ("val1", dic.find("key1")->second);
  733. EXPECT_EQ("val2", dic.find("key2")->second);
  734. EXPECT_EQ("val3", dic.find("key3")->second);
  735. }
  736. TEST(SplitTest, ParseInvalidQueryTests) {
  737. {
  738. string s = " ";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. {
  744. string s = " = =";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. }
  750. TEST(ParseQueryTest, ParseQueryString) {
  751. {
  752. std::string s = "key1=val1&key2=val2&key3=val3";
  753. Params dic;
  754. detail::parse_query_text(s, dic);
  755. EXPECT_EQ("val1", dic.find("key1")->second);
  756. EXPECT_EQ("val2", dic.find("key2")->second);
  757. EXPECT_EQ("val3", dic.find("key3")->second);
  758. }
  759. {
  760. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  761. Params dic;
  762. detail::parse_query_text(s, dic);
  763. EXPECT_EQ("", dic.find("key1")->second);
  764. EXPECT_EQ("val1", dic.find("key2")->second);
  765. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  766. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  767. }
  768. }
  769. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  770. Params dic;
  771. EXPECT_EQ(detail::params_to_query_str(dic), "");
  772. dic.emplace("key1", "val1");
  773. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  774. dic.emplace("key2", "val2");
  775. dic.emplace("key3", "val3");
  776. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  777. }
  778. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  779. string content_type = "multipart/form-data; boundary=something";
  780. string boundary;
  781. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  782. EXPECT_TRUE(ret);
  783. EXPECT_EQ(boundary, "something");
  784. }
  785. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  786. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  787. string boundary;
  788. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  789. EXPECT_TRUE(ret);
  790. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  791. }
  792. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  793. string content_type =
  794. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  795. string boundary;
  796. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  797. EXPECT_TRUE(ret);
  798. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  799. }
  800. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  801. string content_type =
  802. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  803. string boundary;
  804. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  805. EXPECT_TRUE(ret);
  806. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  807. }
  808. TEST(GetHeaderValueTest, DefaultValue) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  811. EXPECT_STREQ("text/plain", val);
  812. }
  813. TEST(GetHeaderValueTest, DefaultValueInt) {
  814. Headers headers = {{"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  816. EXPECT_EQ(100ull, val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValue) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  824. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  826. EXPECT_STREQ("text/html", val);
  827. }
  828. TEST(GetHeaderValueTest, SetContent) {
  829. Response res;
  830. res.set_content("html", "text/html");
  831. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  832. res.set_content("text", "text/plain");
  833. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  834. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  835. }
  836. TEST(GetHeaderValueTest, RegularValueInt) {
  837. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  839. EXPECT_EQ(100ull, val);
  840. }
  841. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  842. Headers headers = {{"Content-Length", "x"}};
  843. auto is_invalid_value = false;
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  845. is_invalid_value);
  846. EXPECT_EQ(0ull, val);
  847. EXPECT_TRUE(is_invalid_value);
  848. }
  849. TEST(GetHeaderValueTest, Range) {
  850. {
  851. Headers headers = {make_range_header({{1, -1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=1-", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{-1, 1}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=-1", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=1-10, 100-200", val);
  874. }
  875. {
  876. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  878. EXPECT_STREQ("bytes=0-0, -1", val);
  879. }
  880. }
  881. TEST(ParseHeaderValueTest, Range) {
  882. {
  883. Ranges ranges;
  884. auto ret = detail::parse_range_header("bytes=1-", ranges);
  885. EXPECT_TRUE(ret);
  886. EXPECT_EQ(1u, ranges.size());
  887. EXPECT_EQ(1u, ranges[0].first);
  888. EXPECT_EQ(-1, ranges[0].second);
  889. }
  890. {
  891. Ranges ranges;
  892. auto ret = detail::parse_range_header("bytes=-1", ranges);
  893. EXPECT_TRUE(ret);
  894. EXPECT_EQ(1u, ranges.size());
  895. EXPECT_EQ(-1, ranges[0].first);
  896. EXPECT_EQ(1u, ranges[0].second);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(1u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  909. EXPECT_FALSE(ret);
  910. }
  911. {
  912. Ranges ranges;
  913. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  914. EXPECT_TRUE(ret);
  915. EXPECT_EQ(2u, ranges.size());
  916. EXPECT_EQ(1u, ranges[0].first);
  917. EXPECT_EQ(10u, ranges[0].second);
  918. EXPECT_EQ(100u, ranges[1].first);
  919. EXPECT_EQ(-1, ranges[1].second);
  920. }
  921. {
  922. Ranges ranges;
  923. auto ret =
  924. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  925. EXPECT_TRUE(ret);
  926. EXPECT_EQ(3u, ranges.size());
  927. EXPECT_EQ(1u, ranges[0].first);
  928. EXPECT_EQ(10u, ranges[0].second);
  929. EXPECT_EQ(100u, ranges[1].first);
  930. EXPECT_EQ(200u, ranges[1].second);
  931. EXPECT_EQ(300u, ranges[2].first);
  932. EXPECT_EQ(400u, ranges[2].second);
  933. }
  934. {
  935. Ranges ranges;
  936. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  949. EXPECT_TRUE(ranges.empty());
  950. }
  951. }
  952. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  953. Request req;
  954. req.set_header("Accept-Encoding", "gzip");
  955. Response res;
  956. res.set_header("Content-Type", "text/plain");
  957. auto ret = detail::encoding_type(req, res);
  958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #else
  961. EXPECT_TRUE(ret == detail::EncodingType::None);
  962. #endif
  963. }
  964. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  972. #elif CPPHTTPLIB_ZLIB_SUPPORT
  973. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  974. #elif CPPHTTPLIB_ZSTD_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  976. #else
  977. EXPECT_TRUE(ret == detail::EncodingType::None);
  978. #endif
  979. }
  980. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  981. Request req;
  982. req.set_header("Accept-Encoding",
  983. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  984. Response res;
  985. res.set_header("Content-Type", "text/plain");
  986. auto ret = detail::encoding_type(req, res);
  987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  988. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  989. #elif CPPHTTPLIB_ZLIB_SUPPORT
  990. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  991. #elif CPPHTTPLIB_ZSTD_SUPPORT
  992. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  993. #else
  994. EXPECT_TRUE(ret == detail::EncodingType::None);
  995. #endif
  996. }
  997. TEST(BufferStreamTest, read) {
  998. detail::BufferStream strm1;
  999. Stream &strm = strm1;
  1000. EXPECT_EQ(5, strm.write("hello"));
  1001. char buf[512];
  1002. EXPECT_EQ(2, strm.read(buf, 2));
  1003. EXPECT_EQ('h', buf[0]);
  1004. EXPECT_EQ('e', buf[1]);
  1005. EXPECT_EQ(2, strm.read(buf, 2));
  1006. EXPECT_EQ('l', buf[0]);
  1007. EXPECT_EQ('l', buf[1]);
  1008. EXPECT_EQ(1, strm.read(buf, 1));
  1009. EXPECT_EQ('o', buf[0]);
  1010. EXPECT_EQ(0, strm.read(buf, 1));
  1011. }
  1012. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1013. auto host = "www.httpwatch.com";
  1014. auto ip = hosted_at(host);
  1015. EXPECT_EQ("23.96.13.243", ip);
  1016. std::vector<std::string> addrs;
  1017. hosted_at(host, addrs);
  1018. EXPECT_EQ(1u, addrs.size());
  1019. }
  1020. #if 0 // It depends on each test environment...
  1021. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1022. auto host = "www.youtube.com";
  1023. std::vector<std::string> addrs;
  1024. hosted_at(host, addrs);
  1025. EXPECT_EQ(20u, addrs.size());
  1026. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1027. EXPECT_TRUE(it != addrs.end());
  1028. }
  1029. #endif
  1030. class ChunkedEncodingTest : public ::testing::Test {
  1031. protected:
  1032. ChunkedEncodingTest()
  1033. : cli_(HOST, PORT)
  1034. #ifdef CPPHTTPLIB_SSL_ENABLED
  1035. ,
  1036. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1037. #endif
  1038. {
  1039. cli_.set_connection_timeout(2);
  1040. #ifdef CPPHTTPLIB_SSL_ENABLED
  1041. cli_.enable_server_certificate_verification(false);
  1042. #endif
  1043. }
  1044. virtual void SetUp() {
  1045. read_file("./image.jpg", image_data_);
  1046. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1047. res.set_content("Hello World!", "text/plain");
  1048. });
  1049. svr_.Get(
  1050. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1051. res.set_chunked_content_provider(
  1052. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1053. size_t remaining = image_data_.size() - offset;
  1054. if (remaining == 0) {
  1055. sink.done();
  1056. } else {
  1057. constexpr size_t CHUNK_SIZE = 1024;
  1058. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1059. sink.write(&image_data_[offset], send_size);
  1060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1061. }
  1062. return true;
  1063. });
  1064. });
  1065. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1066. svr_.wait_until_ready();
  1067. }
  1068. virtual void TearDown() {
  1069. svr_.stop();
  1070. if (!request_threads_.empty()) {
  1071. std::this_thread::sleep_for(std::chrono::seconds(1));
  1072. for (auto &t : request_threads_) {
  1073. t.join();
  1074. }
  1075. }
  1076. t_.join();
  1077. }
  1078. #ifdef CPPHTTPLIB_SSL_ENABLED
  1079. SSLClient cli_;
  1080. SSLServer svr_;
  1081. #else
  1082. Client cli_;
  1083. Server svr_;
  1084. #endif
  1085. thread t_;
  1086. std::vector<thread> request_threads_;
  1087. std::string image_data_;
  1088. };
  1089. TEST_F(ChunkedEncodingTest, NormalGet) {
  1090. auto res = cli_.Get("/chunked");
  1091. ASSERT_TRUE(res);
  1092. std::string out;
  1093. read_file("./image.jpg", out);
  1094. EXPECT_EQ(StatusCode::OK_200, res->status);
  1095. EXPECT_EQ(out, res->body);
  1096. }
  1097. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1098. std::string body;
  1099. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1100. body.append(data, data_length);
  1101. return true;
  1102. });
  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, body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get(
  1112. "/chunked",
  1113. [&](const Response &response) {
  1114. EXPECT_EQ(StatusCode::OK_200, response.status);
  1115. return true;
  1116. },
  1117. [&](const char *data, size_t data_length) {
  1118. body.append(data, data_length);
  1119. return true;
  1120. });
  1121. ASSERT_TRUE(res);
  1122. std::string out;
  1123. read_file("./image.jpg", out);
  1124. EXPECT_EQ(StatusCode::OK_200, res->status);
  1125. EXPECT_EQ(out, body);
  1126. }
  1127. TEST(RangeTest, FromHTTPBin_Online) {
  1128. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1129. auto host = "httpcan.org";
  1130. auto path = std::string{"/range/32"};
  1131. #else
  1132. auto host = "nghttp2.org";
  1133. auto path = std::string{"/httpbin/range/32"};
  1134. #endif
  1135. #ifdef CPPHTTPLIB_SSL_ENABLED
  1136. auto port = 443;
  1137. SSLClient cli(host, port);
  1138. #else
  1139. auto port = 80;
  1140. Client cli(host, port);
  1141. #endif
  1142. cli.set_connection_timeout(5);
  1143. {
  1144. auto res = cli.Get(path);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{1, -1}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{1, 10}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("bcdefghijk", res->body);
  1161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 31}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. Headers headers = {make_range_header({{0, -1}})};
  1172. auto res = cli.Get(path, headers);
  1173. ASSERT_TRUE(res);
  1174. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. }
  1177. {
  1178. Headers headers = {make_range_header({{0, 32}})};
  1179. auto res = cli.Get(path, headers);
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1182. }
  1183. }
  1184. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1185. auto host = "unresolvableaddress.local";
  1186. auto path = std::string{"/"};
  1187. #ifdef CPPHTTPLIB_SSL_ENABLED
  1188. auto port = 443;
  1189. SSLClient cli(host, port);
  1190. #else
  1191. auto port = 80;
  1192. Client cli(host, port);
  1193. #endif
  1194. cli.set_connection_timeout(1);
  1195. {
  1196. auto res = cli.Get(path);
  1197. ASSERT_FALSE(res);
  1198. }
  1199. std::this_thread::sleep_for(std::chrono::seconds(8));
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost) {
  1202. auto host = "-abcde.com";
  1203. #ifdef CPPHTTPLIB_SSL_ENABLED
  1204. auto port = 443;
  1205. SSLClient cli(host, port);
  1206. #else
  1207. auto port = 80;
  1208. Client cli(host, port);
  1209. #endif
  1210. cli.set_connection_timeout(std::chrono::seconds(2));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Connection, res.error());
  1214. }
  1215. TEST(ConnectionErrorTest, InvalidHost2) {
  1216. auto host = "httpcan.org/";
  1217. #ifdef CPPHTTPLIB_SSL_ENABLED
  1218. SSLClient cli(host);
  1219. #else
  1220. Client cli(host);
  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, InvalidHostCheckResultErrorToString) {
  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. stringstream s;
  1238. s << "error code: " << res.error();
  1239. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1240. }
  1241. TEST(ConnectionErrorTest, InvalidPort) {
  1242. auto host = "localhost";
  1243. auto port = 44380;
  1244. #ifdef CPPHTTPLIB_SSL_ENABLED
  1245. SSLClient cli(host, port);
  1246. #else
  1247. Client cli(host, port);
  1248. #endif
  1249. cli.set_connection_timeout(std::chrono::seconds(2));
  1250. auto res = cli.Get("/");
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_TRUE(Error::Connection == res.error() ||
  1253. Error::ConnectionTimeout == res.error());
  1254. }
  1255. TEST(ConnectionErrorTest, Timeout_Online) {
  1256. auto host = "google.com";
  1257. #ifdef CPPHTTPLIB_SSL_ENABLED
  1258. auto port = 44380;
  1259. SSLClient cli(host, port);
  1260. #else
  1261. auto port = 8080;
  1262. Client cli(host, port);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. // only probe one address type so that the error reason
  1266. // correlates to the timed-out IPv4, not the unsupported
  1267. // IPv6 connection attempt
  1268. cli.set_address_family(AF_INET);
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1272. }
  1273. TEST(CancelTest, NoCancel_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpcan.org";
  1276. auto path = std::string{"/range/32"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/32"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_SSL_ENABLED
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1290. ASSERT_TRUE(res);
  1291. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1292. EXPECT_EQ(StatusCode::OK_200, res->status);
  1293. }
  1294. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1295. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1296. auto host = "httpcan.org";
  1297. auto path = std::string{"/range/32"};
  1298. #else
  1299. auto host = "nghttp2.org";
  1300. auto path = std::string{"/httpbin/range/32"};
  1301. #endif
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. auto port = 443;
  1304. SSLClient cli(host, port);
  1305. #else
  1306. auto port = 80;
  1307. Client cli(host, port);
  1308. #endif
  1309. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1310. cli.set_connection_timeout(std::chrono::seconds(5));
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_EQ(Error::Canceled, res.error());
  1313. }
  1314. TEST(CancelTest, WithCancelLargePayload_Online) {
  1315. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1316. auto host = "httpcan.org";
  1317. auto path = std::string{"/range/65536"};
  1318. #else
  1319. auto host = "nghttp2.org";
  1320. auto path = std::string{"/httpbin/range/65536"};
  1321. #endif
  1322. #ifdef CPPHTTPLIB_SSL_ENABLED
  1323. auto port = 443;
  1324. SSLClient cli(host, port);
  1325. #else
  1326. auto port = 80;
  1327. Client cli(host, port);
  1328. #endif
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. uint32_t count = 0;
  1331. auto res =
  1332. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, NoCancelPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return true; });
  1353. ASSERT_TRUE(res);
  1354. EXPECT_EQ("Hello World!", res->body);
  1355. EXPECT_EQ(StatusCode::OK_200, res->status);
  1356. }
  1357. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1358. Server svr;
  1359. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1360. res.set_content("Hello World!", "text/plain");
  1361. });
  1362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1363. auto se = detail::scope_exit([&] {
  1364. svr.stop();
  1365. thread.join();
  1366. ASSERT_FALSE(svr.is_running());
  1367. });
  1368. svr.wait_until_ready();
  1369. Client cli(HOST, PORT);
  1370. cli.set_connection_timeout(std::chrono::seconds(5));
  1371. auto res =
  1372. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1373. "application/json", [](uint64_t, uint64_t) { return false; });
  1374. ASSERT_TRUE(!res);
  1375. EXPECT_EQ(Error::Canceled, res.error());
  1376. }
  1377. TEST(CancelTest, WithCancelLargePayloadPost) {
  1378. Server svr;
  1379. svr.set_payload_max_length(200 * 1024 * 1024);
  1380. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1381. res.set_content(LARGE_DATA, "text/plain");
  1382. });
  1383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1384. auto se = detail::scope_exit([&] {
  1385. svr.stop();
  1386. thread.join();
  1387. ASSERT_FALSE(svr.is_running());
  1388. });
  1389. svr.wait_until_ready();
  1390. Client cli(HOST, PORT);
  1391. cli.set_payload_max_length(200 * 1024 * 1024);
  1392. cli.set_connection_timeout(std::chrono::seconds(5));
  1393. auto res =
  1394. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1395. "application/json", [](uint64_t, uint64_t) { return false; });
  1396. ASSERT_TRUE(!res);
  1397. EXPECT_EQ(Error::Canceled, res.error());
  1398. }
  1399. TEST(CancelTest, NoCancelPut) {
  1400. Server svr;
  1401. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1402. res.set_content("Hello World!", "text/plain");
  1403. });
  1404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. thread.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. Client cli(HOST, PORT);
  1412. cli.set_connection_timeout(std::chrono::seconds(5));
  1413. auto res =
  1414. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1415. "application/json", [](uint64_t, uint64_t) { return true; });
  1416. ASSERT_TRUE(res);
  1417. EXPECT_EQ("Hello World!", res->body);
  1418. EXPECT_EQ(StatusCode::OK_200, res->status);
  1419. }
  1420. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1421. Server svr;
  1422. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1423. res.set_content("Hello World!", "text/plain");
  1424. });
  1425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1426. auto se = detail::scope_exit([&] {
  1427. svr.stop();
  1428. thread.join();
  1429. ASSERT_FALSE(svr.is_running());
  1430. });
  1431. svr.wait_until_ready();
  1432. Client cli(HOST, PORT);
  1433. cli.set_connection_timeout(std::chrono::seconds(5));
  1434. auto res =
  1435. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1436. "application/json", [](uint64_t, uint64_t) { return false; });
  1437. ASSERT_TRUE(!res);
  1438. EXPECT_EQ(Error::Canceled, res.error());
  1439. }
  1440. TEST(CancelTest, WithCancelLargePayloadPut) {
  1441. Server svr;
  1442. svr.set_payload_max_length(200 * 1024 * 1024);
  1443. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1444. res.set_content(LARGE_DATA, "text/plain");
  1445. });
  1446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1447. auto se = detail::scope_exit([&] {
  1448. svr.stop();
  1449. thread.join();
  1450. ASSERT_FALSE(svr.is_running());
  1451. });
  1452. svr.wait_until_ready();
  1453. Client cli(HOST, PORT);
  1454. cli.set_payload_max_length(200 * 1024 * 1024);
  1455. cli.set_connection_timeout(std::chrono::seconds(5));
  1456. auto res =
  1457. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1458. "application/json", [](uint64_t, uint64_t) { return false; });
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::Canceled, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancelPatch) {
  1463. Server svr;
  1464. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1465. res.set_content("Hello World!", "text/plain");
  1466. });
  1467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1468. auto se = detail::scope_exit([&] {
  1469. svr.stop();
  1470. thread.join();
  1471. ASSERT_FALSE(svr.is_running());
  1472. });
  1473. svr.wait_until_ready();
  1474. Client cli(HOST, PORT);
  1475. cli.set_connection_timeout(std::chrono::seconds(5));
  1476. auto res =
  1477. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1478. "application/json", [](uint64_t, uint64_t) { return true; });
  1479. ASSERT_TRUE(res);
  1480. EXPECT_EQ("Hello World!", res->body);
  1481. EXPECT_EQ(StatusCode::OK_200, res->status);
  1482. }
  1483. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1484. Server svr;
  1485. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1486. res.set_content("Hello World!", "text/plain");
  1487. });
  1488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1489. auto se = detail::scope_exit([&] {
  1490. svr.stop();
  1491. thread.join();
  1492. ASSERT_FALSE(svr.is_running());
  1493. });
  1494. svr.wait_until_ready();
  1495. Client cli(HOST, PORT);
  1496. cli.set_connection_timeout(std::chrono::seconds(5));
  1497. auto res =
  1498. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1499. "application/json", [](uint64_t, uint64_t) { return false; });
  1500. ASSERT_TRUE(!res);
  1501. EXPECT_EQ(Error::Canceled, res.error());
  1502. }
  1503. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1504. Server svr;
  1505. svr.set_payload_max_length(200 * 1024 * 1024);
  1506. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content(LARGE_DATA, "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_payload_max_length(200 * 1024 * 1024);
  1518. cli.set_connection_timeout(std::chrono::seconds(5));
  1519. auto res =
  1520. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1521. "application/json", [](uint64_t, uint64_t) { return false; });
  1522. ASSERT_TRUE(!res);
  1523. EXPECT_EQ(Error::Canceled, res.error());
  1524. }
  1525. TEST(CancelTest, NoCancelDelete) {
  1526. Server svr;
  1527. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return true; });
  1542. ASSERT_TRUE(res);
  1543. EXPECT_EQ("Hello World!", res->body);
  1544. EXPECT_EQ(StatusCode::OK_200, res->status);
  1545. }
  1546. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1547. Server svr;
  1548. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content("Hello World!", "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_connection_timeout(std::chrono::seconds(5));
  1560. auto res =
  1561. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1562. "application/json", [](uint64_t, uint64_t) { return false; });
  1563. ASSERT_TRUE(!res);
  1564. EXPECT_EQ(Error::Canceled, res.error());
  1565. }
  1566. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1567. Server svr;
  1568. svr.set_payload_max_length(200 * 1024 * 1024);
  1569. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content(LARGE_DATA, "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. Client cli(HOST, PORT);
  1580. cli.set_payload_max_length(200 * 1024 * 1024);
  1581. cli.set_connection_timeout(std::chrono::seconds(5));
  1582. auto res =
  1583. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1584. "application/json", [](uint64_t, uint64_t) { return false; });
  1585. ASSERT_TRUE(!res);
  1586. EXPECT_EQ(Error::Canceled, res.error());
  1587. }
  1588. static std::string remove_whitespace(const std::string &input) {
  1589. std::string output;
  1590. output.reserve(input.size());
  1591. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1592. [](unsigned char c) { return !std::isspace(c); });
  1593. return output;
  1594. }
  1595. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1596. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1597. auto host = "httpcan.org";
  1598. auto path = std::string{"/basic-auth/hello/world"};
  1599. #else
  1600. auto host = "nghttp2.org";
  1601. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1602. #endif
  1603. #ifdef CPPHTTPLIB_SSL_ENABLED
  1604. auto port = 443;
  1605. SSLClient cli(host, port);
  1606. #else
  1607. auto port = 80;
  1608. Client cli(host, port);
  1609. #endif
  1610. {
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1614. }
  1615. {
  1616. auto res =
  1617. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1620. remove_whitespace(res->body));
  1621. EXPECT_EQ(StatusCode::OK_200, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("hello", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1628. remove_whitespace(res->body));
  1629. EXPECT_EQ(StatusCode::OK_200, res->status);
  1630. }
  1631. {
  1632. cli.set_basic_auth("hello", "bad");
  1633. auto res = cli.Get(path);
  1634. ASSERT_TRUE(res);
  1635. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1636. }
  1637. {
  1638. cli.set_basic_auth("bad", "world");
  1639. auto res = cli.Get(path);
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1642. }
  1643. }
  1644. #ifdef CPPHTTPLIB_SSL_ENABLED
  1645. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1646. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1647. auto host = "httpcan.org";
  1648. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1649. auto paths = std::vector<std::string>{
  1650. "/digest-auth/auth/hello/world/MD5",
  1651. "/digest-auth/auth/hello/world/SHA-256",
  1652. "/digest-auth/auth/hello/world/SHA-512",
  1653. };
  1654. #else
  1655. auto host = "nghttp2.org";
  1656. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1657. auto paths = std::vector<std::string>{
  1658. "/httpbin/digest-auth/auth/hello/world/MD5",
  1659. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1660. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1661. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1662. };
  1663. #endif
  1664. auto port = 443;
  1665. SSLClient cli(host, port);
  1666. {
  1667. auto res = cli.Get(unauth_path);
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1670. }
  1671. {
  1672. cli.set_digest_auth("hello", "world");
  1673. for (const auto &path : paths) {
  1674. auto res = cli.Get(path.c_str());
  1675. ASSERT_TRUE(res);
  1676. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1677. std::string algo(path.substr(path.rfind('/') + 1));
  1678. EXPECT_EQ(
  1679. remove_whitespace("{\"algorithm\":\"" + algo +
  1680. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1681. remove_whitespace(res->body));
  1682. #else
  1683. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1684. remove_whitespace(res->body));
  1685. #endif
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. cli.set_digest_auth("hello", "bad");
  1690. for (const auto &path : paths) {
  1691. auto res = cli.Get(path.c_str());
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1694. }
  1695. #endif
  1696. }
  1697. }
  1698. #endif
  1699. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1700. auto host = "google.com";
  1701. auto another_host = "example.com";
  1702. auto wrong_ip = "0.0.0.0";
  1703. #ifdef CPPHTTPLIB_SSL_ENABLED
  1704. SSLClient cli(host);
  1705. #else
  1706. Client cli(host);
  1707. #endif
  1708. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1709. auto res = cli.Get("/");
  1710. ASSERT_TRUE(res);
  1711. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1712. }
  1713. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1714. auto host = "google.com";
  1715. auto wrong_ip = "0.0.0.0";
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. SSLClient cli(host);
  1718. #else
  1719. Client cli(host);
  1720. #endif
  1721. cli.set_hostname_addr_map({{host, wrong_ip}});
  1722. auto res = cli.Get("/");
  1723. ASSERT_TRUE(!res);
  1724. EXPECT_EQ(Error::Connection, res.error());
  1725. }
  1726. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1727. auto host = "nghttp2.org";
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. SSLClient cli(host);
  1730. #else
  1731. Client cli(host);
  1732. #endif
  1733. cli.set_follow_location(true);
  1734. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1735. ASSERT_TRUE(res);
  1736. EXPECT_EQ(StatusCode::OK_200, res->status);
  1737. }
  1738. TEST(RedirectTest, 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/redirect/3");
  1747. ASSERT_TRUE(res);
  1748. EXPECT_EQ(StatusCode::OK_200, res->status);
  1749. }
  1750. TEST(RelativeRedirectTest, 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/relative-redirect/3");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. }
  1762. TEST(TooManyRedirectTest, 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/redirect/21");
  1771. ASSERT_TRUE(!res);
  1772. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1773. }
  1774. #ifdef CPPHTTPLIB_SSL_ENABLED
  1775. TEST(YahooRedirectTest, Redirect_Online) {
  1776. Client cli("yahoo.com");
  1777. auto res = cli.Get("/");
  1778. ASSERT_TRUE(res);
  1779. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1780. cli.set_follow_location(true);
  1781. res = cli.Get("/");
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1785. }
  1786. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1787. #define REDIR_HOST "httpbingo.org"
  1788. #define REDIR_PATH "/redirect-to"
  1789. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1790. SSLClient cli(REDIR_HOST);
  1791. cli.set_follow_location(true);
  1792. auto res =
  1793. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(StatusCode::OK_200, res->status);
  1796. }
  1797. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1798. SSLClient cli(REDIR_HOST);
  1799. cli.set_follow_location(true);
  1800. Params params;
  1801. params.emplace("url", "http://example.com");
  1802. params.emplace("status_code", "302");
  1803. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1804. ASSERT_TRUE(res);
  1805. EXPECT_EQ(StatusCode::OK_200, res->status);
  1806. }
  1807. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1808. SSLClient cli(REDIR_HOST);
  1809. cli.set_follow_location(true);
  1810. Params params;
  1811. params.emplace("url", "http://example.com");
  1812. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::OK_200, res->status);
  1815. }
  1816. TEST(UrlWithSpace, Redirect_Online) {
  1817. SSLClient cli("edge.forgecdn.net");
  1818. cli.set_follow_location(true);
  1819. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::OK_200, res->status);
  1822. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1823. }
  1824. #endif
  1825. #if !defined(_WIN32) && !defined(_WIN64)
  1826. TEST(ReceiveSignals, Signal) {
  1827. auto setupSignalHandlers = []() {
  1828. struct sigaction act;
  1829. sigemptyset(&act.sa_mask);
  1830. act.sa_flags = SA_SIGINFO;
  1831. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1832. switch (sig) {
  1833. case SIGINT:
  1834. default: break;
  1835. }
  1836. };
  1837. ::sigaction(SIGINT, &act, nullptr);
  1838. };
  1839. Server svr;
  1840. int port = 0;
  1841. auto thread = std::thread([&]() {
  1842. setupSignalHandlers();
  1843. port = svr.bind_to_any_port(HOST);
  1844. svr.listen_after_bind();
  1845. });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. thread.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. svr.wait_until_ready();
  1852. ASSERT_TRUE(svr.is_running());
  1853. pthread_kill(thread.native_handle(), SIGINT);
  1854. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1855. ASSERT_TRUE(svr.is_running());
  1856. }
  1857. #endif
  1858. TEST(RedirectToDifferentPort, Redirect) {
  1859. Server svr1;
  1860. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1861. res.set_content("Hello World!", "text/plain");
  1862. });
  1863. int svr1_port = 0;
  1864. auto thread1 = std::thread([&]() {
  1865. svr1_port = svr1.bind_to_any_port(HOST);
  1866. svr1.listen_after_bind();
  1867. });
  1868. Server svr2;
  1869. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1870. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1871. });
  1872. int svr2_port = 0;
  1873. auto thread2 = std::thread([&]() {
  1874. svr2_port = svr2.bind_to_any_port(HOST);
  1875. svr2.listen_after_bind();
  1876. });
  1877. auto se = detail::scope_exit([&] {
  1878. svr2.stop();
  1879. thread2.join();
  1880. svr1.stop();
  1881. thread1.join();
  1882. ASSERT_FALSE(svr2.is_running());
  1883. ASSERT_FALSE(svr1.is_running());
  1884. });
  1885. svr1.wait_until_ready();
  1886. svr2.wait_until_ready();
  1887. Client cli("localhost", svr2_port);
  1888. cli.set_follow_location(true);
  1889. auto res = cli.Get("/2");
  1890. ASSERT_TRUE(res);
  1891. EXPECT_EQ(StatusCode::OK_200, res->status);
  1892. EXPECT_EQ("Hello World!", res->body);
  1893. }
  1894. TEST(RedirectFromPageWithContent, Redirect) {
  1895. Server svr;
  1896. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1897. res.set_content("___", "text/plain");
  1898. res.set_redirect("/2");
  1899. });
  1900. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1901. res.set_content("Hello World!", "text/plain");
  1902. });
  1903. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. th.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. {
  1911. Client cli("localhost", PORT);
  1912. cli.set_follow_location(true);
  1913. std::string body;
  1914. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1915. body.append(data, data_length);
  1916. return true;
  1917. });
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. EXPECT_EQ("Hello World!", body);
  1921. }
  1922. {
  1923. Client cli("localhost", PORT);
  1924. std::string body;
  1925. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1926. body.append(data, data_length);
  1927. return true;
  1928. });
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(StatusCode::Found_302, res->status);
  1931. EXPECT_EQ("___", body);
  1932. }
  1933. }
  1934. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1935. Server svr;
  1936. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1937. res.set_content("___", "text/plain");
  1938. // res.set_redirect("/2");
  1939. res.set_redirect("http://[::1]:1234/2");
  1940. });
  1941. svr.Get("/2", [&](const Request &req, Response &res) {
  1942. auto host_header = req.headers.find("Host");
  1943. ASSERT_TRUE(host_header != req.headers.end());
  1944. EXPECT_EQ("[::1]:1234", host_header->second);
  1945. res.set_content("Hello World!", "text/plain");
  1946. });
  1947. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1948. auto se = detail::scope_exit([&] {
  1949. svr.stop();
  1950. th.join();
  1951. ASSERT_FALSE(svr.is_running());
  1952. });
  1953. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1954. // actually starts anything, so the condition !svr.is_running() will
  1955. // always remain true, and the loop never stops.
  1956. // This basically counts how many milliseconds have passed since the
  1957. // call to svr.listen(), and if after 5 seconds nothing started yet
  1958. // aborts the test.
  1959. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1960. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1961. ASSERT_LT(milliseconds, 5000U);
  1962. }
  1963. {
  1964. Client cli("http://[::1]:1234");
  1965. cli.set_follow_location(true);
  1966. std::string body;
  1967. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1968. body.append(data, data_length);
  1969. return true;
  1970. });
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::OK_200, res->status);
  1973. EXPECT_EQ("Hello World!", body);
  1974. }
  1975. {
  1976. Client cli("http://[::1]:1234");
  1977. std::string body;
  1978. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1979. body.append(data, data_length);
  1980. return true;
  1981. });
  1982. ASSERT_TRUE(res);
  1983. EXPECT_EQ(StatusCode::Found_302, res->status);
  1984. EXPECT_EQ("___", body);
  1985. }
  1986. }
  1987. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1988. Server svr;
  1989. svr.Get("/foo", [](const Request &req, Response &res) {
  1990. auto a = req.params.find("a");
  1991. if (a != req.params.end()) {
  1992. res.set_content((*a).second, "text/plain");
  1993. res.status = StatusCode::OK_200;
  1994. } else {
  1995. res.status = StatusCode::BadRequest_400;
  1996. }
  1997. });
  1998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1999. auto se = detail::scope_exit([&] {
  2000. svr.stop();
  2001. thread.join();
  2002. ASSERT_FALSE(svr.is_running());
  2003. });
  2004. svr.wait_until_ready();
  2005. {
  2006. Client cli(HOST, PORT);
  2007. cli.set_path_encode(false);
  2008. auto res = cli.Get("/foo?a=explicitly+encoded");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. // This expects it back with a space, as the `+` won't have been
  2012. // url-encoded, and server-side the params get decoded turning `+`
  2013. // into spaces.
  2014. EXPECT_EQ("explicitly encoded", res->body);
  2015. }
  2016. }
  2017. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2018. Server svr;
  2019. svr.Get("/", [](const Request &req, Response &) {
  2020. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2021. });
  2022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2023. auto se = detail::scope_exit([&] {
  2024. svr.stop();
  2025. thread.join();
  2026. ASSERT_FALSE(svr.is_running());
  2027. });
  2028. svr.wait_until_ready();
  2029. {
  2030. Client cli(HOST, PORT);
  2031. cli.set_path_encode(false);
  2032. auto res = cli.Get("/?something=%0A");
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(StatusCode::OK_200, res->status);
  2035. }
  2036. }
  2037. TEST(BindServerTest, DISABLED_BindDualStack) {
  2038. Server svr;
  2039. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2040. res.set_content("Hello World!", "text/plain");
  2041. });
  2042. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2043. auto se = detail::scope_exit([&] {
  2044. svr.stop();
  2045. thread.join();
  2046. ASSERT_FALSE(svr.is_running());
  2047. });
  2048. svr.wait_until_ready();
  2049. {
  2050. Client cli("127.0.0.1", PORT);
  2051. auto res = cli.Get("/1");
  2052. ASSERT_TRUE(res);
  2053. EXPECT_EQ(StatusCode::OK_200, res->status);
  2054. EXPECT_EQ("Hello World!", res->body);
  2055. }
  2056. {
  2057. Client cli("::1", PORT);
  2058. auto res = cli.Get("/1");
  2059. ASSERT_TRUE(res);
  2060. EXPECT_EQ(StatusCode::OK_200, res->status);
  2061. EXPECT_EQ("Hello World!", res->body);
  2062. }
  2063. }
  2064. TEST(BindServerTest, BindAndListenSeparately) {
  2065. Server svr;
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. svr.stop();
  2070. }
  2071. #ifdef CPPHTTPLIB_SSL_ENABLED
  2072. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2074. CLIENT_CA_CERT_DIR);
  2075. int port = svr.bind_to_any_port("0.0.0.0");
  2076. ASSERT_TRUE(svr.is_valid());
  2077. ASSERT_TRUE(port > 0);
  2078. svr.stop();
  2079. }
  2080. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2081. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2082. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2083. int port = svr.bind_to_any_port("0.0.0.0");
  2084. ASSERT_TRUE(svr.is_valid());
  2085. ASSERT_TRUE(port > 0);
  2086. svr.stop();
  2087. }
  2088. TEST(BindServerTest, UpdateCertsPem) {
  2089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2090. int port = svr.bind_to_any_port("0.0.0.0");
  2091. ASSERT_TRUE(svr.is_valid());
  2092. ASSERT_TRUE(port > 0);
  2093. // Read PEM files
  2094. std::string cert_pem, key_pem, ca_pem;
  2095. read_file(SERVER_CERT_FILE, cert_pem);
  2096. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2097. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2098. // Update server certificates using PEM API
  2099. ASSERT_TRUE(
  2100. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2101. ASSERT_TRUE(svr.is_valid());
  2102. svr.stop();
  2103. }
  2104. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2105. // Start server with client CA (enables client auth)
  2106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2107. ASSERT_TRUE(svr.is_valid());
  2108. bool handler_called = false;
  2109. svr.Get("/test", [&](const Request &req, Response &res) {
  2110. handler_called = true;
  2111. // Verify client certificate is present
  2112. auto cert = req.peer_cert();
  2113. EXPECT_TRUE(static_cast<bool>(cert));
  2114. res.set_content("ok", "text/plain");
  2115. });
  2116. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2117. auto se = detail::scope_exit([&] {
  2118. svr.stop();
  2119. t.join();
  2120. ASSERT_FALSE(svr.is_running());
  2121. });
  2122. svr.wait_until_ready();
  2123. // Read PEM files
  2124. std::string cert_pem, key_pem, ca_pem;
  2125. read_file(SERVER_CERT_FILE, cert_pem);
  2126. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2127. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2128. // Update server certificates and client CA using PEM API while server running
  2129. ASSERT_TRUE(
  2130. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2131. // Connect with client certificate
  2132. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2133. cli.enable_server_certificate_verification(false);
  2134. cli.set_connection_timeout(30);
  2135. auto res = cli.Get("/test");
  2136. ASSERT_TRUE(res);
  2137. ASSERT_EQ(StatusCode::OK_200, res->status);
  2138. ASSERT_TRUE(handler_called);
  2139. EXPECT_EQ("ok", res->body);
  2140. }
  2141. #endif
  2142. TEST(ErrorHandlerTest, ContentLength) {
  2143. Server svr;
  2144. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2145. res.status = StatusCode::OK_200;
  2146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2147. "text/html"); // <= Content-Length still 13
  2148. });
  2149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!\n", "text/plain");
  2151. res.status = 524;
  2152. });
  2153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2154. auto se = detail::scope_exit([&] {
  2155. svr.stop();
  2156. thread.join();
  2157. ASSERT_FALSE(svr.is_running());
  2158. });
  2159. svr.wait_until_ready();
  2160. {
  2161. Client cli(HOST, PORT);
  2162. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2163. ASSERT_TRUE(res);
  2164. EXPECT_EQ(StatusCode::OK_200, res->status);
  2165. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2166. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2168. }
  2169. }
  2170. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2171. TEST(ExceptionTest, WithoutExceptionHandler) {
  2172. Server svr;
  2173. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2174. throw std::runtime_error("exception...");
  2175. });
  2176. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2177. throw std::runtime_error("exception\r\n...");
  2178. });
  2179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2180. auto se = detail::scope_exit([&] {
  2181. svr.stop();
  2182. listen_thread.join();
  2183. ASSERT_FALSE(svr.is_running());
  2184. });
  2185. svr.wait_until_ready();
  2186. Client cli("localhost", PORT);
  2187. {
  2188. auto res = cli.Get("/exception");
  2189. ASSERT_TRUE(res);
  2190. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2191. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2192. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2193. }
  2194. {
  2195. auto res = cli.Get("/unknown");
  2196. ASSERT_TRUE(res);
  2197. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2198. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2199. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2200. }
  2201. }
  2202. TEST(ExceptionTest, WithExceptionHandler) {
  2203. Server svr;
  2204. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2205. std::exception_ptr ep) {
  2206. EXPECT_FALSE(ep == nullptr);
  2207. try {
  2208. std::rethrow_exception(ep);
  2209. } catch (std::exception &e) {
  2210. EXPECT_EQ("abc", std::string(e.what()));
  2211. } catch (...) {}
  2212. res.status = StatusCode::InternalServerError_500;
  2213. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2214. "text/html"); // <= Content-Length still 13 at this point
  2215. });
  2216. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2217. res.set_content("Hello World!\n", "text/plain");
  2218. throw std::runtime_error("abc");
  2219. });
  2220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2221. auto se = detail::scope_exit([&] {
  2222. svr.stop();
  2223. thread.join();
  2224. ASSERT_FALSE(svr.is_running());
  2225. });
  2226. svr.wait_until_ready();
  2227. for (size_t i = 0; i < 10; i++) {
  2228. Client cli(HOST, PORT);
  2229. for (size_t j = 0; j < 100; j++) {
  2230. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2231. ASSERT_TRUE(res);
  2232. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2234. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2235. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2236. }
  2237. cli.set_keep_alive(true);
  2238. for (size_t j = 0; j < 100; j++) {
  2239. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2240. ASSERT_TRUE(res);
  2241. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2242. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2243. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2245. }
  2246. }
  2247. }
  2248. TEST(ExceptionTest, AndErrorHandler) {
  2249. Server svr;
  2250. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2251. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2252. });
  2253. svr.set_exception_handler(
  2254. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2255. EXPECT_FALSE(ep == nullptr);
  2256. try {
  2257. std::rethrow_exception(ep);
  2258. } catch (std::exception &e) {
  2259. res.set_content(e.what(), "text/html");
  2260. } catch (...) {}
  2261. res.status = StatusCode::InternalServerError_500;
  2262. });
  2263. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2264. throw std::runtime_error("EXCEPTION");
  2265. });
  2266. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2267. res.set_content("ERROR", "text/html");
  2268. res.status = StatusCode::InternalServerError_500;
  2269. });
  2270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2271. auto se = detail::scope_exit([&] {
  2272. svr.stop();
  2273. thread.join();
  2274. ASSERT_FALSE(svr.is_running());
  2275. });
  2276. svr.wait_until_ready();
  2277. Client cli(HOST, PORT);
  2278. {
  2279. auto res = cli.Get("/exception");
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2282. EXPECT_EQ("EXCEPTION", res->body);
  2283. }
  2284. {
  2285. auto res = cli.Get("/error");
  2286. ASSERT_TRUE(res);
  2287. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2288. EXPECT_EQ("ERROR", res->body);
  2289. }
  2290. {
  2291. auto res = cli.Get("/invalid");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2294. EXPECT_EQ("NOT_FOUND", res->body);
  2295. }
  2296. }
  2297. #endif
  2298. TEST(NoContentTest, ContentLength) {
  2299. Server svr;
  2300. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2301. res.status = StatusCode::NoContent_204;
  2302. });
  2303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2304. auto se = detail::scope_exit([&] {
  2305. svr.stop();
  2306. thread.join();
  2307. ASSERT_FALSE(svr.is_running());
  2308. });
  2309. svr.wait_until_ready();
  2310. {
  2311. Client cli(HOST, PORT);
  2312. auto res = cli.Get("/hi");
  2313. ASSERT_TRUE(res);
  2314. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2315. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2316. }
  2317. }
  2318. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2319. #ifdef CPPHTTPLIB_SSL_ENABLED
  2320. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2321. ASSERT_TRUE(svr.is_valid());
  2322. #else
  2323. Server svr;
  2324. #endif
  2325. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2326. if (req.path == "/routing_handler") {
  2327. res.set_header("PRE_ROUTING", "on");
  2328. res.set_content("Routing Handler", "text/plain");
  2329. return httplib::Server::HandlerResponse::Handled;
  2330. }
  2331. return httplib::Server::HandlerResponse::Unhandled;
  2332. });
  2333. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2334. res.set_content("Error", "text/html");
  2335. });
  2336. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2337. if (req.path == "/routing_handler") {
  2338. res.set_header("POST_ROUTING", "on");
  2339. }
  2340. });
  2341. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2342. res.set_content("Hello World!\n", "text/plain");
  2343. });
  2344. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2345. auto se = detail::scope_exit([&] {
  2346. svr.stop();
  2347. thread.join();
  2348. ASSERT_FALSE(svr.is_running());
  2349. });
  2350. svr.wait_until_ready();
  2351. {
  2352. #ifdef CPPHTTPLIB_SSL_ENABLED
  2353. SSLClient cli(HOST, PORT);
  2354. cli.enable_server_certificate_verification(false);
  2355. #else
  2356. Client cli(HOST, PORT);
  2357. #endif
  2358. auto res = cli.Get("/routing_handler");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ(StatusCode::OK_200, res->status);
  2361. EXPECT_EQ("Routing Handler", res->body);
  2362. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2363. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2364. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2365. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2366. }
  2367. {
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. SSLClient cli(HOST, PORT);
  2370. cli.enable_server_certificate_verification(false);
  2371. #else
  2372. Client cli(HOST, PORT);
  2373. #endif
  2374. auto res = cli.Get("/hi");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("Hello World!\n", res->body);
  2378. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2379. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2380. }
  2381. {
  2382. #ifdef CPPHTTPLIB_SSL_ENABLED
  2383. SSLClient cli(HOST, PORT);
  2384. cli.enable_server_certificate_verification(false);
  2385. #else
  2386. Client cli(HOST, PORT);
  2387. #endif
  2388. auto res = cli.Get("/aaa");
  2389. ASSERT_TRUE(res);
  2390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2391. EXPECT_EQ("Error", res->body);
  2392. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2393. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2394. }
  2395. }
  2396. TEST(RequestHandlerTest, PreRequestHandler) {
  2397. auto route_path = "/user/:user";
  2398. Server svr;
  2399. svr.Get("/hi", [](const Request &, Response &res) {
  2400. res.set_content("hi", "text/plain");
  2401. });
  2402. svr.Get(route_path, [](const Request &req, Response &res) {
  2403. res.set_content(req.path_params.at("user"), "text/plain");
  2404. });
  2405. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2406. if (req.matched_route == route_path) {
  2407. auto user = req.path_params.at("user");
  2408. if (user != "john") {
  2409. res.status = StatusCode::Forbidden_403;
  2410. res.set_content("error", "text/html");
  2411. return Server::HandlerResponse::Handled;
  2412. }
  2413. }
  2414. return Server::HandlerResponse::Unhandled;
  2415. });
  2416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2417. auto se = detail::scope_exit([&] {
  2418. svr.stop();
  2419. thread.join();
  2420. ASSERT_FALSE(svr.is_running());
  2421. });
  2422. svr.wait_until_ready();
  2423. Client cli(HOST, PORT);
  2424. {
  2425. auto res = cli.Get("/hi");
  2426. ASSERT_TRUE(res);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. EXPECT_EQ("hi", res->body);
  2429. }
  2430. {
  2431. auto res = cli.Get("/user/john");
  2432. ASSERT_TRUE(res);
  2433. EXPECT_EQ(StatusCode::OK_200, res->status);
  2434. EXPECT_EQ("john", res->body);
  2435. }
  2436. {
  2437. auto res = cli.Get("/user/invalid-user");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2440. EXPECT_EQ("error", res->body);
  2441. }
  2442. }
  2443. TEST(InvalidFormatTest, StatusCode) {
  2444. Server svr;
  2445. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2446. res.set_content("Hello World!\n", "text/plain");
  2447. res.status = 9999; // Status should be a three-digit code...
  2448. });
  2449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2450. auto se = detail::scope_exit([&] {
  2451. svr.stop();
  2452. thread.join();
  2453. ASSERT_FALSE(svr.is_running());
  2454. });
  2455. svr.wait_until_ready();
  2456. {
  2457. Client cli(HOST, PORT);
  2458. auto res = cli.Get("/hi");
  2459. ASSERT_FALSE(res);
  2460. }
  2461. }
  2462. TEST(URLFragmentTest, WithFragment) {
  2463. Server svr;
  2464. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2465. EXPECT_TRUE(req.target == "/hi");
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. {
  2475. Client cli(HOST, PORT);
  2476. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2477. EXPECT_TRUE(res);
  2478. EXPECT_EQ(StatusCode::OK_200, res->status);
  2479. res = cli.Get("/hi%23key1=val1=key2=val2");
  2480. EXPECT_TRUE(res);
  2481. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2482. }
  2483. }
  2484. TEST(HeaderWriter, SetHeaderWriter) {
  2485. Server svr;
  2486. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2487. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2488. return detail::write_headers(strm, hdrs);
  2489. });
  2490. svr.Get("/hi", [](const Request &req, Response &res) {
  2491. auto it = req.headers.find("CustomClientHeader");
  2492. EXPECT_TRUE(it != req.headers.end());
  2493. EXPECT_EQ(it->second, "CustomClientValue");
  2494. res.set_content("Hello World!\n", "text/plain");
  2495. });
  2496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. thread.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. svr.wait_until_ready();
  2503. {
  2504. Client cli(HOST, PORT);
  2505. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2506. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2507. return detail::write_headers(strm, hdrs);
  2508. });
  2509. auto res = cli.Get("/hi");
  2510. EXPECT_TRUE(res);
  2511. EXPECT_EQ(StatusCode::OK_200, res->status);
  2512. auto it = res->headers.find("CustomServerHeader");
  2513. EXPECT_TRUE(it != res->headers.end());
  2514. EXPECT_EQ(it->second, "CustomServerValue");
  2515. }
  2516. }
  2517. class ServerTest : public ::testing::Test {
  2518. protected:
  2519. ServerTest()
  2520. : cli_(HOST, PORT)
  2521. #ifdef CPPHTTPLIB_SSL_ENABLED
  2522. ,
  2523. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2524. #endif
  2525. {
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. cli_.enable_server_certificate_verification(false);
  2528. #endif
  2529. // Allow LARGE_DATA (100MB) responses
  2530. cli_.set_payload_max_length(200 * 1024 * 1024);
  2531. }
  2532. virtual void SetUp() {
  2533. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2534. svr_.set_payload_max_length(200 * 1024 * 1024);
  2535. svr_.set_mount_point("/", "./www");
  2536. svr_.set_mount_point("/mount", "./www2");
  2537. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2538. svr_.Get("/hi",
  2539. [&](const Request & /*req*/, Response &res) {
  2540. res.set_content("Hello World!", "text/plain");
  2541. })
  2542. .Get("/file_content",
  2543. [&](const Request & /*req*/, Response &res) {
  2544. res.set_file_content("./www/dir/test.html");
  2545. })
  2546. .Get("/file_content_with_content_type",
  2547. [&](const Request & /*req*/, Response &res) {
  2548. res.set_file_content("./www/file", "text/plain");
  2549. })
  2550. .Get("/invalid_file_content",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_file_content("./www/dir/invalid_file_path");
  2553. })
  2554. .Get("/http_response_splitting",
  2555. [&](const Request & /*req*/, Response &res) {
  2556. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2557. EXPECT_EQ(0U, res.headers.size());
  2558. EXPECT_FALSE(res.has_header("a"));
  2559. res.set_header("a", "1\nSet-Cookie: a=1");
  2560. EXPECT_EQ(0U, res.headers.size());
  2561. EXPECT_FALSE(res.has_header("a"));
  2562. res.set_header("a", "1\rSet-Cookie: a=1");
  2563. EXPECT_EQ(0U, res.headers.size());
  2564. EXPECT_FALSE(res.has_header("a"));
  2565. res.set_header("a\r\nb", "0");
  2566. EXPECT_EQ(0U, res.headers.size());
  2567. EXPECT_FALSE(res.has_header("a"));
  2568. res.set_header("a\rb", "0");
  2569. EXPECT_EQ(0U, res.headers.size());
  2570. EXPECT_FALSE(res.has_header("a"));
  2571. res.set_header("a\nb", "0");
  2572. EXPECT_EQ(0U, res.headers.size());
  2573. EXPECT_FALSE(res.has_header("a"));
  2574. res.set_redirect("1\r\nSet-Cookie: a=1");
  2575. EXPECT_EQ(0U, res.headers.size());
  2576. EXPECT_FALSE(res.has_header("Location"));
  2577. })
  2578. .Get("/slow",
  2579. [&](const Request & /*req*/, Response &res) {
  2580. std::this_thread::sleep_for(std::chrono::seconds(2));
  2581. res.set_content("slow", "text/plain");
  2582. })
  2583. #if 0
  2584. .Post("/slowpost",
  2585. [&](const Request & /*req*/, Response &res) {
  2586. std::this_thread::sleep_for(std::chrono::seconds(2));
  2587. res.set_content("slow", "text/plain");
  2588. })
  2589. #endif
  2590. .Get("/remote_addr",
  2591. [&](const Request &req, Response &res) {
  2592. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2593. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2594. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2595. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2596. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2597. #endif
  2598. res.set_content(req.remote_addr, "text/plain");
  2599. })
  2600. .Get("/local_addr",
  2601. [&](const Request &req, Response &res) {
  2602. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2603. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2604. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2605. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2606. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2607. #endif
  2608. auto local_addr = req.local_addr;
  2609. auto local_port = std::to_string(req.local_port);
  2610. res.set_content(local_addr.append(":").append(local_port),
  2611. "text/plain");
  2612. })
  2613. .Get("/endwith%",
  2614. [&](const Request & /*req*/, Response &res) {
  2615. res.set_content("Hello World!", "text/plain");
  2616. })
  2617. .Get("/a\\+\\+b",
  2618. [&](const Request &req, Response &res) {
  2619. ASSERT_TRUE(req.has_param("a +b"));
  2620. auto val = req.get_param_value("a +b");
  2621. res.set_content(val, "text/plain");
  2622. })
  2623. .Get("/", [&](const Request & /*req*/,
  2624. Response &res) { res.set_redirect("/hi"); })
  2625. .Post("/1",
  2626. [](const Request & /*req*/, Response &res) {
  2627. res.set_redirect("/2", StatusCode::SeeOther_303);
  2628. })
  2629. .Get("/2",
  2630. [](const Request & /*req*/, Response &res) {
  2631. res.set_content("redirected.", "text/plain");
  2632. res.status = StatusCode::OK_200;
  2633. })
  2634. .Post("/person",
  2635. [&](const Request &req, Response &res) {
  2636. if (req.has_param("name") && req.has_param("note")) {
  2637. persons_[req.get_param_value("name")] =
  2638. req.get_param_value("note");
  2639. } else {
  2640. res.status = StatusCode::BadRequest_400;
  2641. }
  2642. })
  2643. .Put("/person",
  2644. [&](const Request &req, Response &res) {
  2645. if (req.has_param("name") && req.has_param("note")) {
  2646. persons_[req.get_param_value("name")] =
  2647. req.get_param_value("note");
  2648. } else {
  2649. res.status = StatusCode::BadRequest_400;
  2650. }
  2651. })
  2652. .Get("/person/(.*)",
  2653. [&](const Request &req, Response &res) {
  2654. string name = req.matches[1];
  2655. if (persons_.find(name) != persons_.end()) {
  2656. auto note = persons_[name];
  2657. res.set_content(note, "text/plain");
  2658. } else {
  2659. res.status = StatusCode::NotFound_404;
  2660. }
  2661. })
  2662. .Delete("/person",
  2663. [&](const Request &req, Response &res) {
  2664. if (req.has_param("name")) {
  2665. string name = req.get_param_value("name");
  2666. if (persons_.find(name) != persons_.end()) {
  2667. persons_.erase(name);
  2668. res.set_content("DELETED", "text/plain");
  2669. } else {
  2670. res.status = StatusCode::NotFound_404;
  2671. }
  2672. } else {
  2673. res.status = StatusCode::BadRequest_400;
  2674. }
  2675. })
  2676. .Post("/x-www-form-urlencoded-json",
  2677. [&](const Request &req, Response &res) {
  2678. auto json = req.get_param_value("json");
  2679. ASSERT_EQ(JSON_DATA, json);
  2680. res.set_content(json, "appliation/json");
  2681. res.status = StatusCode::OK_200;
  2682. })
  2683. .Get("/streamed-chunked",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. res.set_chunked_content_provider(
  2686. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2687. sink.os << "123";
  2688. sink.os << "456";
  2689. sink.os << "789";
  2690. sink.done();
  2691. return true;
  2692. });
  2693. })
  2694. .Get("/streamed-chunked-with-prohibited-trailer",
  2695. [&](const Request & /*req*/, Response &res) {
  2696. auto i = new int(0);
  2697. // Declare both a prohibited trailer (Content-Length) and an
  2698. // allowed one
  2699. res.set_header("Trailer", "Content-Length, X-Allowed");
  2700. res.set_chunked_content_provider(
  2701. "text/plain",
  2702. [i](size_t /*offset*/, DataSink &sink) {
  2703. switch (*i) {
  2704. case 0: sink.os << "123"; break;
  2705. case 1: sink.os << "456"; break;
  2706. case 2: sink.os << "789"; break;
  2707. case 3: {
  2708. sink.done_with_trailer(
  2709. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2710. } break;
  2711. }
  2712. (*i)++;
  2713. return true;
  2714. },
  2715. [i](bool success) {
  2716. EXPECT_TRUE(success);
  2717. delete i;
  2718. });
  2719. })
  2720. .Get("/streamed-chunked2",
  2721. [&](const Request & /*req*/, Response &res) {
  2722. auto i = new int(0);
  2723. res.set_chunked_content_provider(
  2724. "text/plain",
  2725. [i](size_t /*offset*/, DataSink &sink) {
  2726. switch (*i) {
  2727. case 0: sink.os << "123"; break;
  2728. case 1: sink.os << "456"; break;
  2729. case 2: sink.os << "789"; break;
  2730. case 3: sink.done(); break;
  2731. }
  2732. (*i)++;
  2733. return true;
  2734. },
  2735. [i](bool success) {
  2736. EXPECT_TRUE(success);
  2737. delete i;
  2738. });
  2739. })
  2740. .Get("/streamed-chunked-with-trailer",
  2741. [&](const Request & /*req*/, Response &res) {
  2742. auto i = new int(0);
  2743. res.set_header("Trailer", "Dummy1, Dummy2");
  2744. res.set_chunked_content_provider(
  2745. "text/plain",
  2746. [i](size_t /*offset*/, DataSink &sink) {
  2747. switch (*i) {
  2748. case 0: sink.os << "123"; break;
  2749. case 1: sink.os << "456"; break;
  2750. case 2: sink.os << "789"; break;
  2751. case 3: {
  2752. sink.done_with_trailer(
  2753. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2754. } break;
  2755. }
  2756. (*i)++;
  2757. return true;
  2758. },
  2759. [i](bool success) {
  2760. EXPECT_TRUE(success);
  2761. delete i;
  2762. });
  2763. })
  2764. .Get("/streamed",
  2765. [&](const Request & /*req*/, Response &res) {
  2766. res.set_content_provider(
  2767. 6, "text/plain",
  2768. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2769. sink.os << (offset < 3 ? "a" : "b");
  2770. return true;
  2771. });
  2772. })
  2773. .Get("/streamed-with-range",
  2774. [&](const Request &req, Response &res) {
  2775. auto data = new std::string("abcdefg");
  2776. res.set_content_provider(
  2777. data->size(), "text/plain",
  2778. [data](size_t offset, size_t length, DataSink &sink) {
  2779. size_t DATA_CHUNK_SIZE = 4;
  2780. const auto &d = *data;
  2781. auto out_len =
  2782. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2783. auto ret =
  2784. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2785. EXPECT_TRUE(ret);
  2786. return true;
  2787. },
  2788. [data, &req](bool success) {
  2789. EXPECT_EQ(success, !req.has_param("error"));
  2790. delete data;
  2791. });
  2792. })
  2793. .Get("/streamed-cancel",
  2794. [&](const Request & /*req*/, Response &res) {
  2795. res.set_content_provider(
  2796. size_t(-1), "text/plain",
  2797. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2798. sink.os << "data_chunk";
  2799. return true;
  2800. });
  2801. })
  2802. .Get("/regex-with-delimiter",
  2803. [&](const Request &req, Response & /*res*/) {
  2804. ASSERT_TRUE(req.has_param("key"));
  2805. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2806. })
  2807. .Get("/with-range",
  2808. [&](const Request & /*req*/, Response &res) {
  2809. res.set_content("abcdefg", "text/plain");
  2810. })
  2811. .Get("/test-start-time",
  2812. [&](const Request &req, Response & /*res*/) {
  2813. EXPECT_NE(req.start_time_,
  2814. std::chrono::steady_clock::time_point::min());
  2815. })
  2816. .Get("/with-range-customized-response",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. res.status = StatusCode::BadRequest_400;
  2819. res.set_content(JSON_DATA, "application/json");
  2820. })
  2821. .Post("/chunked",
  2822. [&](const Request &req, Response & /*res*/) {
  2823. EXPECT_EQ(req.body, "dechunked post body");
  2824. })
  2825. .Post("/large-chunked",
  2826. [&](const Request &req, Response & /*res*/) {
  2827. std::string expected(6 * 30 * 1024u, 'a');
  2828. EXPECT_EQ(req.body, expected);
  2829. })
  2830. .Post("/multipart",
  2831. [&](const Request &req, Response & /*res*/) {
  2832. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2833. req.form.get_field_count("text2") +
  2834. req.form.get_field_count("file3") +
  2835. req.form.get_field_count("file4"));
  2836. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2837. req.form.get_file_count("file2"));
  2838. ASSERT_TRUE(!req.form.has_file("???"));
  2839. ASSERT_TRUE(!req.form.has_field("???"));
  2840. ASSERT_TRUE(req.body.empty());
  2841. {
  2842. const auto &text = req.form.get_field("text1");
  2843. EXPECT_EQ("text default", text);
  2844. }
  2845. {
  2846. const auto &text = req.form.get_field("text2");
  2847. EXPECT_EQ("aωb", text);
  2848. }
  2849. {
  2850. const auto &file = req.form.get_file("file1");
  2851. EXPECT_EQ("hello.txt", file.filename);
  2852. EXPECT_EQ("text/plain", file.content_type);
  2853. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2854. }
  2855. {
  2856. const auto &file = req.form.get_file("file2");
  2857. EXPECT_EQ("world.json", file.filename);
  2858. EXPECT_EQ("application/json", file.content_type);
  2859. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2860. }
  2861. {
  2862. const auto &text = req.form.get_field("file3");
  2863. EXPECT_EQ(0u, text.size());
  2864. }
  2865. {
  2866. const auto &text = req.form.get_field("file4");
  2867. EXPECT_EQ(0u, text.size());
  2868. }
  2869. })
  2870. .Post("/multipart/multi_file_values",
  2871. [&](const Request &req, Response & /*res*/) {
  2872. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2873. req.form.get_field_count("multi_text1"));
  2874. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2875. ASSERT_TRUE(!req.form.has_file("???"));
  2876. ASSERT_TRUE(!req.form.has_field("???"));
  2877. ASSERT_TRUE(req.body.empty());
  2878. {
  2879. const auto &text = req.form.get_field("text");
  2880. EXPECT_EQ("default text", text);
  2881. }
  2882. {
  2883. const auto &text1_values = req.form.get_fields("multi_text1");
  2884. EXPECT_EQ(2u, text1_values.size());
  2885. EXPECT_EQ("aaaaa", text1_values[0]);
  2886. EXPECT_EQ("bbbbb", text1_values[1]);
  2887. }
  2888. {
  2889. const auto &file1_values = req.form.get_files("multi_file1");
  2890. EXPECT_EQ(2u, file1_values.size());
  2891. auto file1 = file1_values[0];
  2892. EXPECT_EQ(file1.filename, "hello.txt");
  2893. EXPECT_EQ(file1.content_type, "text/plain");
  2894. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2895. auto file2 = file1_values[1];
  2896. EXPECT_EQ(file2.filename, "world.json");
  2897. EXPECT_EQ(file2.content_type, "application/json");
  2898. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2899. }
  2900. })
  2901. .Post("/empty",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "");
  2904. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2905. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2906. res.set_content("empty", "text/plain");
  2907. })
  2908. .Post("/empty-no-content-type",
  2909. [&](const Request &req, Response &res) {
  2910. EXPECT_EQ(req.body, "");
  2911. EXPECT_FALSE(req.has_header("Content-Type"));
  2912. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2913. res.set_content("empty-no-content-type", "text/plain");
  2914. })
  2915. .Post("/path-only",
  2916. [&](const Request &req, Response &res) {
  2917. EXPECT_EQ(req.body, "");
  2918. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2920. res.set_content("path-only", "text/plain");
  2921. })
  2922. .Post("/path-headers-only",
  2923. [&](const Request &req, Response &res) {
  2924. EXPECT_EQ(req.body, "");
  2925. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2926. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2927. EXPECT_EQ("world", req.get_header_value("hello"));
  2928. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2929. res.set_content("path-headers-only", "text/plain");
  2930. })
  2931. .Post("/post-large",
  2932. [&](const Request &req, Response &res) {
  2933. EXPECT_EQ(req.body, LARGE_DATA);
  2934. res.set_content(req.body, "text/plain");
  2935. })
  2936. .Post("/post-loopback",
  2937. [&](const Request &, Response &res,
  2938. ContentReader const &content_reader) {
  2939. std::string body;
  2940. content_reader([&](const char *data, size_t data_length) {
  2941. body.append(data, data_length);
  2942. return true;
  2943. });
  2944. res.set_content(body, "text/plain");
  2945. })
  2946. .Put("/put-loopback",
  2947. [&](const Request &, Response &res,
  2948. ContentReader const &content_reader) {
  2949. std::string body;
  2950. content_reader([&](const char *data, size_t data_length) {
  2951. body.append(data, data_length);
  2952. return true;
  2953. });
  2954. res.set_content(body, "text/plain");
  2955. })
  2956. .Patch("/patch-loopback",
  2957. [&](const Request &, Response &res,
  2958. ContentReader const &content_reader) {
  2959. std::string body;
  2960. content_reader([&](const char *data, size_t data_length) {
  2961. body.append(data, data_length);
  2962. return true;
  2963. });
  2964. res.set_content(body, "text/plain");
  2965. })
  2966. .Put("/empty-no-content-type",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(req.body, "");
  2969. EXPECT_FALSE(req.has_header("Content-Type"));
  2970. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2971. res.set_content("empty-no-content-type", "text/plain");
  2972. })
  2973. .Put("/put",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(req.body, "PUT");
  2976. res.set_content(req.body, "text/plain");
  2977. })
  2978. .Put("/put-large",
  2979. [&](const Request &req, Response &res) {
  2980. EXPECT_EQ(req.body, LARGE_DATA);
  2981. res.set_content(req.body, "text/plain");
  2982. })
  2983. .Patch("/patch",
  2984. [&](const Request &req, Response &res) {
  2985. EXPECT_EQ(req.body, "PATCH");
  2986. res.set_content(req.body, "text/plain");
  2987. })
  2988. .Delete("/delete",
  2989. [&](const Request & /*req*/, Response &res) {
  2990. res.set_content("DELETE", "text/plain");
  2991. })
  2992. .Delete("/delete-body",
  2993. [&](const Request &req, Response &res) {
  2994. EXPECT_EQ(req.body, "content");
  2995. res.set_content(req.body, "text/plain");
  2996. })
  2997. .Options(R"(\*)",
  2998. [&](const Request & /*req*/, Response &res) {
  2999. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3000. })
  3001. .Get("/request-target",
  3002. [&](const Request &req, Response & /*res*/) {
  3003. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3004. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3005. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3006. })
  3007. .Get("/long-query-value",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3010. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3011. })
  3012. .Get("/too-long-query-value",
  3013. [&](const Request &req, Response & /*res*/) {
  3014. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3015. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3016. })
  3017. .Get("/array-param",
  3018. [&](const Request &req, Response & /*res*/) {
  3019. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3020. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3021. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3022. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3023. })
  3024. .Post("/validate-no-multiple-headers",
  3025. [&](const Request &req, Response & /*res*/) {
  3026. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3027. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3028. })
  3029. .Post("/content_receiver",
  3030. [&](const Request &req, Response &res,
  3031. const ContentReader &content_reader) {
  3032. if (req.is_multipart_form_data()) {
  3033. std::vector<FormData> items;
  3034. content_reader(
  3035. [&](const FormData &file) {
  3036. items.push_back(file);
  3037. return true;
  3038. },
  3039. [&](const char *data, size_t data_length) {
  3040. items.back().content.append(data, data_length);
  3041. return true;
  3042. });
  3043. EXPECT_EQ(5u, items.size());
  3044. {
  3045. const auto &file = get_file_value(items, "text1");
  3046. EXPECT_TRUE(file.filename.empty());
  3047. EXPECT_EQ("text default", file.content);
  3048. }
  3049. {
  3050. const auto &file = get_file_value(items, "text2");
  3051. EXPECT_TRUE(file.filename.empty());
  3052. EXPECT_EQ("aωb", file.content);
  3053. }
  3054. {
  3055. const auto &file = get_file_value(items, "file1");
  3056. EXPECT_EQ("hello.txt", file.filename);
  3057. EXPECT_EQ("text/plain", file.content_type);
  3058. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3059. }
  3060. {
  3061. const auto &file = get_file_value(items, "file2");
  3062. EXPECT_EQ("world.json", file.filename);
  3063. EXPECT_EQ("application/json", file.content_type);
  3064. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3065. }
  3066. {
  3067. const auto &file = get_file_value(items, "file3");
  3068. EXPECT_TRUE(file.filename.empty());
  3069. EXPECT_EQ("application/octet-stream", file.content_type);
  3070. EXPECT_EQ(0u, file.content.size());
  3071. }
  3072. } else {
  3073. std::string body;
  3074. content_reader([&](const char *data, size_t data_length) {
  3075. EXPECT_EQ(7U, data_length);
  3076. body.append(data, data_length);
  3077. return true;
  3078. });
  3079. EXPECT_EQ(body, "content");
  3080. res.set_content(body, "text/plain");
  3081. }
  3082. })
  3083. .Put("/content_receiver",
  3084. [&](const Request & /*req*/, Response &res,
  3085. const ContentReader &content_reader) {
  3086. std::string body;
  3087. content_reader([&](const char *data, size_t data_length) {
  3088. body.append(data, data_length);
  3089. return true;
  3090. });
  3091. EXPECT_EQ(body, "content");
  3092. res.set_content(body, "text/plain");
  3093. })
  3094. .Patch("/content_receiver",
  3095. [&](const Request & /*req*/, Response &res,
  3096. const ContentReader &content_reader) {
  3097. std::string body;
  3098. content_reader([&](const char *data, size_t data_length) {
  3099. body.append(data, data_length);
  3100. return true;
  3101. });
  3102. EXPECT_EQ(body, "content");
  3103. res.set_content(body, "text/plain");
  3104. })
  3105. .Post("/query-string-and-body",
  3106. [&](const Request &req, Response & /*res*/) {
  3107. ASSERT_TRUE(req.has_param("key"));
  3108. EXPECT_EQ(req.get_param_value("key"), "value");
  3109. EXPECT_EQ(req.body, "content");
  3110. })
  3111. .Get("/last-request",
  3112. [&](const Request &req, Response & /*res*/) {
  3113. EXPECT_EQ("close", req.get_header_value("Connection"));
  3114. })
  3115. .Get(R"(/redirect/(\d+))",
  3116. [&](const Request &req, Response &res) {
  3117. auto num = std::stoi(req.matches[1]) + 1;
  3118. std::string url = "/redirect/" + std::to_string(num);
  3119. res.set_redirect(url);
  3120. })
  3121. .Post("/binary",
  3122. [&](const Request &req, Response &res) {
  3123. EXPECT_EQ(4U, req.body.size());
  3124. EXPECT_EQ("application/octet-stream",
  3125. req.get_header_value("Content-Type"));
  3126. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3127. res.set_content(req.body, "application/octet-stream");
  3128. })
  3129. .Put("/binary",
  3130. [&](const Request &req, Response &res) {
  3131. EXPECT_EQ(4U, req.body.size());
  3132. EXPECT_EQ("application/octet-stream",
  3133. req.get_header_value("Content-Type"));
  3134. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3135. res.set_content(req.body, "application/octet-stream");
  3136. })
  3137. .Patch("/binary",
  3138. [&](const Request &req, Response &res) {
  3139. EXPECT_EQ(4U, req.body.size());
  3140. EXPECT_EQ("application/octet-stream",
  3141. req.get_header_value("Content-Type"));
  3142. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3143. res.set_content(req.body, "application/octet-stream");
  3144. })
  3145. .Delete("/binary",
  3146. [&](const Request &req, Response &res) {
  3147. EXPECT_EQ(4U, req.body.size());
  3148. EXPECT_EQ("application/octet-stream",
  3149. req.get_header_value("Content-Type"));
  3150. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3151. res.set_content(req.body, "application/octet-stream");
  3152. })
  3153. .Get("/issue1772",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.status = 401;
  3156. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3157. })
  3158. .Delete("/issue609",
  3159. [](const httplib::Request &, httplib::Response &res,
  3160. const httplib::ContentReader &) {
  3161. res.set_content("ok", "text/plain");
  3162. })
  3163. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3164. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3165. .Get("/compress",
  3166. [&](const Request & /*req*/, Response &res) {
  3167. res.set_content(
  3168. "12345678901234567890123456789012345678901234567890123456789"
  3169. "01234567890123456789012345678901234567890",
  3170. "text/plain");
  3171. })
  3172. .Get("/nocompress",
  3173. [&](const Request & /*req*/, Response &res) {
  3174. res.set_content(
  3175. "12345678901234567890123456789012345678901234567890123456789"
  3176. "01234567890123456789012345678901234567890",
  3177. "application/octet-stream");
  3178. })
  3179. .Post("/compress-multipart",
  3180. [&](const Request &req, Response & /*res*/) {
  3181. EXPECT_EQ(2u, req.form.fields.size());
  3182. ASSERT_TRUE(!req.form.has_field("???"));
  3183. {
  3184. const auto &text = req.form.get_field("key1");
  3185. EXPECT_EQ("test", text);
  3186. }
  3187. {
  3188. const auto &text = req.form.get_field("key2");
  3189. EXPECT_EQ("--abcdefg123", text);
  3190. }
  3191. })
  3192. #endif
  3193. ;
  3194. persons_["john"] = "programmer";
  3195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3196. svr_.wait_until_ready();
  3197. }
  3198. virtual void TearDown() {
  3199. svr_.stop();
  3200. if (!request_threads_.empty()) {
  3201. std::this_thread::sleep_for(std::chrono::seconds(1));
  3202. for (auto &t : request_threads_) {
  3203. t.join();
  3204. }
  3205. }
  3206. t_.join();
  3207. }
  3208. map<string, string> persons_;
  3209. #ifdef CPPHTTPLIB_SSL_ENABLED
  3210. SSLClient cli_;
  3211. SSLServer svr_;
  3212. #else
  3213. Client cli_;
  3214. Server svr_;
  3215. #endif
  3216. thread t_;
  3217. std::vector<thread> request_threads_;
  3218. };
  3219. TEST_F(ServerTest, GetMethod200) {
  3220. auto res = cli_.Get("/hi");
  3221. ASSERT_TRUE(res);
  3222. EXPECT_EQ("HTTP/1.1", res->version);
  3223. EXPECT_EQ(StatusCode::OK_200, res->status);
  3224. EXPECT_EQ("OK", res->reason);
  3225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3226. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3227. EXPECT_EQ("Hello World!", res->body);
  3228. }
  3229. TEST_F(ServerTest, GetEmptyFile) {
  3230. auto res = cli_.Get("/empty_file");
  3231. ASSERT_TRUE(res);
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3234. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3235. EXPECT_EQ("", res->body);
  3236. }
  3237. TEST_F(ServerTest, GetFileContent) {
  3238. auto res = cli_.Get("/file_content");
  3239. ASSERT_TRUE(res);
  3240. EXPECT_EQ(StatusCode::OK_200, res->status);
  3241. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3242. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3243. EXPECT_EQ("test.html", res->body);
  3244. }
  3245. TEST_F(ServerTest, GetFileContentWithRange) {
  3246. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3249. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3250. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3251. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3252. EXPECT_EQ("est", res->body);
  3253. }
  3254. TEST_F(ServerTest, GetFileContentWithContentType) {
  3255. auto res = cli_.Get("/file_content_with_content_type");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::OK_200, res->status);
  3258. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3259. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3260. EXPECT_EQ("file\n", res->body);
  3261. }
  3262. TEST_F(ServerTest, GetInvalidFileContent) {
  3263. auto res = cli_.Get("/invalid_file_content");
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3266. }
  3267. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3268. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3269. ASSERT_TRUE(res);
  3270. EXPECT_EQ("HTTP/1.1", res->version);
  3271. EXPECT_EQ(StatusCode::OK_200, res->status);
  3272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3273. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3274. EXPECT_EQ("Hello World!", res->body);
  3275. }
  3276. TEST_F(ServerTest, GetMethod302) {
  3277. auto res = cli_.Get("/");
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::Found_302, res->status);
  3280. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3281. }
  3282. TEST_F(ServerTest, GetMethod302Redirect) {
  3283. cli_.set_follow_location(true);
  3284. auto res = cli_.Get("/");
  3285. ASSERT_TRUE(res);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("Hello World!", res->body);
  3288. EXPECT_EQ("/hi", res->location);
  3289. }
  3290. TEST_F(ServerTest, GetMethod404) {
  3291. auto res = cli_.Get("/invalid");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3294. }
  3295. TEST_F(ServerTest, HeadMethod200) {
  3296. auto res = cli_.Head("/hi");
  3297. ASSERT_TRUE(res);
  3298. EXPECT_EQ(StatusCode::OK_200, res->status);
  3299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3300. EXPECT_TRUE(res->body.empty());
  3301. }
  3302. TEST_F(ServerTest, HeadMethod200Static) {
  3303. auto res = cli_.Head("/mount/dir/index.html");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ(StatusCode::OK_200, res->status);
  3306. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3307. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3308. EXPECT_TRUE(res->body.empty());
  3309. }
  3310. TEST_F(ServerTest, HeadMethod404) {
  3311. auto res = cli_.Head("/invalid");
  3312. ASSERT_TRUE(res);
  3313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3314. EXPECT_TRUE(res->body.empty());
  3315. }
  3316. TEST_F(ServerTest, GetMethodPersonJohn) {
  3317. auto res = cli_.Get("/person/john");
  3318. ASSERT_TRUE(res);
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3321. EXPECT_EQ("programmer", res->body);
  3322. }
  3323. TEST_F(ServerTest, PostMethod1) {
  3324. auto res = cli_.Get("/person/john1");
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3327. res = cli_.Post("/person", "name=john1&note=coder",
  3328. "application/x-www-form-urlencoded");
  3329. ASSERT_TRUE(res);
  3330. ASSERT_EQ(StatusCode::OK_200, res->status);
  3331. res = cli_.Get("/person/john1");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3335. ASSERT_EQ("coder", res->body);
  3336. }
  3337. TEST_F(ServerTest, PostMethod2) {
  3338. auto res = cli_.Get("/person/john2");
  3339. ASSERT_TRUE(res);
  3340. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3341. Params params;
  3342. params.emplace("name", "john2");
  3343. params.emplace("note", "coder");
  3344. res = cli_.Post("/person", params);
  3345. ASSERT_TRUE(res);
  3346. ASSERT_EQ(StatusCode::OK_200, res->status);
  3347. res = cli_.Get("/person/john2");
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3351. ASSERT_EQ("coder", res->body);
  3352. }
  3353. TEST_F(ServerTest, PutMethod3) {
  3354. auto res = cli_.Get("/person/john3");
  3355. ASSERT_TRUE(res);
  3356. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3357. Params params;
  3358. params.emplace("name", "john3");
  3359. params.emplace("note", "coder");
  3360. res = cli_.Put("/person", params);
  3361. ASSERT_TRUE(res);
  3362. ASSERT_EQ(StatusCode::OK_200, res->status);
  3363. res = cli_.Get("/person/john3");
  3364. ASSERT_TRUE(res);
  3365. ASSERT_EQ(StatusCode::OK_200, res->status);
  3366. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3367. ASSERT_EQ("coder", res->body);
  3368. }
  3369. TEST_F(ServerTest, DeleteMethod1) {
  3370. auto res = cli_.Get("/person/john4");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3373. Params params;
  3374. params.emplace("name", "john4");
  3375. params.emplace("note", "coder");
  3376. res = cli_.Post("/person", params);
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::OK_200, res->status);
  3379. res = cli_.Get("/person/john4");
  3380. ASSERT_TRUE(res);
  3381. ASSERT_EQ(StatusCode::OK_200, res->status);
  3382. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3383. ASSERT_EQ("coder", res->body);
  3384. Params delete_params;
  3385. delete_params.emplace("name", "john4");
  3386. res = cli_.Delete("/person", delete_params);
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::OK_200, res->status);
  3389. ASSERT_EQ("DELETED", res->body);
  3390. res = cli_.Get("/person/john4");
  3391. ASSERT_TRUE(res);
  3392. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, DeleteMethod2) {
  3395. auto res = cli_.Get("/person/john5");
  3396. ASSERT_TRUE(res);
  3397. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3398. Params params;
  3399. params.emplace("name", "john5");
  3400. params.emplace("note", "developer");
  3401. res = cli_.Post("/person", params);
  3402. ASSERT_TRUE(res);
  3403. ASSERT_EQ(StatusCode::OK_200, res->status);
  3404. res = cli_.Get("/person/john5");
  3405. ASSERT_TRUE(res);
  3406. ASSERT_EQ(StatusCode::OK_200, res->status);
  3407. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3408. ASSERT_EQ("developer", res->body);
  3409. Params delete_params;
  3410. delete_params.emplace("name", "john5");
  3411. Headers headers;
  3412. headers.emplace("Custom-Header", "test-value");
  3413. res = cli_.Delete("/person", headers, delete_params);
  3414. ASSERT_TRUE(res);
  3415. ASSERT_EQ(StatusCode::OK_200, res->status);
  3416. ASSERT_EQ("DELETED", res->body);
  3417. res = cli_.Get("/person/john5");
  3418. ASSERT_TRUE(res);
  3419. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3420. }
  3421. TEST_F(ServerTest, DeleteMethod3) {
  3422. auto res = cli_.Get("/person/john6");
  3423. ASSERT_TRUE(res);
  3424. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3425. Params params;
  3426. params.emplace("name", "john6");
  3427. params.emplace("note", "tester");
  3428. res = cli_.Post("/person", params);
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. res = cli_.Get("/person/john6");
  3432. ASSERT_TRUE(res);
  3433. ASSERT_EQ(StatusCode::OK_200, res->status);
  3434. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3435. ASSERT_EQ("tester", res->body);
  3436. Params delete_params;
  3437. delete_params.emplace("name", "john6");
  3438. Headers headers;
  3439. headers.emplace("Custom-Header", "test-value");
  3440. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. ASSERT_EQ("DELETED", res->body);
  3444. res = cli_.Get("/person/john6");
  3445. ASSERT_TRUE(res);
  3446. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3447. }
  3448. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3449. Params params;
  3450. params.emplace("json", JSON_DATA);
  3451. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ(JSON_DATA, res->body);
  3455. }
  3456. TEST_F(ServerTest, PostEmptyContent) {
  3457. auto res = cli_.Post("/empty", "", "text/plain");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::OK_200, res->status);
  3460. ASSERT_EQ("empty", res->body);
  3461. }
  3462. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3463. auto res = cli_.Post("/empty-no-content-type");
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. ASSERT_EQ("empty-no-content-type", res->body);
  3467. }
  3468. TEST_F(ServerTest, PostPathOnly) {
  3469. auto res = cli_.Post("/path-only");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("path-only", res->body);
  3473. }
  3474. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3475. auto res = cli_.Post("/path-headers-only",
  3476. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::OK_200, res->status);
  3479. ASSERT_EQ("path-headers-only", res->body);
  3480. }
  3481. TEST_F(ServerTest, PostLarge) {
  3482. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3483. ASSERT_TRUE(res);
  3484. ASSERT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ(LARGE_DATA, res->body);
  3486. }
  3487. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3488. auto res = cli_.Put("/empty-no-content-type");
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. ASSERT_EQ("empty-no-content-type", res->body);
  3492. }
  3493. TEST_F(ServerTest, GetMethodDir) {
  3494. auto res = cli_.Get("/dir/");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3498. auto body = R"(<html>
  3499. <head>
  3500. </head>
  3501. <body>
  3502. <a href="/dir/test.html">Test</a>
  3503. <a href="/hi">hi</a>
  3504. </body>
  3505. </html>
  3506. )";
  3507. EXPECT_EQ(body, res->body);
  3508. }
  3509. TEST_F(ServerTest, GetMethodDirTest) {
  3510. auto res = cli_.Get("/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("test.html", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3517. auto res = cli_.Get("/dir/../dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("test.html", res->body);
  3522. }
  3523. TEST_F(ServerTest, GetMethodInvalidPath) {
  3524. auto res = cli_.Get("/dir/../test.html");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3527. }
  3528. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3529. auto res = cli_.Get("/../www/dir/test.html");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3532. }
  3533. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3534. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, GetMethodDirMountTest) {
  3539. auto res = cli_.Get("/mount/dir/test.html");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3543. EXPECT_EQ("test.html", res->body);
  3544. }
  3545. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3546. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::OK_200, res->status);
  3549. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3550. EXPECT_EQ("test.html", res->body);
  3551. }
  3552. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3553. auto res = cli_.Get("/mount/dir/../test.html");
  3554. ASSERT_TRUE(res);
  3555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3556. }
  3557. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3558. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3561. }
  3562. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3563. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3564. ASSERT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3566. }
  3567. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3568. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3569. ASSERT_TRUE(res);
  3570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3571. }
  3572. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3573. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3576. }
  3577. TEST_F(ServerTest, PostMethod303) {
  3578. auto res = cli_.Post("/1", "body", "text/plain");
  3579. ASSERT_TRUE(res);
  3580. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3581. EXPECT_EQ("/2", res->get_header_value("Location"));
  3582. }
  3583. TEST_F(ServerTest, PostMethod303Redirect) {
  3584. cli_.set_follow_location(true);
  3585. auto res = cli_.Post("/1", "body", "text/plain");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("redirected.", res->body);
  3589. EXPECT_EQ("/2", res->location);
  3590. }
  3591. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3592. auto res = cli_.Get("/dir/test.abcde");
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3596. EXPECT_EQ("abcde", res->body);
  3597. }
  3598. TEST_F(ServerTest, StaticFileRange) {
  3599. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3600. ASSERT_TRUE(res);
  3601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3602. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3603. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3604. EXPECT_EQ(true, res->has_header("Content-Range"));
  3605. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3606. EXPECT_EQ(std::string("cd"), res->body);
  3607. }
  3608. TEST_F(ServerTest, StaticFileRanges) {
  3609. auto res =
  3610. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3611. ASSERT_TRUE(res);
  3612. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3613. EXPECT_TRUE(
  3614. res->get_header_value("Content-Type")
  3615. .find(
  3616. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3617. 0);
  3618. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3619. }
  3620. TEST_F(ServerTest, StaticFileRangeHead) {
  3621. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3624. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3625. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3626. EXPECT_EQ(true, res->has_header("Content-Range"));
  3627. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3628. }
  3629. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3630. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3631. ASSERT_TRUE(res);
  3632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3634. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3635. EXPECT_EQ(true, res->has_header("Content-Range"));
  3636. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3637. res->get_header_value("Content-Range"));
  3638. EXPECT_EQ("LAST\n", res->body);
  3639. }
  3640. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3641. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3642. ASSERT_TRUE(res);
  3643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3645. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3646. EXPECT_EQ(true, res->has_header("Content-Range"));
  3647. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3648. }
  3649. TEST_F(ServerTest, StaticFileBigFile) {
  3650. auto res = cli_.Get("/dir/1MB.txt");
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::OK_200, res->status);
  3653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3654. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3655. }
  3656. TEST_F(ServerTest, InvalidBaseDirMount) {
  3657. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3658. }
  3659. TEST_F(ServerTest, Binary) {
  3660. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3661. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3662. "application/octet-stream");
  3663. ASSERT_TRUE(res);
  3664. ASSERT_EQ(StatusCode::OK_200, res->status);
  3665. ASSERT_EQ(4U, res->body.size());
  3666. res = cli_.Put("/binary", binary.data(), binary.size(),
  3667. "application/octet-stream");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ(4U, res->body.size());
  3671. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3672. "application/octet-stream");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. ASSERT_EQ(4U, res->body.size());
  3676. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3677. "application/octet-stream");
  3678. ASSERT_TRUE(res);
  3679. ASSERT_EQ(StatusCode::OK_200, res->status);
  3680. ASSERT_EQ(4U, res->body.size());
  3681. }
  3682. TEST_F(ServerTest, BinaryString) {
  3683. auto binary = std::string("\x00\x01\x02\x03", 4);
  3684. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3685. ASSERT_TRUE(res);
  3686. ASSERT_EQ(StatusCode::OK_200, res->status);
  3687. ASSERT_EQ(4U, res->body.size());
  3688. res = cli_.Put("/binary", binary, "application/octet-stream");
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. ASSERT_EQ(4U, res->body.size());
  3692. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3693. ASSERT_TRUE(res);
  3694. ASSERT_EQ(StatusCode::OK_200, res->status);
  3695. ASSERT_EQ(4U, res->body.size());
  3696. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3697. ASSERT_TRUE(res);
  3698. ASSERT_EQ(StatusCode::OK_200, res->status);
  3699. ASSERT_EQ(4U, res->body.size());
  3700. }
  3701. TEST_F(ServerTest, EmptyRequest) {
  3702. auto res = cli_.Get("");
  3703. ASSERT_TRUE(!res);
  3704. EXPECT_EQ(Error::Connection, res.error());
  3705. }
  3706. TEST_F(ServerTest, LongRequest) {
  3707. std::string request;
  3708. for (size_t i = 0; i < 545; i++) {
  3709. request += "/TooLongRequest";
  3710. }
  3711. request += "OK";
  3712. auto res = cli_.Get(request.c_str());
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3715. }
  3716. TEST_F(ServerTest, TooLongRequest) {
  3717. std::string request;
  3718. for (size_t i = 0; i < 546; i++) {
  3719. request += "/TooLongRequest";
  3720. }
  3721. request += "_NG";
  3722. auto start = std::chrono::high_resolution_clock::now();
  3723. cli_.set_keep_alive(true);
  3724. auto res = cli_.Get(request.c_str());
  3725. auto end = std::chrono::high_resolution_clock::now();
  3726. auto elapsed =
  3727. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3728. .count();
  3729. ASSERT_TRUE(res);
  3730. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3731. EXPECT_LE(elapsed, 100);
  3732. EXPECT_EQ("close", res->get_header_value("Connection"));
  3733. EXPECT_FALSE(cli_.is_socket_open());
  3734. }
  3735. TEST_F(ServerTest, AlmostTooLongRequest) {
  3736. // test for #2046 - URI length check shouldn't include other content on req
  3737. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3738. // leading /, space, HTTP/1.1)
  3739. std::string request =
  3740. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3741. auto res = cli_.Get(request.c_str());
  3742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3743. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3744. }
  3745. TEST_F(ServerTest, LongHeader) {
  3746. Request req;
  3747. req.method = "GET";
  3748. req.path = "/hi";
  3749. std::string host_and_port;
  3750. host_and_port += HOST;
  3751. host_and_port += ":";
  3752. host_and_port += std::to_string(PORT);
  3753. req.headers.emplace("Host", host_and_port.c_str());
  3754. req.headers.emplace("Accept", "*/*");
  3755. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3756. req.headers.emplace(
  3757. "Header-Name",
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@");
  3787. auto res = std::make_shared<Response>();
  3788. auto error = Error::Success;
  3789. auto ret = cli_.send(req, *res, error);
  3790. ASSERT_TRUE(ret);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. }
  3793. TEST_F(ServerTest, LongQueryValue) {
  3794. auto start = std::chrono::high_resolution_clock::now();
  3795. cli_.set_keep_alive(true);
  3796. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3797. auto end = std::chrono::high_resolution_clock::now();
  3798. auto elapsed =
  3799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3800. .count();
  3801. ASSERT_TRUE(res);
  3802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3803. EXPECT_LE(elapsed, 100);
  3804. EXPECT_EQ("close", res->get_header_value("Connection"));
  3805. EXPECT_FALSE(cli_.is_socket_open());
  3806. }
  3807. TEST_F(ServerTest, TooLongQueryValue) {
  3808. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3809. ASSERT_FALSE(res);
  3810. EXPECT_EQ(Error::Read, res.error());
  3811. }
  3812. TEST_F(ServerTest, TooLongHeader) {
  3813. Request req;
  3814. req.method = "GET";
  3815. req.path = "/hi";
  3816. std::string host_and_port;
  3817. host_and_port += HOST;
  3818. host_and_port += ":";
  3819. host_and_port += std::to_string(PORT);
  3820. req.headers.emplace("Host", host_and_port.c_str());
  3821. req.headers.emplace("Accept", "*/*");
  3822. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3823. req.headers.emplace(
  3824. "Header-Name",
  3825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3853. "@@@@@@@@@@@@@@@@@");
  3854. auto res = std::make_shared<Response>();
  3855. auto error = Error::Success;
  3856. auto ret = cli_.send(req, *res, error);
  3857. ASSERT_TRUE(ret);
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. TEST_F(ServerTest, HeaderCountAtLimit) {
  3861. // Test with headers just under the 100 limit
  3862. httplib::Headers headers;
  3863. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3864. // This should keep us just under the 100 header limit
  3865. for (int i = 0; i < 95; i++) {
  3866. std::string name = "X-Test-Header-" + std::to_string(i);
  3867. std::string value = "value" + std::to_string(i);
  3868. headers.emplace(name, value);
  3869. }
  3870. // This should work fine as we're under the limit
  3871. auto res = cli_.Get("/hi", headers);
  3872. EXPECT_TRUE(res);
  3873. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3874. }
  3875. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3876. // Test with many headers to exceed the 100 limit
  3877. httplib::Headers headers;
  3878. // Add 150 headers to definitely exceed the 100 limit
  3879. for (int i = 0; i < 150; i++) {
  3880. std::string name = "X-Test-Header-" + std::to_string(i);
  3881. std::string value = "value" + std::to_string(i);
  3882. headers.emplace(name, value);
  3883. }
  3884. // This should fail due to exceeding header count limit
  3885. cli_.set_keep_alive(true);
  3886. auto res = cli_.Get("/hi", headers);
  3887. // The request should either fail or return 400 Bad Request
  3888. if (res) {
  3889. // If we get a response, it should be 400 Bad Request
  3890. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3891. } else {
  3892. // Or the request should fail entirely
  3893. EXPECT_FALSE(res);
  3894. }
  3895. EXPECT_EQ("close", res->get_header_value("Connection"));
  3896. EXPECT_FALSE(cli_.is_socket_open());
  3897. }
  3898. TEST_F(ServerTest, PercentEncoding) {
  3899. auto res = cli_.Get("/e%6edwith%");
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::OK_200, res->status);
  3902. }
  3903. TEST_F(ServerTest, PercentEncodingUnicode) {
  3904. auto res = cli_.Get("/e%u006edwith%");
  3905. ASSERT_TRUE(res);
  3906. EXPECT_EQ(StatusCode::OK_200, res->status);
  3907. }
  3908. TEST_F(ServerTest, InvalidPercentEncoding) {
  3909. auto res = cli_.Get("/%endwith%");
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3912. }
  3913. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3914. auto res = cli_.Get("/%uendwith%");
  3915. ASSERT_TRUE(res);
  3916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3917. }
  3918. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3919. auto res = cli_.Get("/hello?aaa=bbb%");
  3920. ASSERT_TRUE(res);
  3921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3922. }
  3923. TEST_F(ServerTest, PlusSignEncoding) {
  3924. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3925. ASSERT_TRUE(res);
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. EXPECT_EQ("a +b", res->body);
  3928. }
  3929. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3930. // This test simulates a potential DoS attack using many headers
  3931. // to verify our security fix prevents memory exhaustion
  3932. httplib::Headers attack_headers;
  3933. // Attempt to add many headers like an attacker would (200 headers to far
  3934. // exceed limit)
  3935. for (int i = 0; i < 200; i++) {
  3936. std::string name = "X-Attack-Header-" + std::to_string(i);
  3937. std::string value = "attack_payload_" + std::to_string(i);
  3938. attack_headers.emplace(name, value);
  3939. }
  3940. // Try to POST with excessive headers
  3941. cli_.set_keep_alive(true);
  3942. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3943. // Should either fail or return 400 Bad Request due to security limit
  3944. if (res) {
  3945. // If we get a response, it should be 400 Bad Request
  3946. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3947. } else {
  3948. // Request failed, which is the expected behavior for DoS protection
  3949. EXPECT_FALSE(res);
  3950. }
  3951. EXPECT_EQ("close", res->get_header_value("Connection"));
  3952. EXPECT_FALSE(cli_.is_socket_open());
  3953. }
  3954. TEST_F(ServerTest, MultipartFormData) {
  3955. UploadFormDataItems items = {
  3956. {"text1", "text default", "", ""},
  3957. {"text2", "aωb", "", ""},
  3958. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3959. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3960. {"file3", "", "", "application/octet-stream"},
  3961. {"file4", "", "", " application/json tmp-string "}};
  3962. auto res = cli_.Post("/multipart", items);
  3963. ASSERT_TRUE(res);
  3964. EXPECT_EQ(StatusCode::OK_200, res->status);
  3965. }
  3966. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3967. UploadFormDataItems items = {
  3968. {"text", "default text", "", ""},
  3969. {"multi_text1", "aaaaa", "", ""},
  3970. {"multi_text1", "bbbbb", "", ""},
  3971. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3972. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3973. "application/json"},
  3974. };
  3975. auto res = cli_.Post("/multipart/multi_file_values", items);
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::OK_200, res->status);
  3978. }
  3979. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3980. auto res = cli_.Get("/hi");
  3981. ASSERT_TRUE(res);
  3982. EXPECT_EQ(StatusCode::OK_200, res->status);
  3983. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3984. EXPECT_EQ("Hello World!", res->body);
  3985. }
  3986. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3987. Request req;
  3988. req.method = "POST";
  3989. req.path = "/chunked";
  3990. std::string host_and_port;
  3991. host_and_port += HOST;
  3992. host_and_port += ":";
  3993. host_and_port += std::to_string(PORT);
  3994. req.headers.emplace("Host", host_and_port.c_str());
  3995. req.headers.emplace("Accept", "*/*");
  3996. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3997. req.headers.emplace("Content-Type", "text/plain");
  3998. req.headers.emplace("Content-Length", "0");
  3999. req.headers.emplace(
  4000. "Transfer-Encoding",
  4001. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4002. // Client does not chunk, so make a chunked body manually.
  4003. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4004. auto res = std::make_shared<Response>();
  4005. auto error = Error::Success;
  4006. auto ret = cli_.send(req, *res, error);
  4007. ASSERT_TRUE(ret);
  4008. EXPECT_EQ(StatusCode::OK_200, res->status);
  4009. }
  4010. TEST_F(ServerTest, GetStreamed2) {
  4011. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4012. ASSERT_TRUE(res);
  4013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4014. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4015. EXPECT_EQ(true, res->has_header("Content-Range"));
  4016. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4017. EXPECT_EQ(std::string("ab"), res->body);
  4018. }
  4019. TEST_F(ServerTest, GetStreamed) {
  4020. auto res = cli_.Get("/streamed");
  4021. ASSERT_TRUE(res);
  4022. EXPECT_EQ(StatusCode::OK_200, res->status);
  4023. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4024. EXPECT_EQ(std::string("aaabbb"), res->body);
  4025. }
  4026. TEST_F(ServerTest, GetStreamedWithRange1) {
  4027. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4030. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(true, res->has_header("Content-Range"));
  4032. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4033. EXPECT_EQ(std::string("def"), res->body);
  4034. }
  4035. TEST_F(ServerTest, GetStreamedWithRange2) {
  4036. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4039. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4040. EXPECT_EQ(true, res->has_header("Content-Range"));
  4041. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4042. EXPECT_EQ(std::string("bcdefg"), res->body);
  4043. }
  4044. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4045. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4046. ASSERT_TRUE(res);
  4047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4048. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4049. EXPECT_EQ(true, res->has_header("Content-Range"));
  4050. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4051. EXPECT_EQ(std::string("efg"), res->body);
  4052. }
  4053. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4054. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4055. ASSERT_TRUE(res);
  4056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4058. EXPECT_EQ(false, res->has_header("Content-Range"));
  4059. EXPECT_EQ(0U, res->body.size());
  4060. }
  4061. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4062. auto res = cli_.Get("/streamed-with-range",
  4063. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4064. "92233720368547758079223372036854775807"}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4067. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ(false, res->has_header("Content-Range"));
  4069. EXPECT_EQ(0U, res->body.size());
  4070. }
  4071. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4072. auto res = cli_.Get(
  4073. "/with-range",
  4074. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4075. {"Accept-Encoding", ""}});
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4079. EXPECT_EQ(true, res->has_header("Content-Range"));
  4080. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4081. EXPECT_EQ(std::string("abcdefg"), res->body);
  4082. }
  4083. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4084. auto res = cli_.Get("/with-range", {
  4085. {"Range", "bytes=0-"},
  4086. {"Accept-Encoding", ""},
  4087. });
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4090. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4091. EXPECT_EQ(true, res->has_header("Content-Range"));
  4092. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4093. EXPECT_EQ(std::string("abcdefg"), res->body);
  4094. }
  4095. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4096. auto res =
  4097. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4100. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4101. EXPECT_EQ(false, res->has_header("Content-Range"));
  4102. EXPECT_EQ(267U, res->body.size());
  4103. // Check that both range contents are present
  4104. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4105. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4106. // Check that Content-Range headers are present for both ranges
  4107. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4108. std::string::npos);
  4109. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4110. std::string::npos);
  4111. }
  4112. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4113. Ranges ranges;
  4114. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4115. ranges.emplace_back(0, -1);
  4116. }
  4117. auto res =
  4118. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4121. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4122. EXPECT_EQ(false, res->has_header("Content-Range"));
  4123. EXPECT_EQ(0U, res->body.size());
  4124. }
  4125. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4126. auto res =
  4127. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4130. EXPECT_EQ(5U, res->body.size());
  4131. // Check that overlapping ranges are coalesced into a single range
  4132. EXPECT_EQ("bcdef", res->body);
  4133. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4134. // Should be single range, not multipart
  4135. EXPECT_TRUE(res->has_header("Content-Range"));
  4136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4137. }
  4138. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4139. auto res =
  4140. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4143. EXPECT_EQ(268U, res->body.size());
  4144. // Check that both range contents are present
  4145. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4146. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4147. // Check that Content-Range headers are present for both ranges
  4148. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4149. std::string::npos);
  4150. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4151. std::string::npos);
  4152. }
  4153. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4154. auto res =
  4155. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4158. EXPECT_EQ(269U, res->body.size());
  4159. // Check that both duplicate range contents are present
  4160. size_t first_abc = res->body.find("abc\r\n");
  4161. EXPECT_TRUE(first_abc != std::string::npos);
  4162. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4163. EXPECT_TRUE(second_abc != std::string::npos);
  4164. // Check that Content-Range headers are present for both ranges
  4165. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4166. EXPECT_TRUE(first_range != std::string::npos);
  4167. size_t second_range =
  4168. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4169. EXPECT_TRUE(second_range != std::string::npos);
  4170. }
  4171. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4172. auto res = cli_.Get("/streamed-with-range?error",
  4173. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4176. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ(false, res->has_header("Content-Range"));
  4178. EXPECT_EQ(0U, res->body.size());
  4179. }
  4180. TEST_F(ServerTest, GetStreamedEndless) {
  4181. uint64_t offset = 0;
  4182. auto res = cli_.Get("/streamed-cancel",
  4183. [&](const char * /*data*/, uint64_t data_length) {
  4184. if (offset < 100) {
  4185. offset += data_length;
  4186. return true;
  4187. }
  4188. return false;
  4189. });
  4190. ASSERT_TRUE(!res);
  4191. EXPECT_EQ(Error::Canceled, res.error());
  4192. }
  4193. TEST_F(ServerTest, ClientStop) {
  4194. std::atomic_size_t count{4};
  4195. std::vector<std::thread> threads;
  4196. for (auto i = count.load(); i != 0; --i) {
  4197. threads.emplace_back([&]() {
  4198. auto res = cli_.Get("/streamed-cancel",
  4199. [&](const char *, uint64_t) { return true; });
  4200. --count;
  4201. ASSERT_TRUE(!res);
  4202. EXPECT_TRUE(res.error() == Error::Canceled ||
  4203. res.error() == Error::Read || res.error() == Error::Write);
  4204. });
  4205. }
  4206. std::this_thread::sleep_for(std::chrono::seconds(2));
  4207. while (count != 0) {
  4208. cli_.stop();
  4209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4210. }
  4211. for (auto &t : threads) {
  4212. t.join();
  4213. }
  4214. }
  4215. TEST_F(ServerTest, GetWithRange1) {
  4216. auto res = cli_.Get("/with-range", {
  4217. make_range_header({{3, 5}}),
  4218. {"Accept-Encoding", ""},
  4219. });
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4222. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4223. EXPECT_EQ(true, res->has_header("Content-Range"));
  4224. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4225. EXPECT_EQ(std::string("def"), res->body);
  4226. }
  4227. TEST_F(ServerTest, GetWithRange2) {
  4228. auto res = cli_.Get("/with-range", {
  4229. make_range_header({{1, -1}}),
  4230. {"Accept-Encoding", ""},
  4231. });
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("bcdefg"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetWithRange3) {
  4240. auto res = cli_.Get("/with-range", {
  4241. make_range_header({{0, 0}}),
  4242. {"Accept-Encoding", ""},
  4243. });
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4246. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4247. EXPECT_EQ(true, res->has_header("Content-Range"));
  4248. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4249. EXPECT_EQ(std::string("a"), res->body);
  4250. }
  4251. TEST_F(ServerTest, GetWithRange4) {
  4252. auto res = cli_.Get("/with-range", {
  4253. make_range_header({{-1, 2}}),
  4254. {"Accept-Encoding", ""},
  4255. });
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4258. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4259. EXPECT_EQ(true, res->has_header("Content-Range"));
  4260. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4261. EXPECT_EQ(std::string("fg"), res->body);
  4262. }
  4263. TEST_F(ServerTest, GetWithRange5) {
  4264. auto res = cli_.Get("/with-range", {
  4265. make_range_header({{0, 5}}),
  4266. {"Accept-Encoding", ""},
  4267. });
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4270. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4271. EXPECT_EQ(true, res->has_header("Content-Range"));
  4272. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4273. EXPECT_EQ(std::string("abcdef"), res->body);
  4274. }
  4275. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4276. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4279. }
  4280. TEST_F(ServerTest, GetWithRangeMultipart) {
  4281. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4284. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4285. EXPECT_EQ(false, res->has_header("Content-Range"));
  4286. EXPECT_EQ(267U, res->body.size());
  4287. }
  4288. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4289. auto res =
  4290. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4293. }
  4294. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4295. auto res = cli_.Get("/with-range-customized-response",
  4296. {{make_range_header({{1, 2}})}});
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4299. EXPECT_EQ(true, res->has_header("Content-Length"));
  4300. EXPECT_EQ(false, res->has_header("Content-Range"));
  4301. EXPECT_EQ(JSON_DATA, res->body);
  4302. }
  4303. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4304. auto res = cli_.Get("/with-range-customized-response",
  4305. {{make_range_header({{1, 2}, {4, 5}})}});
  4306. ASSERT_TRUE(res);
  4307. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4308. EXPECT_EQ(true, res->has_header("Content-Length"));
  4309. EXPECT_EQ(false, res->has_header("Content-Range"));
  4310. EXPECT_EQ(JSON_DATA, res->body);
  4311. }
  4312. TEST_F(ServerTest, Issue1772) {
  4313. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4314. ASSERT_TRUE(res);
  4315. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4316. }
  4317. TEST_F(ServerTest, Issue609) {
  4318. auto res = cli_.Delete("/issue609");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ(std::string("ok"), res->body);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedChunked) {
  4324. auto res = cli_.Get("/streamed-chunked");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ(std::string("123456789"), res->body);
  4328. }
  4329. TEST_F(ServerTest, GetStreamedChunked2) {
  4330. auto res = cli_.Get("/streamed-chunked2");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. EXPECT_EQ(std::string("123456789"), res->body);
  4334. }
  4335. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4336. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::OK_200, res->status);
  4339. EXPECT_EQ(std::string("123456789"), res->body);
  4340. EXPECT_TRUE(res->has_header("Trailer"));
  4341. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4342. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4343. // Trailers are now stored separately from headers (security fix)
  4344. EXPECT_EQ(2U, res->trailers.size());
  4345. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4346. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4347. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4348. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4349. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4350. // Verify trailers are NOT in headers (security verification)
  4351. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4352. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4353. }
  4354. TEST_F(ServerTest, LargeChunkedPost) {
  4355. Request req;
  4356. req.method = "POST";
  4357. req.path = "/large-chunked";
  4358. std::string host_and_port;
  4359. host_and_port += HOST;
  4360. host_and_port += ":";
  4361. host_and_port += std::to_string(PORT);
  4362. req.headers.emplace("Host", host_and_port.c_str());
  4363. req.headers.emplace("Accept", "*/*");
  4364. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4365. req.headers.emplace("Content-Type", "text/plain");
  4366. req.headers.emplace("Content-Length", "0");
  4367. req.headers.emplace("Transfer-Encoding", "chunked");
  4368. std::string long_string(30 * 1024u, 'a');
  4369. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4370. // Attempt to make a large enough post to exceed OS buffers, to test that
  4371. // the server handles short reads if the full chunk data isn't available.
  4372. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4373. auto res = std::make_shared<Response>();
  4374. auto error = Error::Success;
  4375. auto ret = cli_.send(req, *res, error);
  4376. ASSERT_TRUE(ret);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. }
  4379. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4380. auto res = cli_.Get("/remote_addr");
  4381. ASSERT_TRUE(res);
  4382. EXPECT_EQ(StatusCode::OK_200, res->status);
  4383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4384. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4385. }
  4386. TEST_F(ServerTest, GetMethodLocalAddr) {
  4387. auto res = cli_.Get("/local_addr");
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4391. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4392. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4393. }
  4394. TEST_F(ServerTest, HTTPResponseSplitting) {
  4395. auto res = cli_.Get("/http_response_splitting");
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::OK_200, res->status);
  4398. }
  4399. TEST_F(ServerTest, SlowRequest) {
  4400. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4401. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4402. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4403. }
  4404. #if 0
  4405. TEST_F(ServerTest, SlowPost) {
  4406. char buffer[64 * 1024];
  4407. memset(buffer, 0x42, sizeof(buffer));
  4408. auto res = cli_.Post(
  4409. "/slowpost", 64 * 1024 * 1024,
  4410. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4411. auto ret = sink.write(buffer, sizeof(buffer));
  4412. EXPECT_TRUE(ret);
  4413. return true;
  4414. },
  4415. "text/plain");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. }
  4419. TEST_F(ServerTest, SlowPostFail) {
  4420. char buffer[64 * 1024];
  4421. memset(buffer, 0x42, sizeof(buffer));
  4422. cli_.set_write_timeout(std::chrono::seconds(0));
  4423. auto res = cli_.Post(
  4424. "/slowpost", 64 * 1024 * 1024,
  4425. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4426. sink.write(buffer, sizeof(buffer));
  4427. return true;
  4428. },
  4429. "text/plain");
  4430. ASSERT_TRUE(!res);
  4431. EXPECT_EQ(Error::Write, res.error());
  4432. }
  4433. #endif
  4434. TEST_F(ServerTest, Put) {
  4435. auto res = cli_.Put("/put", "PUT", "text/plain");
  4436. ASSERT_TRUE(res);
  4437. EXPECT_EQ(StatusCode::OK_200, res->status);
  4438. EXPECT_EQ("PUT", res->body);
  4439. }
  4440. TEST_F(ServerTest, PutWithContentProvider) {
  4441. auto res = cli_.Put(
  4442. "/put", 3,
  4443. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4444. sink.os << "PUT";
  4445. return true;
  4446. },
  4447. "text/plain");
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::OK_200, res->status);
  4450. EXPECT_EQ("PUT", res->body);
  4451. }
  4452. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4453. auto res = cli_.Post(
  4454. "/post", 42,
  4455. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4456. return false;
  4457. },
  4458. "text/plain");
  4459. ASSERT_TRUE(!res);
  4460. EXPECT_EQ(Error::Canceled, res.error());
  4461. }
  4462. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4463. auto res = cli_.Put(
  4464. "/put",
  4465. [](size_t /*offset*/, DataSink &sink) {
  4466. sink.os << "PUT";
  4467. sink.done();
  4468. return true;
  4469. },
  4470. "text/plain");
  4471. ASSERT_TRUE(res);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("PUT", res->body);
  4474. }
  4475. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4476. auto res = cli_.Post(
  4477. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4478. "text/plain");
  4479. ASSERT_TRUE(!res);
  4480. EXPECT_EQ(Error::Canceled, res.error());
  4481. }
  4482. TEST_F(ServerTest, PostLoopBack) {
  4483. std::string body;
  4484. auto res = cli_.Post(
  4485. "/post-loopback", 9,
  4486. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4487. EXPECT_EQ(9u, length);
  4488. sink.write("123", 3);
  4489. sink.write("456", 3);
  4490. sink.write("789", 3);
  4491. return true;
  4492. },
  4493. "text/plain",
  4494. [&body](const char *data, size_t data_length) {
  4495. body.append(data, data_length);
  4496. return true;
  4497. });
  4498. ASSERT_TRUE(res);
  4499. EXPECT_EQ(StatusCode::OK_200, res->status);
  4500. EXPECT_EQ("123456789", body);
  4501. }
  4502. TEST_F(ServerTest, PutLoopBack) {
  4503. std::string body;
  4504. auto res = cli_.Put(
  4505. "/put-loopback", 9,
  4506. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4507. EXPECT_EQ(9u, length);
  4508. sink.write("123", 3);
  4509. sink.write("456", 3);
  4510. sink.write("789", 3);
  4511. return true;
  4512. },
  4513. "text/plain",
  4514. [&body](const char *data, size_t data_length) {
  4515. body.append(data, data_length);
  4516. return true;
  4517. });
  4518. ASSERT_TRUE(res);
  4519. EXPECT_EQ(StatusCode::OK_200, res->status);
  4520. EXPECT_EQ("123456789", body);
  4521. }
  4522. TEST_F(ServerTest, PatchLoopBack) {
  4523. std::string body;
  4524. auto res = cli_.Patch(
  4525. "/patch-loopback", 9,
  4526. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4527. EXPECT_EQ(9u, length);
  4528. sink.write("123", 3);
  4529. sink.write("456", 3);
  4530. sink.write("789", 3);
  4531. return true;
  4532. },
  4533. "text/plain",
  4534. [&body](const char *data, size_t data_length) {
  4535. body.append(data, data_length);
  4536. return true;
  4537. });
  4538. ASSERT_TRUE(res);
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. EXPECT_EQ("123456789", body);
  4541. }
  4542. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4543. std::string body;
  4544. auto res = cli_.Post(
  4545. "/post-loopback",
  4546. [](size_t /*offset*/, DataSink &sink) {
  4547. sink.write("123", 3);
  4548. sink.write("456", 3);
  4549. sink.write("789", 3);
  4550. sink.done();
  4551. return true;
  4552. },
  4553. "text/plain",
  4554. [&body](const char *data, size_t data_length) {
  4555. body.append(data, data_length);
  4556. return true;
  4557. });
  4558. ASSERT_TRUE(res);
  4559. EXPECT_EQ(StatusCode::OK_200, res->status);
  4560. EXPECT_EQ("123456789", body);
  4561. }
  4562. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4563. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4564. cli_.set_compress(true);
  4565. auto res = cli_.Put(
  4566. "/put", 3,
  4567. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4568. sink.os << "PUT";
  4569. return true;
  4570. },
  4571. "text/plain");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("PUT", res->body);
  4575. }
  4576. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4577. cli_.set_compress(true);
  4578. auto res = cli_.Post(
  4579. "/post", 42,
  4580. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4581. return false;
  4582. },
  4583. "text/plain");
  4584. ASSERT_TRUE(!res);
  4585. EXPECT_EQ(Error::Canceled, res.error());
  4586. }
  4587. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4588. cli_.set_compress(true);
  4589. auto res = cli_.Put(
  4590. "/put",
  4591. [](size_t /*offset*/, DataSink &sink) {
  4592. sink.os << "PUT";
  4593. sink.done();
  4594. return true;
  4595. },
  4596. "text/plain");
  4597. ASSERT_TRUE(res);
  4598. EXPECT_EQ(StatusCode::OK_200, res->status);
  4599. EXPECT_EQ("PUT", res->body);
  4600. }
  4601. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4602. cli_.set_compress(true);
  4603. auto res = cli_.Post(
  4604. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4605. "text/plain");
  4606. ASSERT_TRUE(!res);
  4607. EXPECT_EQ(Error::Canceled, res.error());
  4608. }
  4609. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4610. cli_.set_compress(true);
  4611. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ(LARGE_DATA, res->body);
  4615. }
  4616. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4617. #ifdef CPPHTTPLIB_SSL_ENABLED
  4618. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4619. Client cli(s.c_str());
  4620. cli.enable_server_certificate_verification(false);
  4621. #else
  4622. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4623. Client cli(s.c_str());
  4624. #endif
  4625. cli.set_compress(true);
  4626. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. EXPECT_EQ(LARGE_DATA, res->body);
  4630. // The compressed size should be less than a 10th of the original. May vary
  4631. // depending on the zlib library.
  4632. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4633. static_cast<uint64_t>(10 * 1024 * 1024));
  4634. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4635. }
  4636. TEST_F(ServerTest, PutContentWithDeflate) {
  4637. cli_.set_compress(false);
  4638. Headers headers;
  4639. headers.emplace("Content-Encoding", "deflate");
  4640. // PUT in deflate format:
  4641. auto res = cli_.Put("/put", headers,
  4642. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4643. ASSERT_TRUE(res);
  4644. EXPECT_EQ(StatusCode::OK_200, res->status);
  4645. EXPECT_EQ("PUT", res->body);
  4646. }
  4647. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4648. Headers headers;
  4649. headers.emplace("Accept-Encoding", "gzip, deflate");
  4650. auto res = cli_.Get("/streamed-chunked", headers);
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. EXPECT_EQ(std::string("123456789"), res->body);
  4654. }
  4655. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4656. Headers headers;
  4657. headers.emplace("Accept-Encoding", "gzip, deflate");
  4658. auto res = cli_.Get("/streamed-chunked2", headers);
  4659. ASSERT_TRUE(res);
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ(std::string("123456789"), res->body);
  4662. }
  4663. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4664. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4665. ASSERT_TRUE(res);
  4666. EXPECT_EQ(StatusCode::OK_200, res->status);
  4667. }
  4668. TEST(GzipDecompressor, ChunkedDecompression) {
  4669. std::string data;
  4670. for (size_t i = 0; i < 32 * 1024; ++i) {
  4671. data.push_back(static_cast<char>('a' + i % 26));
  4672. }
  4673. std::string compressed_data;
  4674. {
  4675. httplib::detail::gzip_compressor compressor;
  4676. bool result = compressor.compress(
  4677. data.data(), data.size(),
  4678. /*last=*/true,
  4679. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4680. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4681. compressed_data_size);
  4682. return true;
  4683. });
  4684. ASSERT_TRUE(result);
  4685. }
  4686. std::string decompressed_data;
  4687. {
  4688. httplib::detail::gzip_decompressor decompressor;
  4689. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4690. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4691. size_t chunk_size = 130;
  4692. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4693. chunk_begin += chunk_size) {
  4694. size_t current_chunk_size =
  4695. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4696. bool result = decompressor.decompress(
  4697. compressed_data.data() + chunk_begin, current_chunk_size,
  4698. [&](const char *decompressed_data_chunk,
  4699. size_t decompressed_data_chunk_size) {
  4700. decompressed_data.insert(decompressed_data.size(),
  4701. decompressed_data_chunk,
  4702. decompressed_data_chunk_size);
  4703. return true;
  4704. });
  4705. ASSERT_TRUE(result);
  4706. }
  4707. }
  4708. ASSERT_EQ(data, decompressed_data);
  4709. }
  4710. TEST(GzipDecompressor, DeflateDecompression) {
  4711. std::string original_text = "Raw deflate without gzip";
  4712. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4713. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4714. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4715. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4716. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4717. std::string decompressed_data;
  4718. {
  4719. httplib::detail::gzip_decompressor decompressor;
  4720. bool result = decompressor.decompress(
  4721. compressed_data.data(), compressed_data.size(),
  4722. [&](const char *decompressed_data_chunk,
  4723. size_t decompressed_data_chunk_size) {
  4724. decompressed_data.insert(decompressed_data.size(),
  4725. decompressed_data_chunk,
  4726. decompressed_data_chunk_size);
  4727. return true;
  4728. });
  4729. ASSERT_TRUE(result);
  4730. }
  4731. ASSERT_EQ(original_text, decompressed_data);
  4732. }
  4733. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4734. std::string original_text = "Raw deflate without gzip";
  4735. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4736. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4737. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4738. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4739. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4740. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4741. std::string decompressed_data;
  4742. {
  4743. httplib::detail::gzip_decompressor decompressor;
  4744. bool result = decompressor.decompress(
  4745. compressed_data.data(), compressed_data.size(),
  4746. [&](const char *decompressed_data_chunk,
  4747. size_t decompressed_data_chunk_size) {
  4748. decompressed_data.insert(decompressed_data.size(),
  4749. decompressed_data_chunk,
  4750. decompressed_data_chunk_size);
  4751. return true;
  4752. });
  4753. ASSERT_TRUE(result);
  4754. }
  4755. ASSERT_EQ(original_text, decompressed_data);
  4756. }
  4757. #ifdef _WIN32
  4758. TEST(GzipDecompressor, LargeRandomData) {
  4759. // prepare large random data that is difficult to be compressed and is
  4760. // expected to have large size even when compressed
  4761. std::random_device seed_gen;
  4762. std::mt19937 random(seed_gen());
  4763. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4764. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4765. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4766. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4767. // compress data over 4GiB
  4768. std::string compressed_data;
  4769. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4770. httplib::detail::gzip_compressor compressor;
  4771. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4772. data.size() * sizeof(std::uint32_t), true,
  4773. [&](const char *data, size_t size) {
  4774. compressed_data.insert(
  4775. compressed_data.size(), data, size);
  4776. return true;
  4777. });
  4778. ASSERT_TRUE(result);
  4779. // FIXME: compressed data size is expected to be greater than 4GiB,
  4780. // but there is no guarantee
  4781. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4782. // decompress data over 4GiB
  4783. std::string decompressed_data;
  4784. decompressed_data.reserve(data_size);
  4785. httplib::detail::gzip_decompressor decompressor;
  4786. result = decompressor.decompress(
  4787. compressed_data.data(), compressed_data.size(),
  4788. [&](const char *data, size_t size) {
  4789. decompressed_data.insert(decompressed_data.size(), data, size);
  4790. return true;
  4791. });
  4792. ASSERT_TRUE(result);
  4793. // compare
  4794. ASSERT_EQ(data_size, decompressed_data.size());
  4795. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4796. 0);
  4797. }
  4798. #endif
  4799. #endif
  4800. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4801. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4802. Headers headers;
  4803. headers.emplace("Accept-Encoding", "br");
  4804. auto res = cli_.Get("/streamed-chunked", headers);
  4805. ASSERT_TRUE(res);
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ(std::string("123456789"), res->body);
  4808. }
  4809. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4810. Headers headers;
  4811. headers.emplace("Accept-Encoding", "br");
  4812. auto res = cli_.Get("/streamed-chunked2", headers);
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ(std::string("123456789"), res->body);
  4816. }
  4817. #endif
  4818. TEST_F(ServerTest, Patch) {
  4819. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("PATCH", res->body);
  4823. }
  4824. TEST_F(ServerTest, Delete) {
  4825. auto res = cli_.Delete("/delete");
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. EXPECT_EQ("DELETE", res->body);
  4829. }
  4830. TEST_F(ServerTest, DeleteContentReceiver) {
  4831. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::OK_200, res->status);
  4834. EXPECT_EQ("content", res->body);
  4835. }
  4836. TEST_F(ServerTest, Options) {
  4837. auto res = cli_.Options("*");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4841. EXPECT_TRUE(res->body.empty());
  4842. }
  4843. TEST_F(ServerTest, URL) {
  4844. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. }
  4848. TEST_F(ServerTest, ArrayParam) {
  4849. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::OK_200, res->status);
  4852. }
  4853. TEST_F(ServerTest, NoMultipleHeaders) {
  4854. Headers headers = {{"Content-Length", "5"}};
  4855. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4856. "text/plain");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. }
  4860. TEST_F(ServerTest, PostContentReceiver) {
  4861. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4862. ASSERT_TRUE(res);
  4863. ASSERT_EQ(StatusCode::OK_200, res->status);
  4864. ASSERT_EQ("content", res->body);
  4865. }
  4866. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4867. UploadFormDataItems items = {
  4868. {"text1", "text default", "", ""},
  4869. {"text2", "aωb", "", ""},
  4870. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4871. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4872. {"file3", "", "", "application/octet-stream"},
  4873. };
  4874. auto res = cli_.Post("/content_receiver", items);
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4879. UploadFormDataItems items = {
  4880. {"text1", "text default", "", ""},
  4881. {"text2", "aωb", "", ""},
  4882. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4883. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4884. {"file3", "", "", "application/octet-stream"},
  4885. };
  4886. auto boundary = std::string("+++++");
  4887. std::string body;
  4888. for (const auto &item : items) {
  4889. body += "--" + boundary + "\r\n";
  4890. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4891. if (!item.filename.empty()) {
  4892. body += "; filename=\"" + item.filename + "\"";
  4893. }
  4894. body += "\r\n";
  4895. if (!item.content_type.empty()) {
  4896. body += "Content-Type: " + item.content_type + "\r\n";
  4897. }
  4898. body += "\r\n";
  4899. body += item.content + "\r\n";
  4900. }
  4901. body += "--" + boundary + "--\r\n";
  4902. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4903. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4904. ASSERT_TRUE(res);
  4905. EXPECT_EQ(StatusCode::OK_200, res->status);
  4906. }
  4907. TEST_F(ServerTest, PostContentReceiverGzip) {
  4908. cli_.set_compress(true);
  4909. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4910. ASSERT_TRUE(res);
  4911. ASSERT_EQ(StatusCode::OK_200, res->status);
  4912. ASSERT_EQ("content", res->body);
  4913. }
  4914. TEST_F(ServerTest, PutContentReceiver) {
  4915. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4916. ASSERT_TRUE(res);
  4917. ASSERT_EQ(StatusCode::OK_200, res->status);
  4918. ASSERT_EQ("content", res->body);
  4919. }
  4920. TEST_F(ServerTest, PatchContentReceiver) {
  4921. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4922. ASSERT_TRUE(res);
  4923. ASSERT_EQ(StatusCode::OK_200, res->status);
  4924. ASSERT_EQ("content", res->body);
  4925. }
  4926. template <typename ClientType>
  4927. void TestWithHeadersAndContentReceiver(
  4928. ClientType &cli,
  4929. std::function<Result(ClientType &, const std::string &, const Headers &,
  4930. const std::string &, const std::string &,
  4931. ContentReceiver, DownloadProgress)>
  4932. request_func) {
  4933. Headers headers;
  4934. headers.emplace("X-Custom-Header", "test-value");
  4935. std::string received_body;
  4936. auto res = request_func(
  4937. cli, "/content_receiver", headers, "content", "application/json",
  4938. [&](const char *data, size_t data_length) {
  4939. received_body.append(data, data_length);
  4940. return true;
  4941. },
  4942. nullptr);
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. EXPECT_EQ("content", received_body);
  4946. }
  4947. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4948. #ifdef CPPHTTPLIB_SSL_ENABLED
  4949. using ClientT = SSLClient;
  4950. #else
  4951. using ClientT = Client;
  4952. #endif
  4953. TestWithHeadersAndContentReceiver<ClientT>(
  4954. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4955. const std::string &body, const std::string &content_type,
  4956. ContentReceiver receiver, DownloadProgress progress) {
  4957. return cli.Post(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4961. #ifdef CPPHTTPLIB_SSL_ENABLED
  4962. using ClientT = SSLClient;
  4963. #else
  4964. using ClientT = Client;
  4965. #endif
  4966. TestWithHeadersAndContentReceiver<ClientT>(
  4967. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4968. const std::string &body, const std::string &content_type,
  4969. ContentReceiver receiver, DownloadProgress progress) {
  4970. return cli.Put(path, headers, body, content_type, receiver, progress);
  4971. });
  4972. }
  4973. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4974. #ifdef CPPHTTPLIB_SSL_ENABLED
  4975. using ClientT = SSLClient;
  4976. #else
  4977. using ClientT = Client;
  4978. #endif
  4979. TestWithHeadersAndContentReceiver<ClientT>(
  4980. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4981. const std::string &body, const std::string &content_type,
  4982. ContentReceiver receiver, DownloadProgress progress) {
  4983. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4984. });
  4985. }
  4986. template <typename ClientType>
  4987. void TestWithHeadersAndContentReceiverWithProgress(
  4988. ClientType &cli,
  4989. std::function<Result(ClientType &, const std::string &, const Headers &,
  4990. const std::string &, const std::string &,
  4991. ContentReceiver, DownloadProgress)>
  4992. request_func) {
  4993. Headers headers;
  4994. headers.emplace("X-Test-Header", "progress-test");
  4995. std::string received_body;
  4996. auto progress_called = false;
  4997. auto res = request_func(
  4998. cli, "/content_receiver", headers, "content", "text/plain",
  4999. [&](const char *data, size_t data_length) {
  5000. received_body.append(data, data_length);
  5001. return true;
  5002. },
  5003. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5004. progress_called = true;
  5005. return true;
  5006. });
  5007. ASSERT_TRUE(res);
  5008. EXPECT_EQ(StatusCode::OK_200, res->status);
  5009. EXPECT_EQ("content", received_body);
  5010. EXPECT_TRUE(progress_called);
  5011. }
  5012. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5013. #ifdef CPPHTTPLIB_SSL_ENABLED
  5014. using ClientT = SSLClient;
  5015. #else
  5016. using ClientT = Client;
  5017. #endif
  5018. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5019. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5020. const std::string &body, const std::string &content_type,
  5021. ContentReceiver receiver, DownloadProgress progress) {
  5022. return cli.Post(path, headers, body, content_type, receiver, progress);
  5023. });
  5024. }
  5025. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5026. #ifdef CPPHTTPLIB_SSL_ENABLED
  5027. using ClientT = SSLClient;
  5028. #else
  5029. using ClientT = Client;
  5030. #endif
  5031. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5032. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5033. const std::string &body, const std::string &content_type,
  5034. ContentReceiver receiver, DownloadProgress progress) {
  5035. return cli.Put(path, headers, body, content_type, receiver, progress);
  5036. });
  5037. }
  5038. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5039. #ifdef CPPHTTPLIB_SSL_ENABLED
  5040. using ClientT = SSLClient;
  5041. #else
  5042. using ClientT = Client;
  5043. #endif
  5044. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5045. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5046. const std::string &body, const std::string &content_type,
  5047. ContentReceiver receiver, DownloadProgress progress) {
  5048. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5049. });
  5050. }
  5051. template <typename ClientType>
  5052. void TestWithHeadersAndContentReceiverError(
  5053. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5054. const Headers &, const std::string &,
  5055. const std::string &, ContentReceiver)>
  5056. request_func) {
  5057. Headers headers;
  5058. headers.emplace("X-Error-Test", "true");
  5059. std::string received_body;
  5060. auto receiver_failed = false;
  5061. auto res =
  5062. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5063. [&](const char *data, size_t data_length) {
  5064. received_body.append(data, data_length);
  5065. receiver_failed = true;
  5066. return false;
  5067. });
  5068. ASSERT_FALSE(res);
  5069. EXPECT_TRUE(receiver_failed);
  5070. }
  5071. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5072. #ifdef CPPHTTPLIB_SSL_ENABLED
  5073. using ClientT = SSLClient;
  5074. #else
  5075. using ClientT = Client;
  5076. #endif
  5077. TestWithHeadersAndContentReceiverError<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) {
  5081. return cli.Post(path, headers, body, content_type, receiver);
  5082. });
  5083. }
  5084. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5085. #ifdef CPPHTTPLIB_SSL_ENABLED
  5086. using ClientT = SSLClient;
  5087. #else
  5088. using ClientT = Client;
  5089. #endif
  5090. TestWithHeadersAndContentReceiverError<ClientT>(
  5091. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5092. const std::string &body, const std::string &content_type,
  5093. ContentReceiver receiver) {
  5094. return cli.Put(path, headers, body, content_type, receiver);
  5095. });
  5096. }
  5097. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5098. #ifdef CPPHTTPLIB_SSL_ENABLED
  5099. using ClientT = SSLClient;
  5100. #else
  5101. using ClientT = Client;
  5102. #endif
  5103. TestWithHeadersAndContentReceiverError<ClientT>(
  5104. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5105. const std::string &body, const std::string &content_type,
  5106. ContentReceiver receiver) {
  5107. return cli.Patch(path, headers, body, content_type, receiver);
  5108. });
  5109. }
  5110. TEST_F(ServerTest, PostQueryStringAndBody) {
  5111. auto res =
  5112. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5113. ASSERT_TRUE(res);
  5114. ASSERT_EQ(StatusCode::OK_200, res->status);
  5115. }
  5116. TEST_F(ServerTest, HTTP2Magic) {
  5117. Request req;
  5118. req.method = "PRI";
  5119. req.path = "*";
  5120. req.body = "SM";
  5121. auto res = std::make_shared<Response>();
  5122. auto error = Error::Success;
  5123. auto ret = cli_.send(req, *res, error);
  5124. ASSERT_TRUE(ret);
  5125. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5126. }
  5127. TEST_F(ServerTest, KeepAlive) {
  5128. auto res = cli_.Get("/hi");
  5129. ASSERT_TRUE(res);
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ("Hello World!", res->body);
  5133. res = cli_.Get("/hi");
  5134. ASSERT_TRUE(res);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5137. EXPECT_EQ("Hello World!", res->body);
  5138. res = cli_.Get("/hi");
  5139. ASSERT_TRUE(res);
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5142. EXPECT_EQ("Hello World!", res->body);
  5143. res = cli_.Get("/not-exist");
  5144. ASSERT_TRUE(res);
  5145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5146. res = cli_.Post("/empty", "", "text/plain");
  5147. ASSERT_TRUE(res);
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5150. EXPECT_EQ("empty", res->body);
  5151. EXPECT_EQ("close", res->get_header_value("Connection"));
  5152. res = cli_.Post(
  5153. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5154. "text/plain");
  5155. ASSERT_TRUE(res);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5158. EXPECT_EQ("empty", res->body);
  5159. cli_.set_keep_alive(false);
  5160. res = cli_.Get("/last-request");
  5161. ASSERT_TRUE(res);
  5162. EXPECT_EQ(StatusCode::OK_200, res->status);
  5163. EXPECT_EQ("close", res->get_header_value("Connection"));
  5164. }
  5165. TEST_F(ServerTest, TooManyRedirect) {
  5166. cli_.set_follow_location(true);
  5167. auto res = cli_.Get("/redirect/0");
  5168. ASSERT_TRUE(!res);
  5169. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5170. }
  5171. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5172. Request req;
  5173. req.method = "FOOBAR";
  5174. req.path = "/hi";
  5175. cli_.set_keep_alive(true);
  5176. auto res = cli_.send(req);
  5177. ASSERT_TRUE(res);
  5178. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5179. EXPECT_EQ("close", res->get_header_value("Connection"));
  5180. EXPECT_FALSE(cli_.is_socket_open());
  5181. }
  5182. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5184. TEST_F(ServerTest, Gzip) {
  5185. Headers headers;
  5186. headers.emplace("Accept-Encoding", "gzip, deflate");
  5187. auto res = cli_.Get("/compress", headers);
  5188. ASSERT_TRUE(res);
  5189. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5193. "7890123456789012345678901234567890",
  5194. res->body);
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. }
  5197. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5198. Headers headers;
  5199. headers.emplace("Accept-Encoding", "");
  5200. auto res = cli_.Get("/compress", headers);
  5201. ASSERT_TRUE(res);
  5202. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5206. "7890123456789012345678901234567890",
  5207. res->body);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. }
  5210. TEST_F(ServerTest, GzipWithContentReceiver) {
  5211. Headers headers;
  5212. headers.emplace("Accept-Encoding", "gzip, deflate");
  5213. std::string body;
  5214. auto res = cli_.Get("/compress", headers,
  5215. [&](const char *data, uint64_t data_length) {
  5216. EXPECT_EQ(100U, data_length);
  5217. body.append(data, data_length);
  5218. return true;
  5219. });
  5220. ASSERT_TRUE(res);
  5221. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5223. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5224. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5225. "7890123456789012345678901234567890",
  5226. body);
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. }
  5229. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5230. Headers headers;
  5231. headers.emplace("Accept-Encoding", "gzip, deflate");
  5232. cli_.set_decompress(false);
  5233. auto res = cli_.Get("/compress", headers);
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5237. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5238. EXPECT_EQ(33U, res->body.size());
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "");
  5244. std::string body;
  5245. auto res = cli_.Get("/compress", headers,
  5246. [&](const char *data, uint64_t data_length) {
  5247. EXPECT_EQ(100U, data_length);
  5248. body.append(data, data_length);
  5249. return true;
  5250. });
  5251. ASSERT_TRUE(res);
  5252. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5254. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5255. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5256. "7890123456789012345678901234567890",
  5257. body);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. }
  5260. TEST_F(ServerTest, NoGzip) {
  5261. Headers headers;
  5262. headers.emplace("Accept-Encoding", "gzip, deflate");
  5263. auto res = cli_.Get("/nocompress", headers);
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5266. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5267. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5269. "7890123456789012345678901234567890",
  5270. res->body);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5274. Headers headers;
  5275. headers.emplace("Accept-Encoding", "gzip, deflate");
  5276. std::string body;
  5277. auto res = cli_.Get("/nocompress", headers,
  5278. [&](const char *data, uint64_t data_length) {
  5279. EXPECT_EQ(100U, data_length);
  5280. body.append(data, data_length);
  5281. return true;
  5282. });
  5283. ASSERT_TRUE(res);
  5284. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5285. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5286. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5287. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5288. "7890123456789012345678901234567890",
  5289. body);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. }
  5292. TEST_F(ServerTest, MultipartFormDataGzip) {
  5293. UploadFormDataItems items = {
  5294. {"key1", "test", "", ""},
  5295. {"key2", "--abcdefg123", "", ""},
  5296. };
  5297. cli_.set_compress(true);
  5298. auto res = cli_.Post("/compress-multipart", items);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. }
  5302. #endif
  5303. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5304. TEST_F(ServerTest, Brotli) {
  5305. Headers headers;
  5306. headers.emplace("Accept-Encoding", "br");
  5307. auto res = cli_.Get("/compress", headers);
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5311. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5312. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5313. "7890123456789012345678901234567890",
  5314. res->body);
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. }
  5317. #endif
  5318. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5319. TEST_F(ServerTest, Zstd) {
  5320. Headers headers;
  5321. headers.emplace("Accept-Encoding", "zstd");
  5322. auto res = cli_.Get("/compress", headers);
  5323. ASSERT_TRUE(res);
  5324. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5326. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5327. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5328. "7890123456789012345678901234567890",
  5329. res->body);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. }
  5332. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5333. Headers headers;
  5334. headers.emplace("Accept-Encoding", "");
  5335. auto res = cli_.Get("/compress", headers);
  5336. ASSERT_TRUE(res);
  5337. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5341. "7890123456789012345678901234567890",
  5342. res->body);
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "zstd");
  5348. std::string body;
  5349. auto res = cli_.Get("/compress", headers,
  5350. [&](const char *data, uint64_t data_length) {
  5351. EXPECT_EQ(100U, data_length);
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "zstd");
  5367. cli_.set_decompress(false);
  5368. auto res = cli_.Get("/compress", headers);
  5369. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5370. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5371. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5372. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5373. ASSERT_TRUE(res);
  5374. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5376. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5377. EXPECT_EQ(StatusCode::OK_200, res->status);
  5378. ASSERT_EQ(26U, res->body.size());
  5379. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5380. 0);
  5381. }
  5382. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5383. Headers headers;
  5384. headers.emplace("Accept-Encoding", "");
  5385. std::string body;
  5386. auto res = cli_.Get("/compress", headers,
  5387. [&](const char *data, uint64_t data_length) {
  5388. EXPECT_EQ(100U, data_length);
  5389. body.append(data, data_length);
  5390. return true;
  5391. });
  5392. ASSERT_TRUE(res);
  5393. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5395. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5396. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5397. "7890123456789012345678901234567890",
  5398. body);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. }
  5401. TEST_F(ServerTest, NoZstd) {
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "zstd");
  5404. auto res = cli_.Get("/nocompress", headers);
  5405. ASSERT_TRUE(res);
  5406. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5407. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5408. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5410. "7890123456789012345678901234567890",
  5411. res->body);
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. }
  5414. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5415. Headers headers;
  5416. headers.emplace("Accept-Encoding", "zstd");
  5417. std::string body;
  5418. auto res = cli_.Get("/nocompress", headers,
  5419. [&](const char *data, uint64_t data_length) {
  5420. EXPECT_EQ(100U, data_length);
  5421. body.append(data, data_length);
  5422. return true;
  5423. });
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5426. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5429. "7890123456789012345678901234567890",
  5430. body);
  5431. EXPECT_EQ(StatusCode::OK_200, res->status);
  5432. }
  5433. // TODO: How to enable zstd ??
  5434. TEST_F(ServerTest, MultipartFormDataZstd) {
  5435. UploadFormDataItems items = {
  5436. {"key1", "test", "", ""},
  5437. {"key2", "--abcdefg123", "", ""},
  5438. };
  5439. Headers headers;
  5440. headers.emplace("Accept-Encoding", "zstd");
  5441. cli_.set_compress(true);
  5442. auto res = cli_.Post("/compress-multipart", headers, items);
  5443. ASSERT_TRUE(res);
  5444. EXPECT_EQ(StatusCode::OK_200, res->status);
  5445. }
  5446. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5447. Headers headers;
  5448. headers.emplace("Accept-Encoding", "zstd");
  5449. cli_.set_compress(true);
  5450. auto res = cli_.Put(
  5451. "/put", headers, 3,
  5452. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5453. sink.os << "PUT";
  5454. return true;
  5455. },
  5456. "text/plain");
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ(StatusCode::OK_200, res->status);
  5459. EXPECT_EQ("PUT", res->body);
  5460. }
  5461. // Pre-compression logging tests
  5462. TEST_F(ServerTest, PreCompressionLogging) {
  5463. // Test data for compression (matches the actual /compress endpoint content)
  5464. const std::string test_content =
  5465. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5466. "3456789012345678901234567890";
  5467. // Variables to capture logging data
  5468. std::string pre_compression_body;
  5469. std::string pre_compression_content_type;
  5470. std::string pre_compression_content_encoding;
  5471. std::string post_compression_body;
  5472. std::string post_compression_content_type;
  5473. std::string post_compression_content_encoding;
  5474. // Set up pre-compression logger
  5475. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5476. const Response &res) {
  5477. pre_compression_body = res.body;
  5478. pre_compression_content_type = res.get_header_value("Content-Type");
  5479. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5480. });
  5481. // Set up post-compression logger
  5482. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5483. post_compression_body = res.body;
  5484. post_compression_content_type = res.get_header_value("Content-Type");
  5485. post_compression_content_encoding =
  5486. res.get_header_value("Content-Encoding");
  5487. });
  5488. // Test with gzip compression
  5489. Headers headers;
  5490. headers.emplace("Accept-Encoding", "gzip");
  5491. auto res = cli_.Get("/compress", headers);
  5492. // Verify response was compressed
  5493. ASSERT_TRUE(res);
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5496. // Verify pre-compression logger captured uncompressed content
  5497. EXPECT_EQ(test_content, pre_compression_body);
  5498. EXPECT_EQ("text/plain", pre_compression_content_type);
  5499. EXPECT_TRUE(pre_compression_content_encoding
  5500. .empty()); // No encoding header before compression
  5501. // Verify post-compression logger captured compressed content
  5502. EXPECT_NE(test_content,
  5503. post_compression_body); // Should be different after compression
  5504. EXPECT_EQ("text/plain", post_compression_content_type);
  5505. EXPECT_EQ("gzip", post_compression_content_encoding);
  5506. // Verify compressed content is smaller
  5507. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5508. }
  5509. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5510. const std::string test_content =
  5511. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5512. "3456789012345678901234567890";
  5513. std::string pre_compression_body;
  5514. std::string post_compression_body;
  5515. svr_.set_pre_compression_logger(
  5516. [&](const Request & /*req*/, const Response &res) {
  5517. pre_compression_body = res.body;
  5518. });
  5519. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5520. post_compression_body = res.body;
  5521. });
  5522. Headers headers;
  5523. headers.emplace("Accept-Encoding", "br");
  5524. auto res = cli_.Get("/compress", headers);
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5528. // Verify pre-compression content is uncompressed
  5529. EXPECT_EQ(test_content, pre_compression_body);
  5530. // Verify post-compression content is compressed
  5531. EXPECT_NE(test_content, post_compression_body);
  5532. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5533. }
  5534. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5535. const std::string test_content =
  5536. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5537. "3456789012345678901234567890";
  5538. std::string pre_compression_body;
  5539. std::string post_compression_body;
  5540. svr_.set_pre_compression_logger(
  5541. [&](const Request & /*req*/, const Response &res) {
  5542. pre_compression_body = res.body;
  5543. });
  5544. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5545. post_compression_body = res.body;
  5546. });
  5547. // Request without compression (use /nocompress endpoint)
  5548. Headers headers;
  5549. auto res = cli_.Get("/nocompress", headers);
  5550. ASSERT_TRUE(res);
  5551. EXPECT_EQ(StatusCode::OK_200, res->status);
  5552. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5553. // Pre-compression logger should not be called when no compression is applied
  5554. EXPECT_TRUE(
  5555. pre_compression_body.empty()); // Pre-compression logger not called
  5556. EXPECT_EQ(
  5557. test_content,
  5558. post_compression_body); // Post-compression logger captures final content
  5559. }
  5560. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5561. const std::string test_content =
  5562. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5563. "3456789012345678901234567890";
  5564. std::string pre_compression_body;
  5565. bool pre_logger_called = false;
  5566. // Set only pre-compression logger
  5567. svr_.set_pre_compression_logger(
  5568. [&](const Request & /*req*/, const Response &res) {
  5569. pre_compression_body = res.body;
  5570. pre_logger_called = true;
  5571. });
  5572. Headers headers;
  5573. headers.emplace("Accept-Encoding", "gzip");
  5574. auto res = cli_.Get("/compress", headers);
  5575. ASSERT_TRUE(res);
  5576. EXPECT_EQ(StatusCode::OK_200, res->status);
  5577. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5578. // Verify pre-compression logger was called
  5579. EXPECT_TRUE(pre_logger_called);
  5580. EXPECT_EQ(test_content, pre_compression_body);
  5581. }
  5582. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5583. {
  5584. // Test with Expect: 100-continue header - success case
  5585. // Server returns 100 Continue, client sends body, server returns 200 OK
  5586. Request req;
  5587. req.method = "POST";
  5588. req.path = "/post-large";
  5589. req.set_header("Expect", "100-continue");
  5590. req.body = LARGE_DATA;
  5591. Response res;
  5592. auto error = Error::Success;
  5593. cli_.set_keep_alive(true);
  5594. auto ret = cli_.send(req, res, error);
  5595. EXPECT_TRUE(ret);
  5596. EXPECT_EQ(StatusCode::OK_200, res.status);
  5597. EXPECT_EQ(LARGE_DATA, res.body);
  5598. }
  5599. {
  5600. // Test with Expect: 100-continue header - error case
  5601. // Client should not send the body when server returns an error
  5602. Request req;
  5603. req.method = "POST";
  5604. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5605. req.set_header("Expect", "100-continue");
  5606. req.body = LARGE_DATA;
  5607. Response res;
  5608. auto error = Error::Success;
  5609. auto start = std::chrono::high_resolution_clock::now();
  5610. cli_.set_keep_alive(true);
  5611. auto ret = cli_.send(req, res, error);
  5612. auto end = std::chrono::high_resolution_clock::now();
  5613. auto elapsed =
  5614. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5615. .count();
  5616. // With Expect: 100-continue, request completes successfully but with error
  5617. EXPECT_TRUE(ret);
  5618. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5619. EXPECT_EQ("close", res.get_header_value("Connection"));
  5620. EXPECT_FALSE(cli_.is_socket_open());
  5621. EXPECT_LE(elapsed, 200);
  5622. }
  5623. {
  5624. // Send an extra GET request to ensure error recovery without hanging
  5625. Request req;
  5626. req.method = "GET";
  5627. req.path = "/hi";
  5628. auto start = std::chrono::high_resolution_clock::now();
  5629. auto res = cli_.send(req);
  5630. auto end = std::chrono::high_resolution_clock::now();
  5631. auto elapsed =
  5632. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5633. .count();
  5634. ASSERT_TRUE(res);
  5635. EXPECT_EQ(StatusCode::OK_200, res->status);
  5636. EXPECT_EQ("Hello World!", res->body);
  5637. EXPECT_LE(elapsed, 500);
  5638. }
  5639. }
  5640. TEST(ZstdDecompressor, ChunkedDecompression) {
  5641. std::string data;
  5642. for (size_t i = 0; i < 32 * 1024; ++i) {
  5643. data.push_back(static_cast<char>('a' + i % 26));
  5644. }
  5645. std::string compressed_data;
  5646. {
  5647. httplib::detail::zstd_compressor compressor;
  5648. bool result = compressor.compress(
  5649. data.data(), data.size(),
  5650. /*last=*/true,
  5651. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5652. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5653. compressed_data_size);
  5654. return true;
  5655. });
  5656. ASSERT_TRUE(result);
  5657. }
  5658. std::string decompressed_data;
  5659. {
  5660. httplib::detail::zstd_decompressor decompressor;
  5661. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5662. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5663. size_t chunk_size = 130;
  5664. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5665. chunk_begin += chunk_size) {
  5666. size_t current_chunk_size =
  5667. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5668. bool result = decompressor.decompress(
  5669. compressed_data.data() + chunk_begin, current_chunk_size,
  5670. [&](const char *decompressed_data_chunk,
  5671. size_t decompressed_data_chunk_size) {
  5672. decompressed_data.insert(decompressed_data.size(),
  5673. decompressed_data_chunk,
  5674. decompressed_data_chunk_size);
  5675. return true;
  5676. });
  5677. ASSERT_TRUE(result);
  5678. }
  5679. }
  5680. ASSERT_EQ(data, decompressed_data);
  5681. }
  5682. TEST(ZstdDecompressor, Decompress) {
  5683. std::string original_text = "Compressed with ZSTD";
  5684. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5685. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5686. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5687. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5688. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5689. std::string decompressed_data;
  5690. {
  5691. httplib::detail::zstd_decompressor decompressor;
  5692. bool result = decompressor.decompress(
  5693. compressed_data.data(), compressed_data.size(),
  5694. [&](const char *decompressed_data_chunk,
  5695. size_t decompressed_data_chunk_size) {
  5696. decompressed_data.insert(decompressed_data.size(),
  5697. decompressed_data_chunk,
  5698. decompressed_data_chunk_size);
  5699. return true;
  5700. });
  5701. ASSERT_TRUE(result);
  5702. }
  5703. ASSERT_EQ(original_text, decompressed_data);
  5704. }
  5705. #endif
  5706. // Sends a raw request to a server listening at HOST:PORT.
  5707. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5708. std::string *resp = nullptr) {
  5709. auto error = Error::Success;
  5710. auto client_sock = detail::create_client_socket(
  5711. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5712. /*connection_timeout_sec=*/5, 0,
  5713. /*read_timeout_sec=*/5, 0,
  5714. /*write_timeout_sec=*/5, 0, std::string(), error);
  5715. if (client_sock == INVALID_SOCKET) { return false; }
  5716. auto ret = detail::process_client_socket(
  5717. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5718. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5719. if (req.size() !=
  5720. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5721. return false;
  5722. }
  5723. char buf[512];
  5724. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5725. while (line_reader.getline()) {
  5726. if (resp) { *resp += line_reader.ptr(); }
  5727. }
  5728. return true;
  5729. });
  5730. detail::close_socket(client_sock);
  5731. return ret;
  5732. }
  5733. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5734. Server svr;
  5735. std::string header_value;
  5736. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5737. header_value = req.get_header_value("foo");
  5738. res.set_content("ok", "text/plain");
  5739. });
  5740. thread t = thread([&] { svr.listen(HOST, PORT); });
  5741. auto se = detail::scope_exit([&] {
  5742. svr.stop();
  5743. t.join();
  5744. ASSERT_FALSE(svr.is_running());
  5745. });
  5746. svr.wait_until_ready();
  5747. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5748. // like characters are not treated the same - use vertical tab and escape.
  5749. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5750. "foo: \t \v bar \x1B\t \r\n"
  5751. "Connection: close\r\n"
  5752. "\r\n";
  5753. std::string res;
  5754. ASSERT_TRUE(send_request(5, req, &res));
  5755. EXPECT_EQ(header_value, "");
  5756. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5757. }
  5758. // Sends a raw request and verifies that there isn't a crash or exception.
  5759. static void test_raw_request(const std::string &req,
  5760. std::string *out = nullptr) {
  5761. Server svr;
  5762. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5763. res.set_content("ok", "text/plain");
  5764. });
  5765. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5766. res.set_content("ok", "text/plain");
  5767. });
  5768. svr.Get("/header_field_value_check",
  5769. [&](const Request & /*req*/, Response &res) {
  5770. res.set_content("ok", "text/plain");
  5771. });
  5772. // Server read timeout must be longer than the client read timeout for the
  5773. // bug to reproduce, probably to force the server to process a request
  5774. // without a trailing blank line.
  5775. const time_t client_read_timeout_sec = 1;
  5776. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5777. bool listen_thread_ok = false;
  5778. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5779. auto se = detail::scope_exit([&] {
  5780. svr.stop();
  5781. t.join();
  5782. ASSERT_FALSE(svr.is_running());
  5783. EXPECT_TRUE(listen_thread_ok);
  5784. });
  5785. svr.wait_until_ready();
  5786. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5787. }
  5788. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5789. // A certain header line causes an exception if the header property is parsed
  5790. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5791. test_raw_request(
  5792. "GET /hi HTTP/1.1\r\n"
  5793. " : "
  5794. " "
  5795. " ");
  5796. }
  5797. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5798. // A certain header line causes an exception if the header property *name* is
  5799. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5800. // greedy matcher and requires backtracking when there are a lot of ":"
  5801. // characters.
  5802. // This occurs with libc++ but not libstdc++.
  5803. test_raw_request(
  5804. "GET /hi HTTP/1.1\r\n"
  5805. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5806. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5807. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5808. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5809. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5810. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5811. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5812. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5813. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5814. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5815. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5816. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5817. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5818. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5819. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5820. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5821. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5822. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5823. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5824. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5825. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5826. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5827. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5828. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5829. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5830. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5831. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5832. "&&&%%%");
  5833. }
  5834. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5835. // Make sure this doesn't crash the server.
  5836. // In a previous version of the header line regex, the "\r" rendered the line
  5837. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5838. // a new position where the leading white space ended and the field value
  5839. // began.
  5840. // The crash occurs with libc++ but not libstdc++.
  5841. test_raw_request("GET /hi HTTP/1.1\r\n"
  5842. "a:" +
  5843. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5844. "\r\n"
  5845. "\r\n");
  5846. }
  5847. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5848. std::string out;
  5849. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5850. "Content-Type: text/plain\r\n"
  5851. "Transfer-Encoding: chunked\r\n"
  5852. "\r\n"
  5853. "nothex\r\n",
  5854. &out);
  5855. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5856. }
  5857. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5858. std::string out;
  5859. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5860. "Content-Type: text/plain\r\n"
  5861. "Transfer-Encoding: chunked\r\n"
  5862. "\r\n"
  5863. "3\r\n"
  5864. "xyz\r\n"
  5865. "NaN\r\n",
  5866. &out);
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5868. }
  5869. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5870. std::string out;
  5871. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5872. "Content-Type: text/plain\r\n"
  5873. "Transfer-Encoding: chunked\r\n"
  5874. "\r\n"
  5875. // Length is too large for 64 bits.
  5876. "1ffffffffffffffff\r\n"
  5877. "xyz\r\n",
  5878. &out);
  5879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5880. }
  5881. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5882. test_raw_request("GET /hi HTTP/1.1\r\n"
  5883. "Content-Type: text/plain\r\n\r");
  5884. }
  5885. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5886. std::string out;
  5887. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5888. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5889. }
  5890. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5891. Server svr;
  5892. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5893. EXPECT_TRUE(!req.remote_addr.empty());
  5894. });
  5895. thread t = thread([&] { svr.listen(HOST, PORT); });
  5896. auto se = detail::scope_exit([&] {
  5897. svr.stop();
  5898. t.join();
  5899. ASSERT_FALSE(svr.is_running());
  5900. });
  5901. svr.wait_until_ready();
  5902. // Send an invalid request line to trigger Bad Request
  5903. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5904. std::string out;
  5905. ASSERT_TRUE(send_request(5, bad_req, &out));
  5906. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5907. }
  5908. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5909. std::string out;
  5910. std::string request(
  5911. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5912. test_raw_request(request, &out);
  5913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5914. }
  5915. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5916. std::string out;
  5917. std::string request(
  5918. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5919. test_raw_request(request, &out);
  5920. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5921. }
  5922. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5923. std::string out;
  5924. std::string request(
  5925. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5926. test_raw_request(request, &out);
  5927. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5928. }
  5929. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5930. std::string out;
  5931. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5932. "Test: \r\n\r\n",
  5933. &out);
  5934. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5935. }
  5936. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5937. Server svr;
  5938. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5939. res.set_header("Cache-Control", "no-cache");
  5940. res.set_chunked_content_provider(
  5941. "text/event-stream", [](size_t offset, DataSink &sink) {
  5942. std::string s = "data:";
  5943. s += std::to_string(offset);
  5944. s += "\n\n";
  5945. auto ret = sink.write(s.data(), s.size());
  5946. EXPECT_TRUE(ret);
  5947. std::this_thread::sleep_for(std::chrono::seconds(1));
  5948. return true;
  5949. });
  5950. });
  5951. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5952. svr.wait_until_ready();
  5953. Client client(HOST, PORT);
  5954. const Headers headers = {{"Accept", "text/event-stream"}};
  5955. auto get_thread = std::thread([&client, &headers]() {
  5956. auto res = client.Get(
  5957. "/events", headers,
  5958. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5959. });
  5960. auto se = detail::scope_exit([&] {
  5961. svr.stop();
  5962. get_thread.join();
  5963. listen_thread.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. });
  5966. // Give GET time to get a few messages.
  5967. std::this_thread::sleep_for(std::chrono::seconds(2));
  5968. }
  5969. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5970. httplib::Server svr;
  5971. svr.Post("/hi",
  5972. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5973. res.status = StatusCode::OK_200;
  5974. });
  5975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5976. svr.wait_until_ready();
  5977. Client cli(HOST, PORT);
  5978. auto res = cli.Post("/hi", "data", "text/plain");
  5979. ASSERT_TRUE(res);
  5980. EXPECT_EQ(StatusCode::OK_200, res->status);
  5981. svr.stop();
  5982. thread.join();
  5983. ASSERT_FALSE(svr.is_running());
  5984. res = cli.Post("/hi", "data", "text/plain");
  5985. ASSERT_FALSE(res);
  5986. }
  5987. TEST(ServerStopTest, ListenFailure) {
  5988. Server svr;
  5989. auto t = thread([&]() {
  5990. auto ret = svr.listen("????", PORT);
  5991. EXPECT_FALSE(ret);
  5992. });
  5993. svr.wait_until_ready();
  5994. svr.stop();
  5995. t.join();
  5996. }
  5997. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5998. TEST(ServerStopTest, Decommision) {
  5999. Server svr;
  6000. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6001. for (int i = 0; i < 4; i++) {
  6002. auto is_even = !(i % 2);
  6003. std::thread t{[&] {
  6004. try {
  6005. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6006. if (is_even) {
  6007. throw std::runtime_error("Some thing that happens to go wrong.");
  6008. }
  6009. svr.listen(HOST, PORT);
  6010. } catch (...) { svr.decommission(); }
  6011. }};
  6012. svr.wait_until_ready();
  6013. // Server is up
  6014. {
  6015. Client cli(HOST, PORT);
  6016. auto res = cli.Get("/hi");
  6017. if (is_even) {
  6018. EXPECT_FALSE(res);
  6019. } else {
  6020. EXPECT_TRUE(res);
  6021. EXPECT_EQ("hi...", res->body);
  6022. }
  6023. }
  6024. svr.stop();
  6025. t.join();
  6026. // Server is down...
  6027. {
  6028. Client cli(HOST, PORT);
  6029. auto res = cli.Get("/hi");
  6030. EXPECT_FALSE(res);
  6031. }
  6032. }
  6033. }
  6034. #endif
  6035. // Helper function for string body upload progress tests
  6036. template <typename SetupHandler, typename ClientCall>
  6037. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6038. ClientCall &&client_call,
  6039. const string &body) {
  6040. Server svr;
  6041. setup_handler(svr);
  6042. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6043. auto se = detail::scope_exit([&] {
  6044. svr.stop();
  6045. t.join();
  6046. });
  6047. svr.wait_until_ready();
  6048. Client cli(HOST, PORT);
  6049. vector<uint64_t> progress_values;
  6050. bool progress_called = false;
  6051. auto res =
  6052. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6053. progress_values.push_back(current);
  6054. progress_called = true;
  6055. return true;
  6056. });
  6057. ASSERT_TRUE(res);
  6058. EXPECT_EQ(200, res->status);
  6059. EXPECT_TRUE(progress_called);
  6060. }
  6061. TEST(UploadProgressTest, PostStringBodyBasic) {
  6062. TestStringBodyUploadProgress(
  6063. [](Server &svr) {
  6064. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6065. res.set_content("received", "text/plain");
  6066. });
  6067. },
  6068. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6069. return cli.Post("/test", body, "text/plain", progress_callback);
  6070. },
  6071. "test data for upload progress");
  6072. }
  6073. TEST(UploadProgressTest, PutStringBodyBasic) {
  6074. TestStringBodyUploadProgress(
  6075. [](Server &svr) {
  6076. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6077. res.set_content("put received", "text/plain");
  6078. });
  6079. },
  6080. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6081. return cli.Put("/test", body, "text/plain", progress_callback);
  6082. },
  6083. "put test data for upload progress");
  6084. }
  6085. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6086. TestStringBodyUploadProgress(
  6087. [](Server &svr) {
  6088. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6089. res.set_content("patch received", "text/plain");
  6090. });
  6091. },
  6092. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6093. return cli.Patch("/test", body, "text/plain", progress_callback);
  6094. },
  6095. "patch test data for upload progress");
  6096. }
  6097. // Helper function for content provider upload progress tests
  6098. template <typename SetupHandler, typename ClientCall>
  6099. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6100. ClientCall &&client_call) {
  6101. Server svr;
  6102. setup_handler(svr);
  6103. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6104. auto se = detail::scope_exit([&] {
  6105. svr.stop();
  6106. t.join();
  6107. });
  6108. svr.wait_until_ready();
  6109. Client cli(HOST, PORT);
  6110. vector<uint64_t> progress_values;
  6111. auto res =
  6112. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6113. progress_values.push_back(current);
  6114. return true;
  6115. });
  6116. ASSERT_TRUE(res);
  6117. EXPECT_EQ(200, res->status);
  6118. EXPECT_FALSE(progress_values.empty());
  6119. }
  6120. TEST(UploadProgressTest, PostContentProviderProgress) {
  6121. TestContentProviderUploadProgress(
  6122. [](Server &svr) {
  6123. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6124. res.set_content("provider received", "text/plain");
  6125. });
  6126. },
  6127. [](Client &cli, UploadProgress progress_callback) {
  6128. return cli.Post(
  6129. "/test", 10,
  6130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6131. sink.os << "test data";
  6132. return true;
  6133. },
  6134. "text/plain", progress_callback);
  6135. });
  6136. }
  6137. // Helper function for multipart upload progress tests
  6138. template <typename SetupHandler, typename ClientCall>
  6139. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6140. ClientCall &&client_call,
  6141. const string &endpoint) {
  6142. Server svr;
  6143. setup_handler(svr);
  6144. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6145. auto se = detail::scope_exit([&] {
  6146. svr.stop();
  6147. t.join();
  6148. });
  6149. svr.wait_until_ready();
  6150. Client cli(HOST, PORT);
  6151. vector<uint64_t> progress_values;
  6152. UploadFormDataItems items = {
  6153. {"field1", "value1", "", ""},
  6154. {"field2", "longer value for progress tracking test", "", ""},
  6155. {"file1", "file content data for upload progress", "test.txt",
  6156. "text/plain"}};
  6157. auto res = client_call(cli, endpoint, items,
  6158. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6159. progress_values.push_back(current);
  6160. return true;
  6161. });
  6162. ASSERT_TRUE(res);
  6163. EXPECT_EQ(200, res->status);
  6164. EXPECT_FALSE(progress_values.empty());
  6165. }
  6166. TEST(UploadProgressTest, PostMultipartProgress) {
  6167. TestMultipartUploadProgress(
  6168. [](Server &svr) {
  6169. svr.Post("/multipart", [](const Request &req, Response &res) {
  6170. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6171. res.set_content("multipart received", "text/plain");
  6172. });
  6173. },
  6174. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6175. UploadProgress progress_callback) {
  6176. return cli.Post(endpoint, items, progress_callback);
  6177. },
  6178. "/multipart");
  6179. }
  6180. // Helper function for basic download progress tests
  6181. template <typename SetupHandler, typename ClientCall>
  6182. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6183. ClientCall &&client_call, const string &endpoint,
  6184. size_t expected_content_size) {
  6185. Server svr;
  6186. setup_handler(svr);
  6187. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6188. auto se = detail::scope_exit([&] {
  6189. svr.stop();
  6190. t.join();
  6191. });
  6192. svr.wait_until_ready();
  6193. Client cli(HOST, PORT);
  6194. vector<uint64_t> progress_values;
  6195. auto res = client_call(cli, endpoint,
  6196. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6197. progress_values.push_back(current);
  6198. return true;
  6199. });
  6200. ASSERT_TRUE(res);
  6201. EXPECT_EQ(200, res->status);
  6202. EXPECT_FALSE(progress_values.empty());
  6203. EXPECT_EQ(expected_content_size, res->body.size());
  6204. }
  6205. TEST(DownloadProgressTest, GetBasic) {
  6206. TestBasicDownloadProgress(
  6207. [](Server &svr) {
  6208. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6209. string content(1000, 'D');
  6210. res.set_content(content, "text/plain");
  6211. });
  6212. },
  6213. [](Client &cli, const string &endpoint,
  6214. DownloadProgress progress_callback) {
  6215. return cli.Get(endpoint, progress_callback);
  6216. },
  6217. "/download", 1000u);
  6218. }
  6219. // Helper function for content receiver download progress tests
  6220. template <typename SetupHandler, typename ClientCall>
  6221. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6222. ClientCall &&client_call,
  6223. const string &endpoint,
  6224. size_t expected_content_size) {
  6225. Server svr;
  6226. setup_handler(svr);
  6227. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6228. auto se = detail::scope_exit([&] {
  6229. svr.stop();
  6230. t.join();
  6231. });
  6232. svr.wait_until_ready();
  6233. Client cli(HOST, PORT);
  6234. vector<uint64_t> progress_values;
  6235. string received_body;
  6236. auto res = client_call(
  6237. cli, endpoint,
  6238. [&](const char *data, size_t data_length) -> bool {
  6239. received_body.append(data, data_length);
  6240. return true;
  6241. },
  6242. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6243. progress_values.push_back(current);
  6244. return true;
  6245. });
  6246. ASSERT_TRUE(res);
  6247. EXPECT_EQ(200, res->status);
  6248. EXPECT_FALSE(progress_values.empty());
  6249. EXPECT_EQ(expected_content_size, received_body.size());
  6250. EXPECT_TRUE(res->body.empty());
  6251. }
  6252. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6253. TestContentReceiverDownloadProgress(
  6254. [](Server &svr) {
  6255. svr.Get("/download-receiver",
  6256. [](const Request & /*req*/, Response &res) {
  6257. string content(2000, 'R');
  6258. res.set_content(content, "text/plain");
  6259. });
  6260. },
  6261. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6262. DownloadProgress progress_callback) {
  6263. return cli.Get(endpoint, content_receiver, progress_callback);
  6264. },
  6265. "/download-receiver", 2000u);
  6266. }
  6267. TEST(StreamingTest, NoContentLengthStreaming) {
  6268. Server svr;
  6269. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6270. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6271. if (offset < 6) {
  6272. sink.os << (offset < 3 ? "a" : "b");
  6273. } else {
  6274. sink.done();
  6275. }
  6276. return true;
  6277. });
  6278. });
  6279. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6280. auto listen_se = detail::scope_exit([&] {
  6281. svr.stop();
  6282. listen_thread.join();
  6283. ASSERT_FALSE(svr.is_running());
  6284. });
  6285. svr.wait_until_ready();
  6286. Client client(HOST, PORT);
  6287. auto get_thread = std::thread([&client]() {
  6288. std::string s;
  6289. auto res =
  6290. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6291. s += std::string(data, len);
  6292. return true;
  6293. });
  6294. ASSERT_TRUE(res);
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. EXPECT_EQ("aaabbb", s);
  6297. });
  6298. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6299. // Give GET time to get a few messages.
  6300. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6301. }
  6302. TEST(MountTest, Unmount) {
  6303. Server svr;
  6304. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6305. auto se = detail::scope_exit([&] {
  6306. svr.stop();
  6307. listen_thread.join();
  6308. ASSERT_FALSE(svr.is_running());
  6309. });
  6310. svr.wait_until_ready();
  6311. Client cli("localhost", PORT);
  6312. svr.set_mount_point("/mount2", "./www2");
  6313. auto res = cli.Get("/");
  6314. ASSERT_TRUE(res);
  6315. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6316. res = cli.Get("/mount2/dir/test.html");
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. svr.set_mount_point("/", "./www");
  6320. res = cli.Get("/dir/");
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. svr.remove_mount_point("/");
  6324. res = cli.Get("/dir/");
  6325. ASSERT_TRUE(res);
  6326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6327. svr.remove_mount_point("/mount2");
  6328. res = cli.Get("/mount2/dir/test.html");
  6329. ASSERT_TRUE(res);
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST(MountTest, Redicect) {
  6333. Server svr;
  6334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6335. auto se = detail::scope_exit([&] {
  6336. svr.stop();
  6337. listen_thread.join();
  6338. ASSERT_FALSE(svr.is_running());
  6339. });
  6340. svr.set_mount_point("/", "./www");
  6341. svr.wait_until_ready();
  6342. Client cli("localhost", PORT);
  6343. auto res = cli.Get("/dir/");
  6344. ASSERT_TRUE(res);
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. res = cli.Get("/dir");
  6347. ASSERT_TRUE(res);
  6348. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6349. res = cli.Get("/file");
  6350. ASSERT_TRUE(res);
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. res = cli.Get("/file/");
  6353. ASSERT_TRUE(res);
  6354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6355. cli.set_follow_location(true);
  6356. res = cli.Get("/dir");
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. }
  6360. TEST(MountTest, MultibytesPathName) {
  6361. Server svr;
  6362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6363. auto se = detail::scope_exit([&] {
  6364. svr.stop();
  6365. listen_thread.join();
  6366. ASSERT_FALSE(svr.is_running());
  6367. });
  6368. svr.set_mount_point("/", "./www");
  6369. svr.wait_until_ready();
  6370. Client cli("localhost", PORT);
  6371. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6372. ASSERT_TRUE(res);
  6373. EXPECT_EQ(StatusCode::OK_200, res->status);
  6374. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6375. }
  6376. TEST(KeepAliveTest, ReadTimeout) {
  6377. Server svr;
  6378. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6379. std::this_thread::sleep_for(std::chrono::seconds(2));
  6380. res.set_content("a", "text/plain");
  6381. });
  6382. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6383. res.set_content("b", "text/plain");
  6384. });
  6385. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6386. auto se = detail::scope_exit([&] {
  6387. svr.stop();
  6388. listen_thread.join();
  6389. ASSERT_FALSE(svr.is_running());
  6390. });
  6391. svr.wait_until_ready();
  6392. Client cli("localhost", PORT);
  6393. cli.set_keep_alive(true);
  6394. cli.set_read_timeout(std::chrono::seconds(1));
  6395. auto resa = cli.Get("/a");
  6396. ASSERT_FALSE(resa);
  6397. EXPECT_EQ(Error::Read, resa.error());
  6398. auto resb = cli.Get("/b");
  6399. ASSERT_TRUE(resb);
  6400. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6401. EXPECT_EQ("b", resb->body);
  6402. }
  6403. TEST(KeepAliveTest, MaxCount) {
  6404. size_t keep_alive_max_count = 3;
  6405. Server svr;
  6406. svr.set_keep_alive_max_count(keep_alive_max_count);
  6407. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6408. res.set_content("Hello World!", "text/plain");
  6409. });
  6410. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6411. auto se = detail::scope_exit([&] {
  6412. svr.stop();
  6413. listen_thread.join();
  6414. ASSERT_FALSE(svr.is_running());
  6415. });
  6416. svr.wait_until_ready();
  6417. Client cli(HOST, PORT);
  6418. cli.set_keep_alive(true);
  6419. for (size_t i = 0; i < 5; i++) {
  6420. auto result = cli.Get("/hi");
  6421. ASSERT_TRUE(result);
  6422. EXPECT_EQ(StatusCode::OK_200, result->status);
  6423. if (i == keep_alive_max_count - 1) {
  6424. EXPECT_EQ("close", result->get_header_value("Connection"));
  6425. } else {
  6426. EXPECT_FALSE(result->has_header("Connection"));
  6427. }
  6428. }
  6429. }
  6430. TEST(KeepAliveTest, Issue1041) {
  6431. Server svr;
  6432. svr.set_keep_alive_timeout(3);
  6433. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6434. res.set_content("Hello World!", "text/plain");
  6435. });
  6436. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6437. auto se = detail::scope_exit([&] {
  6438. svr.stop();
  6439. listen_thread.join();
  6440. ASSERT_FALSE(svr.is_running());
  6441. });
  6442. svr.wait_until_ready();
  6443. Client cli(HOST, PORT);
  6444. cli.set_keep_alive(true);
  6445. auto result = cli.Get("/hi");
  6446. ASSERT_TRUE(result);
  6447. EXPECT_EQ(StatusCode::OK_200, result->status);
  6448. std::this_thread::sleep_for(std::chrono::seconds(5));
  6449. result = cli.Get("/hi");
  6450. ASSERT_TRUE(result);
  6451. EXPECT_EQ(StatusCode::OK_200, result->status);
  6452. }
  6453. TEST(KeepAliveTest, Issue1959) {
  6454. Server svr;
  6455. svr.set_keep_alive_timeout(5);
  6456. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6457. res.set_content("a", "text/plain");
  6458. });
  6459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6460. auto se = detail::scope_exit([&] {
  6461. if (!svr.is_running()) return;
  6462. svr.stop();
  6463. listen_thread.join();
  6464. ASSERT_FALSE(svr.is_running());
  6465. });
  6466. svr.wait_until_ready();
  6467. Client cli("localhost", PORT);
  6468. cli.set_keep_alive(true);
  6469. using namespace std::chrono;
  6470. auto start = steady_clock::now();
  6471. cli.Get("/a");
  6472. svr.stop();
  6473. listen_thread.join();
  6474. auto end = steady_clock::now();
  6475. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6476. EXPECT_LT(elapsed, 5000);
  6477. }
  6478. #ifdef CPPHTTPLIB_SSL_ENABLED
  6479. TEST(KeepAliveTest, SSLClientReconnection) {
  6480. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6481. ASSERT_TRUE(svr.is_valid());
  6482. svr.set_keep_alive_timeout(1);
  6483. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6484. res.set_content("Hello World!", "text/plain");
  6485. });
  6486. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6487. auto se = detail::scope_exit([&] {
  6488. svr.stop();
  6489. listen_thread.join();
  6490. ASSERT_FALSE(svr.is_running());
  6491. });
  6492. svr.wait_until_ready();
  6493. SSLClient cli(HOST, PORT);
  6494. cli.enable_server_certificate_verification(false);
  6495. cli.set_keep_alive(true);
  6496. auto result = cli.Get("/hi");
  6497. ASSERT_TRUE(result);
  6498. EXPECT_EQ(StatusCode::OK_200, result->status);
  6499. result = cli.Get("/hi");
  6500. ASSERT_TRUE(result);
  6501. EXPECT_EQ(StatusCode::OK_200, result->status);
  6502. std::this_thread::sleep_for(std::chrono::seconds(2));
  6503. // Recoonect
  6504. result = cli.Get("/hi");
  6505. ASSERT_TRUE(result);
  6506. EXPECT_EQ(StatusCode::OK_200, result->status);
  6507. result = cli.Get("/hi");
  6508. ASSERT_TRUE(result);
  6509. EXPECT_EQ(StatusCode::OK_200, result->status);
  6510. }
  6511. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6513. ASSERT_TRUE(svr.is_valid());
  6514. svr.set_keep_alive_timeout(1);
  6515. std::string content = "reconnect";
  6516. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6517. res.set_content("Hello World!", "text/plain");
  6518. });
  6519. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6520. auto se = detail::scope_exit([&] {
  6521. svr.stop();
  6522. listen_thread.join();
  6523. ASSERT_FALSE(svr.is_running());
  6524. });
  6525. svr.wait_until_ready();
  6526. SSLClient cli(HOST, PORT);
  6527. cli.enable_server_certificate_verification(false);
  6528. cli.set_keep_alive(true);
  6529. auto result = cli.Post(
  6530. "/hi", content.size(),
  6531. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6532. sink.write(content.c_str(), content.size());
  6533. return true;
  6534. },
  6535. "text/plain");
  6536. ASSERT_TRUE(result);
  6537. EXPECT_EQ(200, result->status);
  6538. std::this_thread::sleep_for(std::chrono::seconds(2));
  6539. // Recoonect
  6540. result = cli.Post(
  6541. "/hi", content.size(),
  6542. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6543. sink.write(content.c_str(), content.size());
  6544. return true;
  6545. },
  6546. "text/plain");
  6547. ASSERT_TRUE(result);
  6548. EXPECT_EQ(200, result->status);
  6549. result = cli.Post(
  6550. "/hi", content.size(),
  6551. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6552. sink.write(content.c_str(), content.size());
  6553. return true;
  6554. },
  6555. "text/plain");
  6556. ASSERT_TRUE(result);
  6557. EXPECT_EQ(200, result->status);
  6558. }
  6559. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6560. using namespace httplib::tls;
  6561. {
  6562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6563. ASSERT_TRUE(svr.is_valid());
  6564. svr.Get("/sni", [&](const Request &req, Response &res) {
  6565. std::string expected = req.sni();
  6566. EXPECT_EQ(expected, req.get_param_value("expected"));
  6567. res.set_content("ok", "text/plain");
  6568. });
  6569. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. listen_thread.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.wait_until_ready();
  6576. {
  6577. SSLClient cli("localhost", PORT);
  6578. cli.enable_server_certificate_verification(false);
  6579. auto res = cli.Get("/sni?expected=localhost");
  6580. ASSERT_TRUE(res);
  6581. }
  6582. {
  6583. SSLClient cli("::1", PORT);
  6584. cli.enable_server_certificate_verification(false);
  6585. auto res = cli.Get("/sni?expected=");
  6586. // NOTE: This may fail if the server is listening on IPv4 only
  6587. // (e.g., when localhost resolves to 127.0.0.1 only)
  6588. if (res) {
  6589. EXPECT_EQ(StatusCode::OK_200, res->status);
  6590. } else {
  6591. EXPECT_EQ(Error::Connection, res.error());
  6592. }
  6593. }
  6594. }
  6595. }
  6596. #endif
  6597. TEST(ClientProblemDetectionTest, ContentProvider) {
  6598. Server svr;
  6599. size_t content_length = 1024 * 1024;
  6600. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6601. res.set_content_provider(
  6602. content_length, "text/plain",
  6603. [&](size_t offset, size_t length, DataSink &sink) {
  6604. auto out_len = std::min(length, static_cast<size_t>(1024));
  6605. std::string out(out_len, '@');
  6606. sink.write(out.data(), out_len);
  6607. return offset < 4096;
  6608. },
  6609. [](bool success) { ASSERT_FALSE(success); });
  6610. });
  6611. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6612. res.set_content_provider(
  6613. 0, "text/plain",
  6614. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6615. EXPECT_TRUE(false);
  6616. return true;
  6617. },
  6618. [](bool success) { ASSERT_FALSE(success); });
  6619. });
  6620. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6621. auto se = detail::scope_exit([&] {
  6622. svr.stop();
  6623. listen_thread.join();
  6624. ASSERT_FALSE(svr.is_running());
  6625. });
  6626. svr.wait_until_ready();
  6627. Client cli("localhost", PORT);
  6628. {
  6629. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6630. size_t /*data_length*/) { return false; });
  6631. ASSERT_FALSE(res);
  6632. }
  6633. {
  6634. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6635. size_t /*data_length*/) { return false; });
  6636. ASSERT_TRUE(res);
  6637. }
  6638. }
  6639. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6640. Server svr;
  6641. svr.set_error_handler([](Request const &, Response &res) -> void {
  6642. res.set_chunked_content_provider(
  6643. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6644. sink.os << "hello";
  6645. sink.os << "world";
  6646. sink.done();
  6647. return true;
  6648. });
  6649. });
  6650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6651. auto se = detail::scope_exit([&] {
  6652. svr.stop();
  6653. listen_thread.join();
  6654. ASSERT_FALSE(svr.is_running());
  6655. });
  6656. svr.wait_until_ready();
  6657. Client cli("localhost", PORT);
  6658. auto res = cli.Get("/");
  6659. ASSERT_TRUE(res);
  6660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6661. EXPECT_EQ("helloworld", res->body);
  6662. }
  6663. TEST(LongPollingTest, ClientCloseDetection) {
  6664. Server svr;
  6665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6666. res.set_chunked_content_provider(
  6667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6669. sink.os << "hello";
  6670. auto count = 10;
  6671. while (count > 0 && sink.is_writable()) {
  6672. this_thread::sleep_for(chrono::milliseconds(10));
  6673. count--;
  6674. }
  6675. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6676. return true;
  6677. });
  6678. });
  6679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6680. auto se = detail::scope_exit([&] {
  6681. svr.stop();
  6682. listen_thread.join();
  6683. ASSERT_FALSE(svr.is_running());
  6684. });
  6685. svr.wait_until_ready();
  6686. Client cli("localhost", PORT);
  6687. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6688. EXPECT_EQ("hello", string(data, data_length));
  6689. return false; // close the socket immediately.
  6690. });
  6691. ASSERT_FALSE(res);
  6692. }
  6693. TEST(GetWithParametersTest, GetWithParameters) {
  6694. Server svr;
  6695. svr.Get("/", [&](const Request &req, Response &) {
  6696. EXPECT_EQ("world", req.get_param_value("hello"));
  6697. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6698. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6699. });
  6700. svr.Get("/params", [&](const Request &req, Response &) {
  6701. EXPECT_EQ("world", req.get_param_value("hello"));
  6702. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6703. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6704. });
  6705. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6706. EXPECT_EQ("resource-id", req.matches[1]);
  6707. EXPECT_EQ("foo", req.get_param_value("param1"));
  6708. EXPECT_EQ("bar", req.get_param_value("param2"));
  6709. });
  6710. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6711. EXPECT_EQ("user-id", req.path_params.at("id"));
  6712. EXPECT_EQ("foo", req.get_param_value("param1"));
  6713. EXPECT_EQ("bar", req.get_param_value("param2"));
  6714. });
  6715. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6716. auto se = detail::scope_exit([&] {
  6717. svr.stop();
  6718. listen_thread.join();
  6719. ASSERT_FALSE(svr.is_running());
  6720. });
  6721. svr.wait_until_ready();
  6722. {
  6723. Client cli(HOST, PORT);
  6724. Params params;
  6725. params.emplace("hello", "world");
  6726. params.emplace("hello2", "world2");
  6727. params.emplace("hello3", "world3");
  6728. auto res = cli.Get("/", params, Headers{});
  6729. ASSERT_TRUE(res);
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. }
  6732. {
  6733. Client cli(HOST, PORT);
  6734. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6735. ASSERT_TRUE(res);
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. }
  6738. {
  6739. Client cli(HOST, PORT);
  6740. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6741. ASSERT_TRUE(res);
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. }
  6744. {
  6745. Client cli(HOST, PORT);
  6746. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6747. ASSERT_TRUE(res);
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. }
  6751. TEST(GetWithParametersTest, GetWithParameters2) {
  6752. Server svr;
  6753. svr.Get("/", [&](const Request &req, Response &res) {
  6754. auto text = req.get_param_value("hello");
  6755. res.set_content(text, "text/plain");
  6756. });
  6757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6758. auto se = detail::scope_exit([&] {
  6759. svr.stop();
  6760. listen_thread.join();
  6761. ASSERT_FALSE(svr.is_running());
  6762. });
  6763. svr.wait_until_ready();
  6764. Client cli("localhost", PORT);
  6765. Params params;
  6766. params.emplace("hello", "world");
  6767. std::string body;
  6768. auto res = cli.Get("/", params, Headers{},
  6769. [&](const char *data, size_t data_length) {
  6770. body.append(data, data_length);
  6771. return true;
  6772. });
  6773. ASSERT_TRUE(res);
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. EXPECT_EQ("world", body);
  6776. }
  6777. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6778. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6779. auto host = "httpcan.org";
  6780. auto path = std::string{"/range/32"};
  6781. #else
  6782. auto host = "nghttp2.org";
  6783. auto path = std::string{"/httpbin/range/32"};
  6784. #endif
  6785. #ifdef CPPHTTPLIB_SSL_ENABLED
  6786. SSLClient cli(host);
  6787. #else
  6788. Client cli(host);
  6789. #endif
  6790. cli.set_default_headers({make_range_header({{1, 10}})});
  6791. cli.set_connection_timeout(5);
  6792. {
  6793. auto res = cli.Get(path);
  6794. ASSERT_TRUE(res);
  6795. EXPECT_EQ("bcdefghijk", res->body);
  6796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6797. }
  6798. {
  6799. auto res = cli.Get(path);
  6800. ASSERT_TRUE(res);
  6801. EXPECT_EQ("bcdefghijk", res->body);
  6802. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6803. }
  6804. }
  6805. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6806. Server svr;
  6807. svr.set_default_headers({{"Hello", "World"}});
  6808. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6809. res.set_content("ok", "text/plain");
  6810. });
  6811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6812. auto se = detail::scope_exit([&] {
  6813. svr.stop();
  6814. listen_thread.join();
  6815. ASSERT_FALSE(svr.is_running());
  6816. });
  6817. svr.wait_until_ready();
  6818. Client cli("localhost", PORT);
  6819. auto res = cli.Get("/");
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("ok", res->body);
  6823. EXPECT_EQ("World", res->get_header_value("Hello"));
  6824. }
  6825. #ifdef CPPHTTPLIB_SSL_ENABLED
  6826. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6828. ASSERT_TRUE(svr.is_valid());
  6829. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6830. std::this_thread::sleep_for(std::chrono::seconds(2));
  6831. res.set_content("a", "text/plain");
  6832. });
  6833. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6834. res.set_content("b", "text/plain");
  6835. });
  6836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6837. auto se = detail::scope_exit([&] {
  6838. svr.stop();
  6839. listen_thread.join();
  6840. ASSERT_FALSE(svr.is_running());
  6841. });
  6842. svr.wait_until_ready();
  6843. SSLClient cli("localhost", PORT);
  6844. cli.enable_server_certificate_verification(false);
  6845. cli.set_keep_alive(true);
  6846. cli.set_read_timeout(std::chrono::seconds(1));
  6847. auto resa = cli.Get("/a");
  6848. ASSERT_TRUE(!resa);
  6849. EXPECT_EQ(Error::Read, resa.error());
  6850. auto resb = cli.Get("/b");
  6851. ASSERT_TRUE(resb);
  6852. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6853. EXPECT_EQ("b", resb->body);
  6854. }
  6855. #endif
  6856. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6857. protected:
  6858. ServerTestWithAI_PASSIVE()
  6859. : cli_(HOST, PORT)
  6860. #ifdef CPPHTTPLIB_SSL_ENABLED
  6861. ,
  6862. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6863. #endif
  6864. {
  6865. #ifdef CPPHTTPLIB_SSL_ENABLED
  6866. cli_.enable_server_certificate_verification(false);
  6867. #endif
  6868. }
  6869. virtual void SetUp() {
  6870. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6871. res.set_content("Hello World!", "text/plain");
  6872. });
  6873. t_ = thread(
  6874. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6875. svr_.wait_until_ready();
  6876. }
  6877. virtual void TearDown() {
  6878. svr_.stop();
  6879. t_.join();
  6880. }
  6881. #ifdef CPPHTTPLIB_SSL_ENABLED
  6882. SSLClient cli_;
  6883. SSLServer svr_;
  6884. #else
  6885. Client cli_;
  6886. Server svr_;
  6887. #endif
  6888. thread t_;
  6889. };
  6890. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6891. auto res = cli_.Get("/hi");
  6892. ASSERT_TRUE(res);
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6895. EXPECT_EQ("Hello World!", res->body);
  6896. }
  6897. class ServerUpDownTest : public ::testing::Test {
  6898. protected:
  6899. ServerUpDownTest() : cli_(HOST, PORT) {}
  6900. virtual void SetUp() {
  6901. t_ = thread([&]() {
  6902. svr_.bind_to_any_port(HOST);
  6903. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6904. ASSERT_TRUE(svr_.listen_after_bind());
  6905. });
  6906. svr_.wait_until_ready();
  6907. }
  6908. virtual void TearDown() {
  6909. svr_.stop();
  6910. t_.join();
  6911. }
  6912. Client cli_;
  6913. Server svr_;
  6914. thread t_;
  6915. };
  6916. TEST_F(ServerUpDownTest, QuickStartStop) {
  6917. // Should not crash, especially when run with
  6918. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6919. }
  6920. class PayloadMaxLengthTest : public ::testing::Test {
  6921. protected:
  6922. PayloadMaxLengthTest()
  6923. : cli_(HOST, PORT)
  6924. #ifdef CPPHTTPLIB_SSL_ENABLED
  6925. ,
  6926. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6927. #endif
  6928. {
  6929. #ifdef CPPHTTPLIB_SSL_ENABLED
  6930. cli_.enable_server_certificate_verification(false);
  6931. #endif
  6932. }
  6933. virtual void SetUp() {
  6934. svr_.set_payload_max_length(8);
  6935. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6936. res.set_content("test", "text/plain");
  6937. });
  6938. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6939. svr_.wait_until_ready();
  6940. }
  6941. virtual void TearDown() {
  6942. svr_.stop();
  6943. t_.join();
  6944. }
  6945. #ifdef CPPHTTPLIB_SSL_ENABLED
  6946. SSLClient cli_;
  6947. SSLServer svr_;
  6948. #else
  6949. Client cli_;
  6950. Server svr_;
  6951. #endif
  6952. thread t_;
  6953. };
  6954. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6955. auto res = cli_.Post("/test", "123456789", "text/plain");
  6956. ASSERT_TRUE(res);
  6957. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6958. res = cli_.Post("/test", "12345678", "text/plain");
  6959. ASSERT_TRUE(res);
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6963. // Test chunked encoding with payload exceeding the 8-byte limit
  6964. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6965. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6966. ASSERT_TRUE(res);
  6967. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6968. }
  6969. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6970. // Test chunked encoding with payload within the 8-byte limit
  6971. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6972. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6973. ASSERT_TRUE(res);
  6974. EXPECT_EQ(StatusCode::OK_200, res->status);
  6975. }
  6976. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6977. // Test using send_request to send chunked data exceeding payload limit
  6978. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6979. "Host: " +
  6980. std::string(HOST) + ":" + std::to_string(PORT) +
  6981. "\r\n"
  6982. "Transfer-Encoding: chunked\r\n"
  6983. "Connection: close\r\n"
  6984. "\r\n"
  6985. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6986. "0123456789\r\n"
  6987. "0\r\n" // End chunk
  6988. "\r\n";
  6989. std::string response;
  6990. bool result = send_request(1, chunked_request, &response);
  6991. if (!result) {
  6992. // If send_request fails, it might be because the server closed the
  6993. // connection due to payload limit enforcement, which is acceptable
  6994. SUCCEED()
  6995. << "Server rejected oversized chunked request (connection closed)";
  6996. } else {
  6997. // If we got a response, check if it's an error response or connection was
  6998. // closed early Short response length indicates connection was closed due to
  6999. // payload limit
  7000. if (response.length() <= 10) {
  7001. SUCCEED() << "Server closed connection for oversized chunked request";
  7002. } else {
  7003. // Check for error status codes
  7004. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7005. response.find("Payload Too Large") != std::string::npos ||
  7006. response.find("400") != std::string::npos);
  7007. }
  7008. }
  7009. }
  7010. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7011. // Test request without Content-Length header exceeding payload limit
  7012. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7013. "Host: " +
  7014. std::string(HOST) + ":" +
  7015. std::to_string(PORT) +
  7016. "\r\n"
  7017. "Connection: close\r\n"
  7018. "\r\n";
  7019. // Add payload exceeding the 8-byte limit
  7020. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7021. request_without_content_length += large_payload;
  7022. std::string response;
  7023. bool result = send_request(1, request_without_content_length, &response);
  7024. if (!result) {
  7025. // If send_request fails, server likely closed connection due to payload
  7026. // limit
  7027. SUCCEED() << "Server rejected oversized request without Content-Length "
  7028. "(connection closed)";
  7029. } else {
  7030. // Check if server responded with error or closed connection early
  7031. if (response.length() <= 10) {
  7032. SUCCEED() << "Server closed connection for oversized request without "
  7033. "Content-Length";
  7034. } else {
  7035. // Check for error status codes
  7036. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7037. response.find("Payload Too Large") != std::string::npos ||
  7038. response.find("400") != std::string::npos);
  7039. }
  7040. }
  7041. }
  7042. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7043. // Test request without Content-Length header within payload limit
  7044. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7045. "Host: " +
  7046. std::string(HOST) + ":" +
  7047. std::to_string(PORT) +
  7048. "\r\n"
  7049. "Connection: close\r\n"
  7050. "\r\n";
  7051. // Add payload within the 8-byte limit
  7052. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7053. request_without_content_length += small_payload;
  7054. std::string response;
  7055. bool result = send_request(1, request_without_content_length, &response);
  7056. // For requests without Content-Length, the server may have different behavior
  7057. // The key is that it should not reject due to payload limit for small
  7058. // payloads
  7059. if (result) {
  7060. // Check for any HTTP response (success or error, but not connection closed)
  7061. if (response.length() > 10) {
  7062. SUCCEED()
  7063. << "Server processed request without Content-Length within limit";
  7064. } else {
  7065. // Short response might indicate connection closed, which is acceptable
  7066. SUCCEED() << "Server closed connection for request without "
  7067. "Content-Length (acceptable behavior)";
  7068. }
  7069. } else {
  7070. // Connection failure might be due to protocol requirements
  7071. SUCCEED() << "Connection issue with request without Content-Length "
  7072. "(environment-specific)";
  7073. }
  7074. }
  7075. class LargePayloadMaxLengthTest : public ::testing::Test {
  7076. protected:
  7077. LargePayloadMaxLengthTest()
  7078. : cli_(HOST, PORT)
  7079. #ifdef CPPHTTPLIB_SSL_ENABLED
  7080. ,
  7081. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7082. #endif
  7083. {
  7084. #ifdef CPPHTTPLIB_SSL_ENABLED
  7085. cli_.enable_server_certificate_verification(false);
  7086. #endif
  7087. }
  7088. virtual void SetUp() {
  7089. // Set 10MB payload limit
  7090. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7091. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7092. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7093. res.set_content("Large payload test", "text/plain");
  7094. });
  7095. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7096. svr_.wait_until_ready();
  7097. }
  7098. virtual void TearDown() {
  7099. svr_.stop();
  7100. t_.join();
  7101. }
  7102. #ifdef CPPHTTPLIB_SSL_ENABLED
  7103. SSLClient cli_;
  7104. SSLServer svr_;
  7105. #else
  7106. Client cli_;
  7107. Server svr_;
  7108. #endif
  7109. thread t_;
  7110. };
  7111. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7112. // Test chunked encoding with payload within 10MB limit
  7113. std::string medium_payload(5 * 1024 * 1024,
  7114. 'A'); // 5MB payload, within 10MB limit
  7115. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7116. ASSERT_TRUE(res);
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. }
  7119. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7120. // Test chunked encoding with payload exceeding 10MB limit
  7121. std::string large_payload(12 * 1024 * 1024,
  7122. 'B'); // 12MB payload, exceeds 10MB limit
  7123. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7124. // Server may either return 413 or close the connection
  7125. if (res) {
  7126. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7127. } else {
  7128. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7129. }
  7130. }
  7131. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7132. // Test request without Content-Length header within 10MB limit
  7133. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7134. "Host: " +
  7135. std::string(HOST) + ":" +
  7136. std::to_string(PORT) +
  7137. "\r\n"
  7138. "Connection: close\r\n"
  7139. "\r\n";
  7140. // Add 1MB payload (within 10MB limit)
  7141. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7142. request_without_content_length += medium_payload;
  7143. std::string response;
  7144. bool result = send_request(5, request_without_content_length, &response);
  7145. if (result) {
  7146. // Should get a proper HTTP response for payloads within limit
  7147. if (response.length() > 10) {
  7148. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7149. "10MB limit";
  7150. } else {
  7151. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7152. "Content-Length)";
  7153. }
  7154. } else {
  7155. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7156. }
  7157. }
  7158. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7159. // Test request without Content-Length header exceeding 10MB limit
  7160. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7161. "Host: " +
  7162. std::string(HOST) + ":" +
  7163. std::to_string(PORT) +
  7164. "\r\n"
  7165. "Connection: close\r\n"
  7166. "\r\n";
  7167. // Add 12MB payload (exceeds 10MB limit)
  7168. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7169. request_without_content_length += large_payload;
  7170. std::string response;
  7171. bool result = send_request(10, request_without_content_length, &response);
  7172. if (!result) {
  7173. // Server should close connection due to payload limit
  7174. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7175. "(connection closed)";
  7176. } else {
  7177. // Check for error response
  7178. if (response.length() <= 10) {
  7179. SUCCEED()
  7180. << "Server closed connection for 12MB request exceeding 10MB limit";
  7181. } else {
  7182. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7183. response.find("Payload Too Large") != std::string::npos ||
  7184. response.find("400") != std::string::npos);
  7185. }
  7186. }
  7187. }
  7188. // Regression test for DoS vulnerability: a malicious server sending a response
  7189. // without Content-Length header must not cause unbounded memory consumption on
  7190. // the client side. The client should stop reading after a reasonable limit,
  7191. // similar to the server-side set_payload_max_length protection.
  7192. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7193. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7194. #ifndef _WIN32
  7195. signal(SIGPIPE, SIG_IGN);
  7196. #endif
  7197. auto server_thread = std::thread([] {
  7198. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7199. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7200. default_socket_options(srv);
  7201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7202. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7203. sockaddr_in addr{};
  7204. addr.sin_family = AF_INET;
  7205. addr.sin_port = htons(PORT + 2);
  7206. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7207. int opt = 1;
  7208. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7209. #ifdef _WIN32
  7210. reinterpret_cast<const char *>(&opt),
  7211. #else
  7212. &opt,
  7213. #endif
  7214. sizeof(opt));
  7215. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7216. ::listen(srv, 1);
  7217. sockaddr_in cli_addr{};
  7218. socklen_t cli_len = sizeof(cli_addr);
  7219. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7220. if (cli != INVALID_SOCKET) {
  7221. char buf[4096];
  7222. ::recv(cli, buf, sizeof(buf), 0);
  7223. // Malicious response: no Content-Length, no chunked encoding
  7224. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7225. "Connection: close\r\n"
  7226. "\r\n";
  7227. ::send(cli,
  7228. #ifdef _WIN32
  7229. static_cast<const char *>(response_header.c_str()),
  7230. static_cast<int>(response_header.size()),
  7231. #else
  7232. response_header.c_str(), response_header.size(),
  7233. #endif
  7234. 0);
  7235. // Send 10MB of data
  7236. std::string chunk(64 * 1024, 'A');
  7237. size_t total_sent = 0;
  7238. while (total_sent < MALICIOUS_DATA_SIZE) {
  7239. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7240. auto sent = ::send(cli,
  7241. #ifdef _WIN32
  7242. static_cast<const char *>(chunk.c_str()),
  7243. static_cast<int>(to_send),
  7244. #else
  7245. chunk.c_str(), to_send,
  7246. #endif
  7247. 0);
  7248. if (sent <= 0) break;
  7249. total_sent += static_cast<size_t>(sent);
  7250. }
  7251. detail::close_socket(cli);
  7252. }
  7253. detail::close_socket(srv);
  7254. });
  7255. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7256. size_t total_read = 0;
  7257. {
  7258. Client cli("127.0.0.1", PORT + 2);
  7259. cli.set_read_timeout(5, 0);
  7260. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7261. auto stream = cli.open_stream("GET", "/malicious");
  7262. ASSERT_TRUE(stream.is_valid());
  7263. char buffer[64 * 1024];
  7264. ssize_t n;
  7265. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7266. total_read += static_cast<size_t>(n);
  7267. }
  7268. } // StreamHandle and Client destroyed here, closing the socket
  7269. server_thread.join();
  7270. // With set_payload_max_length, the client must stop reading before consuming
  7271. // all 10MB. The read loop should be cut off at or near the configured limit.
  7272. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7273. << "Client read " << total_read << " bytes, exceeding the configured "
  7274. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7275. }
  7276. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7277. // the entire response body without truncation.
  7278. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7279. constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7280. #ifndef _WIN32
  7281. signal(SIGPIPE, SIG_IGN);
  7282. #endif
  7283. auto server_thread = std::thread([DATA_SIZE] {
  7284. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7285. default_socket_options(srv);
  7286. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7287. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7288. sockaddr_in addr{};
  7289. addr.sin_family = AF_INET;
  7290. addr.sin_port = htons(PORT + 2);
  7291. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7292. int opt = 1;
  7293. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7294. #ifdef _WIN32
  7295. reinterpret_cast<const char *>(&opt),
  7296. #else
  7297. &opt,
  7298. #endif
  7299. sizeof(opt));
  7300. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7301. ::listen(srv, 1);
  7302. sockaddr_in cli_addr{};
  7303. socklen_t cli_len = sizeof(cli_addr);
  7304. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7305. if (cli != INVALID_SOCKET) {
  7306. char buf[4096];
  7307. ::recv(cli, buf, sizeof(buf), 0);
  7308. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7309. "Connection: close\r\n"
  7310. "\r\n";
  7311. ::send(cli,
  7312. #ifdef _WIN32
  7313. static_cast<const char *>(response_header.c_str()),
  7314. static_cast<int>(response_header.size()),
  7315. #else
  7316. response_header.c_str(), response_header.size(),
  7317. #endif
  7318. 0);
  7319. std::string chunk(64 * 1024, 'A');
  7320. size_t total_sent = 0;
  7321. while (total_sent < DATA_SIZE) {
  7322. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7323. auto sent = ::send(cli,
  7324. #ifdef _WIN32
  7325. static_cast<const char *>(chunk.c_str()),
  7326. static_cast<int>(to_send),
  7327. #else
  7328. chunk.c_str(), to_send,
  7329. #endif
  7330. 0);
  7331. if (sent <= 0) break;
  7332. total_sent += static_cast<size_t>(sent);
  7333. }
  7334. detail::close_socket(cli);
  7335. }
  7336. detail::close_socket(srv);
  7337. });
  7338. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7339. size_t total_read = 0;
  7340. {
  7341. Client cli("127.0.0.1", PORT + 2);
  7342. cli.set_read_timeout(5, 0);
  7343. cli.set_payload_max_length(0); // 0 means no limit
  7344. auto stream = cli.open_stream("GET", "/data");
  7345. ASSERT_TRUE(stream.is_valid());
  7346. char buffer[64 * 1024];
  7347. ssize_t n;
  7348. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7349. total_read += static_cast<size_t>(n);
  7350. }
  7351. }
  7352. server_thread.join();
  7353. EXPECT_EQ(total_read, DATA_SIZE)
  7354. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7355. << " bytes without truncation, but only read " << total_read << " bytes.";
  7356. }
  7357. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7358. // Regression test for "zip bomb" attack on the client side: a malicious server
  7359. // sends a small gzip-compressed response that decompresses to a huge payload.
  7360. // The client must enforce payload_max_length on the decompressed size.
  7361. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7362. constexpr size_t DECOMPRESSED_SIZE =
  7363. 10 * 1024 * 1024; // 10MB after decompression
  7364. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7365. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7366. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7367. std::string compressed;
  7368. {
  7369. httplib::detail::gzip_compressor compressor;
  7370. bool ok =
  7371. compressor.compress(uncompressed.data(), uncompressed.size(),
  7372. /*last=*/true, [&](const char *buf, size_t len) {
  7373. compressed.append(buf, len);
  7374. return true;
  7375. });
  7376. ASSERT_TRUE(ok);
  7377. }
  7378. // Sanity: compressed data should be much smaller than the decompressed size
  7379. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7380. #ifndef _WIN32
  7381. signal(SIGPIPE, SIG_IGN);
  7382. #endif
  7383. auto server_thread = std::thread([&compressed] {
  7384. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7385. default_socket_options(srv);
  7386. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7387. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7388. sockaddr_in addr{};
  7389. addr.sin_family = AF_INET;
  7390. addr.sin_port = htons(PORT + 3);
  7391. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7392. int opt = 1;
  7393. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7394. #ifdef _WIN32
  7395. reinterpret_cast<const char *>(&opt),
  7396. #else
  7397. &opt,
  7398. #endif
  7399. sizeof(opt));
  7400. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7401. ::listen(srv, 1);
  7402. sockaddr_in cli_addr{};
  7403. socklen_t cli_len = sizeof(cli_addr);
  7404. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7405. if (cli != INVALID_SOCKET) {
  7406. char buf[4096];
  7407. ::recv(cli, buf, sizeof(buf), 0);
  7408. // Malicious response: gzip-compressed body, no Content-Length
  7409. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7410. "Content-Encoding: gzip\r\n"
  7411. "Connection: close\r\n"
  7412. "\r\n";
  7413. ::send(cli,
  7414. #ifdef _WIN32
  7415. static_cast<const char *>(response_header.c_str()),
  7416. static_cast<int>(response_header.size()),
  7417. #else
  7418. response_header.c_str(), response_header.size(),
  7419. #endif
  7420. 0);
  7421. // Send the compressed payload (small on the wire, huge when decompressed)
  7422. size_t total_sent = 0;
  7423. while (total_sent < compressed.size()) {
  7424. auto to_send = std::min(compressed.size() - total_sent,
  7425. static_cast<size_t>(64 * 1024));
  7426. auto sent =
  7427. ::send(cli,
  7428. #ifdef _WIN32
  7429. static_cast<const char *>(compressed.c_str() + total_sent),
  7430. static_cast<int>(to_send),
  7431. #else
  7432. compressed.c_str() + total_sent, to_send,
  7433. #endif
  7434. 0);
  7435. if (sent <= 0) break;
  7436. total_sent += static_cast<size_t>(sent);
  7437. }
  7438. detail::close_socket(cli);
  7439. }
  7440. detail::close_socket(srv);
  7441. });
  7442. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7443. size_t total_decompressed = 0;
  7444. {
  7445. Client cli("127.0.0.1", PORT + 3);
  7446. cli.set_read_timeout(5, 0);
  7447. cli.set_decompress(true);
  7448. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7449. auto stream = cli.open_stream("GET", "/zipbomb");
  7450. ASSERT_TRUE(stream.is_valid());
  7451. char buffer[64 * 1024];
  7452. ssize_t n;
  7453. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7454. total_decompressed += static_cast<size_t>(n);
  7455. }
  7456. }
  7457. server_thread.join();
  7458. // The decompressed size must be capped by payload_max_length. Without
  7459. // protection, the client would decompress the full 10MB from a tiny
  7460. // compressed payload, enabling a zip bomb DoS attack.
  7461. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7462. << "Client decompressed " << total_decompressed
  7463. << " bytes from a gzip response. The decompressed size should be "
  7464. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7465. }
  7466. #endif
  7467. TEST(HostAndPortPropertiesTest, NoSSL) {
  7468. httplib::Client cli("www.google.com", 1234);
  7469. ASSERT_EQ("www.google.com", cli.host());
  7470. ASSERT_EQ(1234, cli.port());
  7471. }
  7472. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7473. httplib::Client cli("www.google.com:1234");
  7474. ASSERT_EQ("www.google.com", cli.host());
  7475. ASSERT_EQ(1234, cli.port());
  7476. }
  7477. #ifdef CPPHTTPLIB_SSL_ENABLED
  7478. TEST(HostAndPortPropertiesTest, SSL) {
  7479. httplib::SSLClient cli("www.google.com");
  7480. ASSERT_EQ("www.google.com", cli.host());
  7481. ASSERT_EQ(443, cli.port());
  7482. }
  7483. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7484. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7485. std::string cert;
  7486. read_file(CA_CERT_FILE, cert);
  7487. httplib::SSLClient httplib_client("www.google.com");
  7488. // Load CA store first time
  7489. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7490. // Load CA store second time (update)
  7491. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7492. // Verify client is still valid and can make connections
  7493. httplib_client.enable_server_certificate_verification(true);
  7494. auto res = httplib_client.Get("/");
  7495. ASSERT_TRUE(res);
  7496. // Google may return 200 or 301 depending on various factors
  7497. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7498. res->status == StatusCode::MovedPermanently_301);
  7499. }
  7500. TEST(SSLClientTest, ServerNameIndication_Online) {
  7501. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7502. auto host = "httpcan.org";
  7503. auto path = std::string{"/get"};
  7504. #else
  7505. auto host = "nghttp2.org";
  7506. auto path = std::string{"/httpbin/get"};
  7507. #endif
  7508. SSLClient cli(host, 443);
  7509. auto res = cli.Get(path);
  7510. ASSERT_TRUE(res);
  7511. ASSERT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7514. // Use a site that will cause SSL verification failure due to self-signed cert
  7515. SSLClient cli("self-signed.badssl.com", 443);
  7516. cli.enable_server_certificate_verification(true);
  7517. auto res = cli.Get("/");
  7518. ASSERT_TRUE(!res);
  7519. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7520. // Verify backend error is captured for SSLServerVerification
  7521. // This occurs when certificate verification fails
  7522. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7523. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7524. EXPECT_NE(0UL, res.ssl_backend_error());
  7525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7526. // For OpenSSL, ssl_error is 0 for verification errors
  7527. EXPECT_EQ(0, res.ssl_error());
  7528. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7529. res.ssl_backend_error());
  7530. #endif
  7531. }
  7532. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7533. // Use a site where hostname doesn't match the certificate
  7534. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7535. SSLClient cli("wrong.host.badssl.com", 443);
  7536. cli.enable_server_certificate_verification(true);
  7537. cli.enable_server_hostname_verification(true);
  7538. auto res = cli.Get("/");
  7539. ASSERT_TRUE(!res);
  7540. // The error type depends on when hostname verification occurs:
  7541. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7542. // - Mbed TLS: SSLServerVerification (during handshake)
  7543. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7544. res.error() == Error::SSLServerVerification);
  7545. // Verify backend error is captured for hostname verification failure
  7546. EXPECT_NE(0UL, res.ssl_backend_error());
  7547. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7548. // For OpenSSL, ssl_error is 0 for verification errors
  7549. EXPECT_EQ(0, res.ssl_error());
  7550. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7551. res.ssl_backend_error());
  7552. #endif
  7553. }
  7554. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7555. Client cli("https://google.com");
  7556. auto res = cli.Get("/");
  7557. ASSERT_TRUE(res);
  7558. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7559. }
  7560. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7561. SSLClient cli("google.com");
  7562. cli.set_ca_cert_path(CA_CERT_FILE);
  7563. auto res = cli.Get("/");
  7564. ASSERT_TRUE(res);
  7565. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7566. }
  7567. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7568. SSLClient cli("google.com");
  7569. cli.enable_server_certificate_verification(true);
  7570. cli.set_ca_cert_path("hello");
  7571. auto res = cli.Get("/");
  7572. ASSERT_TRUE(!res);
  7573. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7574. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7575. // should be set
  7576. EXPECT_EQ(0, res.ssl_error());
  7577. // Verify backend error is captured for SSLLoadingCerts
  7578. // This error occurs when loading CA certificates fails
  7579. EXPECT_NE(0UL, res.ssl_backend_error());
  7580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7581. // OpenSSL specific error codes:
  7582. // > openssl errstr 0x80000002
  7583. // error:80000002:system library::No such file or directory
  7584. // > openssl errstr 0xA000126
  7585. // error:0A000126:SSL routines::unexpected eof while reading
  7586. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7587. res.ssl_backend_error() == 0xA000126);
  7588. #endif
  7589. }
  7590. TEST(SSLClientTest, ServerCertificateVerification4) {
  7591. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7592. ASSERT_TRUE(svr.is_valid());
  7593. svr.Get("/test", [&](const Request &, Response &res) {
  7594. res.set_content("test", "text/plain");
  7595. svr.stop();
  7596. ASSERT_TRUE(true);
  7597. });
  7598. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7599. auto se = detail::scope_exit([&] {
  7600. t.join();
  7601. ASSERT_FALSE(svr.is_running());
  7602. });
  7603. svr.wait_until_ready();
  7604. SSLClient cli("127.0.0.1", PORT);
  7605. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7606. cli.enable_server_certificate_verification(true);
  7607. cli.set_connection_timeout(30);
  7608. auto res = cli.Get("/test");
  7609. ASSERT_TRUE(res);
  7610. ASSERT_EQ(StatusCode::OK_200, res->status);
  7611. }
  7612. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7613. std::string cert;
  7614. read_file(CA_CERT_FILE, cert);
  7615. SSLClient cli("google.com");
  7616. cli.load_ca_cert_store(cert.data(), cert.size());
  7617. const auto res = cli.Get("/");
  7618. ASSERT_TRUE(res);
  7619. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7620. }
  7621. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7622. // clang-format off
  7623. static constexpr char cert[] =
  7624. "GlobalSign Root CA\n"
  7625. "==================\n"
  7626. "-----BEGIN CERTIFICATE-----\n"
  7627. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7628. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7629. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7630. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7631. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7632. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7633. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7634. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7635. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7636. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7637. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7638. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7639. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7640. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7641. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7642. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7643. "-----END CERTIFICATE-----\n";
  7644. // clang-format on
  7645. SSLClient cli("google.com");
  7646. cli.load_ca_cert_store(cert, sizeof(cert));
  7647. const auto res = cli.Get("/");
  7648. ASSERT_TRUE(res);
  7649. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7650. }
  7651. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7652. SSLClient cli("www.youtube.com");
  7653. cli.set_ca_cert_path(CA_CERT_FILE);
  7654. cli.enable_server_certificate_verification(true);
  7655. cli.set_follow_location(true);
  7656. auto res = cli.Get("/");
  7657. ASSERT_TRUE(res);
  7658. ASSERT_EQ(StatusCode::OK_200, res->status);
  7659. }
  7660. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7661. SSLClient cli("wWw.YouTube.Com");
  7662. cli.set_ca_cert_path(CA_CERT_FILE);
  7663. cli.enable_server_certificate_verification(true);
  7664. cli.enable_server_hostname_verification(true);
  7665. cli.set_follow_location(true);
  7666. auto res = cli.Get("/");
  7667. ASSERT_TRUE(res);
  7668. ASSERT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7671. SSLClient cli("gOoGlE.COm");
  7672. cli.enable_server_certificate_verification(true);
  7673. cli.enable_server_hostname_verification(true);
  7674. cli.set_follow_location(true);
  7675. auto res = cli.Get("/");
  7676. ASSERT_TRUE(res);
  7677. ASSERT_EQ(StatusCode::OK_200, res->status);
  7678. }
  7679. TEST(SSLClientTest, Issue2004_Online) {
  7680. Client client("https://google.com");
  7681. client.set_follow_location(true);
  7682. auto res = client.Get("/");
  7683. ASSERT_TRUE(res);
  7684. ASSERT_EQ(StatusCode::OK_200, res->status);
  7685. auto body = res->body;
  7686. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7687. }
  7688. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7689. // Create SSLClient with invalid cert/key to make is_valid() return false
  7690. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7691. "nonexistent_key.pem");
  7692. // is_valid() should be false due to cert loading failure
  7693. ASSERT_FALSE(cli.is_valid());
  7694. auto res = cli.Get("/");
  7695. ASSERT_FALSE(res);
  7696. EXPECT_EQ(Error::SSLConnection, res.error());
  7697. }
  7698. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7699. // Test for Issue #2251: SSL error not properly reported when client cert
  7700. // and key paths are swapped or mismatched
  7701. // This simulates the scenario where user accidentally swaps the cert and key
  7702. // files
  7703. // Using client cert file as private key and vice versa (completely wrong)
  7704. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7705. // Should fail validation due to cert/key mismatch
  7706. ASSERT_FALSE(cli.is_valid());
  7707. // Attempt to make a request should fail with proper error
  7708. auto res = cli.Get("/");
  7709. ASSERT_FALSE(res);
  7710. EXPECT_EQ(Error::SSLConnection, res.error());
  7711. // SSL error should be recorded in the Result object (this is the key fix for
  7712. // Issue #2251)
  7713. auto backend_error = res.ssl_backend_error();
  7714. EXPECT_NE(0u, backend_error);
  7715. }
  7716. // Tests cert/key mismatch detection at the TLS context level
  7717. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7718. // Test that using mismatched cert/key causes connection failure.
  7719. // We verify this at the SSLClient level rather than through internal
  7720. // TLS API functions.
  7721. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  7722. cli.enable_server_certificate_verification(false);
  7723. cli.set_connection_timeout(2);
  7724. // The mismatch should cause a connection or handshake error
  7725. auto res = cli.Get("/test");
  7726. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  7727. // Either way, the request should fail
  7728. EXPECT_FALSE(res);
  7729. }
  7730. #endif
  7731. #if 0
  7732. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7733. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7734. ASSERT_TRUE(cli != nullptr);
  7735. cli->set_address_family(AF_INET6);
  7736. cli->set_interface("en0");
  7737. auto res = cli->Get("/get");
  7738. ASSERT_TRUE(res);
  7739. ASSERT_EQ(StatusCode::OK_200, res->status);
  7740. }
  7741. #endif
  7742. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  7743. #ifdef CPPHTTPLIB_SSL_ENABLED
  7744. void ClientCertPresent(
  7745. const std::string &client_cert_file,
  7746. const std::string &client_private_key_file,
  7747. const std::string &client_encrypted_private_key_pass = std::string()) {
  7748. using namespace httplib::tls;
  7749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7750. CLIENT_CA_CERT_DIR);
  7751. ASSERT_TRUE(svr.is_valid());
  7752. svr.Get("/test", [&](const Request &req, Response &res) {
  7753. res.set_content("test", "text/plain");
  7754. auto cert = req.peer_cert();
  7755. ASSERT_TRUE(static_cast<bool>(cert));
  7756. std::string common_name = cert.subject_cn();
  7757. EXPECT_EQ("Common Name", common_name);
  7758. });
  7759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7760. auto se = detail::scope_exit([&] {
  7761. svr.stop();
  7762. t.join();
  7763. ASSERT_FALSE(svr.is_running());
  7764. });
  7765. svr.wait_until_ready();
  7766. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7767. client_encrypted_private_key_pass);
  7768. cli.enable_server_certificate_verification(false);
  7769. cli.set_connection_timeout(30);
  7770. auto res = cli.Get("/test");
  7771. ASSERT_TRUE(res);
  7772. ASSERT_EQ(StatusCode::OK_200, res->status);
  7773. }
  7774. TEST(SSLClientServerTest, ClientCertPresent) {
  7775. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7776. }
  7777. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7778. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7779. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7780. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7781. }
  7782. // PEM memory-based constructor tests (works with all TLS backends)
  7783. void PemMemoryClientCertPresent(
  7784. const std::string &client_cert_file,
  7785. const std::string &client_private_key_file,
  7786. const std::string &client_encrypted_private_key_pass = std::string()) {
  7787. // Read PEM files into memory
  7788. std::string server_cert_pem, server_key_pem;
  7789. std::string client_ca_pem;
  7790. std::string client_cert_pem, client_key_pem;
  7791. read_file(SERVER_CERT_FILE, server_cert_pem);
  7792. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7793. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7794. read_file(client_cert_file, client_cert_pem);
  7795. read_file(client_private_key_file, client_key_pem);
  7796. // Create server with PEM memory
  7797. SSLServer::PemMemory server_pem = {
  7798. server_cert_pem.c_str(),
  7799. server_cert_pem.size(),
  7800. server_key_pem.c_str(),
  7801. server_key_pem.size(),
  7802. client_ca_pem.c_str(),
  7803. client_ca_pem.size(),
  7804. nullptr // no password for server key
  7805. };
  7806. SSLServer svr(server_pem);
  7807. ASSERT_TRUE(svr.is_valid());
  7808. svr.Get("/test", [&](const Request &, Response &res) {
  7809. res.set_content("test", "text/plain");
  7810. });
  7811. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7812. auto se = detail::scope_exit([&] {
  7813. svr.stop();
  7814. t.join();
  7815. ASSERT_FALSE(svr.is_running());
  7816. });
  7817. svr.wait_until_ready();
  7818. // Create client with PEM memory
  7819. const char *password = client_encrypted_private_key_pass.empty()
  7820. ? nullptr
  7821. : client_encrypted_private_key_pass.c_str();
  7822. SSLClient::PemMemory client_pem = {
  7823. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7824. client_key_pem.size(), password};
  7825. SSLClient cli(HOST, PORT, client_pem);
  7826. cli.enable_server_certificate_verification(false);
  7827. cli.set_connection_timeout(30);
  7828. auto res = cli.Get("/test");
  7829. ASSERT_TRUE(res);
  7830. ASSERT_EQ(StatusCode::OK_200, res->status);
  7831. }
  7832. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7833. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7834. }
  7835. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7836. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7837. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7838. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7839. }
  7840. TEST(SSLClientServerTest, ClientCertMissing) {
  7841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7842. CLIENT_CA_CERT_DIR);
  7843. ASSERT_TRUE(svr.is_valid());
  7844. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7846. auto se = detail::scope_exit([&] {
  7847. svr.stop();
  7848. t.join();
  7849. ASSERT_FALSE(svr.is_running());
  7850. });
  7851. svr.wait_until_ready();
  7852. SSLClient cli(HOST, PORT);
  7853. cli.set_connection_timeout(30);
  7854. auto res = cli.Get("/test");
  7855. ASSERT_TRUE(!res);
  7856. // When client cert is missing and server requires it, connection fails
  7857. // Error type depends on backend implementation
  7858. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7859. res.error() == Error::SSLConnection);
  7860. // Verify backend error is captured
  7861. // Note: This test may have different error codes depending on the exact
  7862. // verification failure
  7863. EXPECT_NE(0UL, res.ssl_backend_error());
  7864. }
  7865. TEST(SSLClientServerTest, TrustDirOptional) {
  7866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7867. ASSERT_TRUE(svr.is_valid());
  7868. svr.Get("/test", [&](const Request &, Response &res) {
  7869. res.set_content("test", "text/plain");
  7870. });
  7871. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7872. auto se = detail::scope_exit([&] {
  7873. svr.stop();
  7874. t.join();
  7875. ASSERT_FALSE(svr.is_running());
  7876. });
  7877. svr.wait_until_ready();
  7878. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7879. cli.enable_server_certificate_verification(false);
  7880. cli.set_connection_timeout(30);
  7881. auto res = cli.Get("/test");
  7882. ASSERT_TRUE(res);
  7883. ASSERT_EQ(StatusCode::OK_200, res->status);
  7884. }
  7885. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7886. class NoListenSSLServer : public SSLServer {
  7887. public:
  7888. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7889. const char *client_ca_cert_file_path,
  7890. const char *client_ca_cert_dir_path = nullptr)
  7891. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7892. client_ca_cert_dir_path),
  7893. stop_(false) {}
  7894. std::atomic_bool stop_;
  7895. private:
  7896. bool process_and_close_socket(socket_t /*sock*/) override {
  7897. // Don't create SSL context
  7898. while (!stop_.load()) {
  7899. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7900. }
  7901. return true;
  7902. }
  7903. };
  7904. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7905. CLIENT_CA_CERT_FILE);
  7906. ASSERT_TRUE(svr.is_valid());
  7907. svr.Get("/test", [&](const Request &, Response &res) {
  7908. res.set_content("test", "text/plain");
  7909. });
  7910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7911. auto se = detail::scope_exit([&] {
  7912. svr.stop_ = true;
  7913. svr.stop();
  7914. t.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7919. cli.enable_server_certificate_verification(false);
  7920. cli.set_connection_timeout(1);
  7921. auto res = cli.Get("/test");
  7922. ASSERT_TRUE(!res);
  7923. EXPECT_EQ(Error::SSLConnection, res.error());
  7924. // Timeout results in WantRead error code (maps to backend-specific value)
  7925. EXPECT_NE(0, res.ssl_error());
  7926. }
  7927. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7928. // Test SSLServer with client certificate verification using the standard
  7929. // constructor (ContextSetupCallback is tested by backend-specific tests)
  7930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7931. CLIENT_CA_CERT_DIR);
  7932. ASSERT_TRUE(svr.is_valid());
  7933. svr.Get("/test", [&](const Request &req, Response &res) {
  7934. res.set_content("test", "text/plain");
  7935. auto cert = req.peer_cert();
  7936. ASSERT_TRUE(static_cast<bool>(cert));
  7937. auto common_name = cert.subject_cn();
  7938. EXPECT_EQ("Common Name", common_name);
  7939. });
  7940. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7941. auto se = detail::scope_exit([&] {
  7942. svr.stop();
  7943. t.join();
  7944. ASSERT_FALSE(svr.is_running());
  7945. });
  7946. svr.wait_until_ready();
  7947. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7948. cli.enable_server_certificate_verification(false);
  7949. cli.set_connection_timeout(30);
  7950. auto res = cli.Get("/test");
  7951. ASSERT_TRUE(res);
  7952. ASSERT_EQ(StatusCode::OK_200, res->status);
  7953. }
  7954. // Test verify_hostname for both OpenSSL and MbedTLS backends
  7955. // Verifies that wildcard matching and exact matching work consistently
  7956. TEST(SSLClientServerTest, TlsVerifyHostname) {
  7957. using namespace httplib::tls;
  7958. // We need a running server to test against
  7959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7960. ASSERT_TRUE(svr.is_valid());
  7961. svr.Get("/test", [](const Request &, Response &res) {
  7962. res.set_content("ok", "text/plain");
  7963. });
  7964. thread t([&]() { svr.listen(HOST, PORT); });
  7965. auto se = detail::scope_exit([&] {
  7966. svr.stop();
  7967. t.join();
  7968. });
  7969. svr.wait_until_ready();
  7970. bool verify_callback_called = false;
  7971. bool verify_result_wrong = false;
  7972. SSLClient cli(HOST, PORT);
  7973. cli.enable_server_certificate_verification(true);
  7974. cli.set_ca_cert_path(CA_CERT_FILE);
  7975. cli.set_connection_timeout(5);
  7976. // Note: Test certificate has CN="Common Name", not "localhost"
  7977. bool verify_result_cn = false;
  7978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7979. verify_callback_called = true;
  7980. if (!ctx.cert) return false;
  7981. // Test 1: "Common Name" should match (our test server cert CN)
  7982. verify_result_cn = ctx.check_hostname("Common Name");
  7983. // Test 2: wrong hostname should not match
  7984. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  7985. return true; // Accept for the purpose of this test
  7986. });
  7987. auto res = cli.Get("/test");
  7988. // The request may succeed or fail depending on cert configuration
  7989. // but the callback should have been called
  7990. ASSERT_TRUE(verify_callback_called)
  7991. << "Verify callback should have been called";
  7992. // CN="Common Name" should match our test certificate
  7993. EXPECT_TRUE(verify_result_cn)
  7994. << "verify_hostname should match 'Common Name' (certificate CN)";
  7995. // Wrong hostname should not match
  7996. EXPECT_FALSE(verify_result_wrong)
  7997. << "verify_hostname should not match 'wronghost.example.com'";
  7998. }
  7999. #endif
  8000. // mbedTLS-specific callback constructor test
  8001. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8002. #ifdef CPPHTTPLIB_SSL_ENABLED
  8003. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8005. ASSERT_TRUE(svr.is_valid());
  8006. // Set up a handler to verify client certificate is present
  8007. bool client_cert_verified = false;
  8008. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8009. // Verify that client certificate was provided
  8010. client_cert_verified = true;
  8011. res.set_content("success", "text/plain");
  8012. });
  8013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8014. auto se = detail::scope_exit([&] {
  8015. svr.stop();
  8016. t.join();
  8017. ASSERT_FALSE(svr.is_running());
  8018. });
  8019. svr.wait_until_ready();
  8020. // Client with certificate
  8021. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8022. cli.enable_server_certificate_verification(false);
  8023. cli.set_connection_timeout(30);
  8024. auto res = cli.Get("/test");
  8025. ASSERT_TRUE(res);
  8026. ASSERT_EQ(StatusCode::OK_200, res->status);
  8027. ASSERT_TRUE(client_cert_verified);
  8028. EXPECT_EQ("success", res->body);
  8029. }
  8030. #endif
  8031. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8032. // backends
  8033. #ifdef CPPHTTPLIB_SSL_ENABLED
  8034. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8035. using namespace httplib::tls;
  8036. // Test that when client CA cert file is provided,
  8037. // the server properly requests and validates client certificates
  8038. // Create a server with client authentication
  8039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8040. ASSERT_TRUE(svr.is_valid());
  8041. bool handler_called = false;
  8042. svr.Get("/test", [&](const Request &req, Response &res) {
  8043. handler_called = true;
  8044. // Verify that a client certificate was provided
  8045. auto cert = req.peer_cert();
  8046. ASSERT_TRUE(static_cast<bool>(cert));
  8047. // Get the issuer name
  8048. std::string issuer_str = cert.issuer_name();
  8049. ASSERT_FALSE(issuer_str.empty());
  8050. // The client certificate should be issued by our test CA
  8051. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8052. res.set_content("authenticated", "text/plain");
  8053. });
  8054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8055. auto se = detail::scope_exit([&] {
  8056. svr.stop();
  8057. t.join();
  8058. ASSERT_FALSE(svr.is_running());
  8059. });
  8060. svr.wait_until_ready();
  8061. // Connect with a client certificate issued by the CA
  8062. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8063. cli.enable_server_certificate_verification(false);
  8064. cli.set_connection_timeout(30);
  8065. auto res = cli.Get("/test");
  8066. ASSERT_TRUE(res);
  8067. ASSERT_EQ(StatusCode::OK_200, res->status);
  8068. ASSERT_TRUE(handler_called);
  8069. EXPECT_EQ("authenticated", res->body);
  8070. }
  8071. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8072. using namespace httplib::tls;
  8073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8074. ASSERT_TRUE(svr.is_valid());
  8075. svr.Get("/test", [](const Request &, Response &res) {
  8076. res.set_content("ok", "text/plain");
  8077. });
  8078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8079. auto se = detail::scope_exit([&] {
  8080. svr.stop();
  8081. t.join();
  8082. });
  8083. svr.wait_until_ready();
  8084. SSLClient cli(HOST, PORT);
  8085. cli.enable_server_certificate_verification(false);
  8086. cli.set_connection_timeout(30);
  8087. bool cert_checked = false;
  8088. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8089. if (ctx.cert) {
  8090. auto sans = ctx.sans();
  8091. // Test certificate may or may not have SANs - just verify the API
  8092. // works If SANs exist, verify the types are valid
  8093. for (const auto &san : sans) {
  8094. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8095. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8096. san.type == SanType::OTHER);
  8097. EXPECT_FALSE(san.value.empty());
  8098. }
  8099. cert_checked = true;
  8100. }
  8101. return true;
  8102. });
  8103. auto res = cli.Get("/test");
  8104. ASSERT_TRUE(res);
  8105. EXPECT_TRUE(cert_checked);
  8106. }
  8107. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8108. using namespace httplib::tls;
  8109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8110. ASSERT_TRUE(svr.is_valid());
  8111. svr.Get("/test", [](const Request &, Response &res) {
  8112. res.set_content("ok", "text/plain");
  8113. });
  8114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8115. auto se = detail::scope_exit([&] {
  8116. svr.stop();
  8117. t.join();
  8118. });
  8119. svr.wait_until_ready();
  8120. SSLClient cli(HOST, PORT);
  8121. cli.enable_server_certificate_verification(false);
  8122. cli.set_connection_timeout(30);
  8123. bool validity_checked = false;
  8124. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8125. if (ctx.cert) {
  8126. time_t not_before = 0, not_after = 0;
  8127. bool result = ctx.validity(not_before, not_after);
  8128. EXPECT_TRUE(result);
  8129. // Verify that not_before < now < not_after for a valid cert
  8130. time_t now = time(nullptr);
  8131. EXPECT_LT(not_before, now);
  8132. EXPECT_GT(not_after, now);
  8133. validity_checked = true;
  8134. }
  8135. return true;
  8136. });
  8137. auto res = cli.Get("/test");
  8138. ASSERT_TRUE(res);
  8139. EXPECT_TRUE(validity_checked);
  8140. }
  8141. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8142. using namespace httplib::tls;
  8143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8144. ASSERT_TRUE(svr.is_valid());
  8145. svr.Get("/test", [](const Request &, Response &res) {
  8146. res.set_content("ok", "text/plain");
  8147. });
  8148. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8149. auto se = detail::scope_exit([&] {
  8150. svr.stop();
  8151. t.join();
  8152. });
  8153. svr.wait_until_ready();
  8154. SSLClient cli(HOST, PORT);
  8155. cli.enable_server_certificate_verification(false);
  8156. cli.set_connection_timeout(30);
  8157. bool serial_checked = false;
  8158. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8159. if (ctx.cert) {
  8160. std::string serial = ctx.serial();
  8161. EXPECT_FALSE(serial.empty());
  8162. // Serial should be a hex string
  8163. for (char c : serial) {
  8164. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8165. (c >= 'a' && c <= 'f'));
  8166. }
  8167. serial_checked = true;
  8168. }
  8169. return true;
  8170. });
  8171. auto res = cli.Get("/test");
  8172. ASSERT_TRUE(res);
  8173. EXPECT_TRUE(serial_checked);
  8174. }
  8175. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8176. // Test 1: Valid CA file - no error should be recorded
  8177. {
  8178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8179. CLIENT_CA_CERT_FILE);
  8180. ASSERT_TRUE(svr.is_valid());
  8181. // With valid setup, last_ssl_error should be 0
  8182. EXPECT_EQ(0, svr.ssl_last_error());
  8183. }
  8184. // Test 2: Invalid CA file content
  8185. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8186. {
  8187. // Create a temporary file with completely invalid content
  8188. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8189. {
  8190. std::ofstream ofs(temp_invalid_ca);
  8191. ofs << "This is not a certificate file at all\n";
  8192. ofs << "Just plain text content\n";
  8193. }
  8194. // Create server with invalid CA file
  8195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8196. // Clean up temporary file
  8197. std::remove(temp_invalid_ca);
  8198. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8199. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8200. // Note: SSL_CTX_load_verify_locations typically fails first,
  8201. // but our error handling code path is still exercised
  8202. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8203. }
  8204. }
  8205. TEST(VerifyCallbackTest, VerifyContextFields) {
  8206. using namespace httplib::tls;
  8207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8208. ASSERT_TRUE(svr.is_valid());
  8209. svr.Get("/test", [](const Request &, Response &res) {
  8210. res.set_content("ok", "text/plain");
  8211. });
  8212. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8213. auto se = detail::scope_exit([&] {
  8214. svr.stop();
  8215. t.join();
  8216. });
  8217. svr.wait_until_ready();
  8218. SSLClient cli(HOST, PORT);
  8219. cli.enable_server_certificate_verification(false);
  8220. cli.set_connection_timeout(30);
  8221. int callback_count = 0;
  8222. bool saw_leaf_cert = false;
  8223. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8224. if (ctx.cert) {
  8225. callback_count++;
  8226. // We should see at least one certificate (the leaf)
  8227. std::string cn = ctx.subject_cn();
  8228. if (!cn.empty()) { saw_leaf_cert = true; }
  8229. // Verify context fields are populated
  8230. EXPECT_NE(ctx.session, nullptr);
  8231. EXPECT_GE(ctx.depth, 0);
  8232. }
  8233. return true;
  8234. });
  8235. auto res = cli.Get("/test");
  8236. ASSERT_TRUE(res);
  8237. EXPECT_GT(callback_count, 0);
  8238. EXPECT_TRUE(saw_leaf_cert);
  8239. }
  8240. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8241. using httplib::tls::TlsError;
  8242. // Test that verify_error_to_string returns empty for success
  8243. std::string success_str = TlsError::verify_error_to_string(0);
  8244. EXPECT_TRUE(success_str.empty());
  8245. // Test that verify_error_to_string returns non-empty for error codes
  8246. // Using a common error code (certificate expired)
  8247. std::string error_str =
  8248. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8249. EXPECT_FALSE(error_str.empty());
  8250. }
  8251. TEST(SessionVerifierTest, CertificateAccepted) {
  8252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8253. ASSERT_TRUE(svr.is_valid());
  8254. svr.Get("/test", [](const Request &, Response &res) {
  8255. res.set_content("ok", "text/plain");
  8256. });
  8257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. t.join();
  8261. });
  8262. svr.wait_until_ready();
  8263. SSLClient cli(HOST, PORT);
  8264. cli.enable_server_certificate_verification(false);
  8265. cli.set_connection_timeout(30);
  8266. bool callback_called = false;
  8267. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8268. EXPECT_NE(session, nullptr);
  8269. callback_called = true;
  8270. return SSLVerifierResponse::CertificateAccepted;
  8271. });
  8272. auto res = cli.Get("/test");
  8273. ASSERT_TRUE(res);
  8274. EXPECT_EQ(200, res->status);
  8275. EXPECT_TRUE(callback_called);
  8276. }
  8277. TEST(SessionVerifierTest, CertificateRejected) {
  8278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8279. ASSERT_TRUE(svr.is_valid());
  8280. svr.Get("/test", [](const Request &, Response &res) {
  8281. res.set_content("ok", "text/plain");
  8282. });
  8283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8284. auto se = detail::scope_exit([&] {
  8285. svr.stop();
  8286. t.join();
  8287. });
  8288. svr.wait_until_ready();
  8289. SSLClient cli(HOST, PORT);
  8290. cli.enable_server_certificate_verification(false);
  8291. cli.set_connection_timeout(30);
  8292. bool callback_called = false;
  8293. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8294. EXPECT_NE(session, nullptr);
  8295. callback_called = true;
  8296. return SSLVerifierResponse::CertificateRejected;
  8297. });
  8298. auto res = cli.Get("/test");
  8299. EXPECT_FALSE(res);
  8300. EXPECT_TRUE(callback_called);
  8301. }
  8302. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8304. ASSERT_TRUE(svr.is_valid());
  8305. svr.Get("/test", [](const Request &, Response &res) {
  8306. res.set_content("ok", "text/plain");
  8307. });
  8308. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8309. auto se = detail::scope_exit([&] {
  8310. svr.stop();
  8311. t.join();
  8312. });
  8313. svr.wait_until_ready();
  8314. // NoDecisionMade with verification disabled should succeed (no default check)
  8315. SSLClient cli(HOST, PORT);
  8316. cli.enable_server_certificate_verification(false);
  8317. cli.set_connection_timeout(30);
  8318. bool callback_called = false;
  8319. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8320. EXPECT_NE(session, nullptr);
  8321. callback_called = true;
  8322. return SSLVerifierResponse::NoDecisionMade;
  8323. });
  8324. auto res = cli.Get("/test");
  8325. ASSERT_TRUE(res);
  8326. EXPECT_EQ(200, res->status);
  8327. EXPECT_TRUE(callback_called);
  8328. }
  8329. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8331. ASSERT_TRUE(svr.is_valid());
  8332. svr.Get("/test", [](const Request &, Response &res) {
  8333. res.set_content("ok", "text/plain");
  8334. });
  8335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8336. auto se = detail::scope_exit([&] {
  8337. svr.stop();
  8338. t.join();
  8339. });
  8340. svr.wait_until_ready();
  8341. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8342. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8343. // so we only check that the request fails, not whether the callback was
  8344. // called.
  8345. SSLClient cli(HOST, PORT);
  8346. cli.enable_server_certificate_verification(true);
  8347. cli.set_connection_timeout(30);
  8348. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8349. EXPECT_NE(session, nullptr);
  8350. return SSLVerifierResponse::NoDecisionMade;
  8351. });
  8352. auto res = cli.Get("/test");
  8353. EXPECT_FALSE(res);
  8354. }
  8355. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8356. // Test SSL server using PemMemory constructor with client CA certificates
  8357. // Read PEM files
  8358. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8359. read_file(SERVER_CERT_FILE, server_cert_pem);
  8360. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8361. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8362. // Create SSLServer with PemMemory constructor including client CA
  8363. SSLServer::PemMemory server_pem = {
  8364. server_cert_pem.c_str(),
  8365. server_cert_pem.size(),
  8366. server_key_pem.c_str(),
  8367. server_key_pem.size(),
  8368. client_ca_pem.c_str(),
  8369. client_ca_pem.size(),
  8370. nullptr // no password for server key
  8371. };
  8372. SSLServer svr(server_pem);
  8373. ASSERT_TRUE(svr.is_valid());
  8374. // No SSL error should be recorded for valid setup
  8375. EXPECT_EQ(0, svr.ssl_last_error());
  8376. // Set up server endpoints
  8377. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8378. res.set_content("ok", "text/plain");
  8379. });
  8380. // Start server in a thread
  8381. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8382. svr.wait_until_ready();
  8383. // Connect with client certificate (using constructor with paths)
  8384. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8385. cli.enable_server_certificate_verification(false);
  8386. auto res = cli.Get("/test-pem-ca");
  8387. ASSERT_TRUE(res);
  8388. EXPECT_EQ(200, res->status);
  8389. EXPECT_EQ("ok", res->body);
  8390. svr.stop();
  8391. server_thread.join();
  8392. }
  8393. #endif
  8394. #ifdef _WIN32
  8395. TEST(CleanupTest, WSACleanup) {
  8396. int ret = WSACleanup();
  8397. ASSERT_EQ(0, ret);
  8398. }
  8399. #endif
  8400. #ifndef CPPHTTPLIB_SSL_ENABLED
  8401. TEST(NoSSLSupport, SimpleInterface) {
  8402. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8403. }
  8404. #endif
  8405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8406. TEST(InvalidScheme, SimpleInterface) {
  8407. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8408. }
  8409. #endif
  8410. TEST(NoScheme, SimpleInterface) {
  8411. Client cli("yahoo.com:80");
  8412. ASSERT_TRUE(cli.is_valid());
  8413. }
  8414. TEST(SendAPI, SimpleInterface_Online) {
  8415. Client cli("http://yahoo.com");
  8416. Request req;
  8417. req.method = "GET";
  8418. req.path = "/";
  8419. auto res = cli.send(req);
  8420. ASSERT_TRUE(res);
  8421. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8422. }
  8423. TEST(SendAPI, WithParamsInRequest) {
  8424. Server svr;
  8425. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8426. EXPECT_TRUE(req.has_param("test"));
  8427. EXPECT_EQ("test_value", req.get_param_value("test"));
  8428. });
  8429. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8430. auto se = detail::scope_exit([&] {
  8431. svr.stop();
  8432. t.join();
  8433. ASSERT_FALSE(svr.is_running());
  8434. });
  8435. svr.wait_until_ready();
  8436. Client cli(HOST, PORT);
  8437. {
  8438. Request req;
  8439. req.method = "GET";
  8440. req.path = "/";
  8441. req.params.emplace("test", "test_value");
  8442. auto res = cli.send(req);
  8443. ASSERT_TRUE(res);
  8444. }
  8445. {
  8446. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8447. ASSERT_TRUE(res);
  8448. }
  8449. }
  8450. TEST(ClientImplMethods, GetSocketTest) {
  8451. httplib::Server svr;
  8452. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8453. res.status = StatusCode::OK_200;
  8454. });
  8455. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8456. auto se = detail::scope_exit([&] {
  8457. svr.stop();
  8458. thread.join();
  8459. ASSERT_FALSE(svr.is_running());
  8460. });
  8461. svr.wait_until_ready();
  8462. {
  8463. httplib::Client cli("http://127.0.0.1:3333");
  8464. cli.set_keep_alive(true);
  8465. // Use the behavior of cpp-httplib of opening the connection
  8466. // only when the first request happens. If that changes,
  8467. // this test would be obsolete.
  8468. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8469. // This also implicitly tests the server. But other tests would fail much
  8470. // earlier than this one to be considered.
  8471. auto res = cli.Get("/");
  8472. ASSERT_TRUE(res);
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8475. }
  8476. }
  8477. // Disabled due to out-of-memory problem on GitHub Actions
  8478. #ifdef _WIN64
  8479. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8480. // allocate content size larger than 2GB in memory
  8481. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8482. char *content = (char *)malloc(content_size);
  8483. ASSERT_TRUE(content);
  8484. Server svr;
  8485. svr.Get("/foo",
  8486. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8487. res.set_content(content, content_size, "application/octet-stream");
  8488. });
  8489. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8490. auto se = detail::scope_exit([&] {
  8491. svr.stop();
  8492. listen_thread.join();
  8493. if (content) free(content);
  8494. ASSERT_FALSE(svr.is_running());
  8495. });
  8496. svr.wait_until_ready();
  8497. Client cli(HOST, PORT);
  8498. auto res = cli.Get("/foo");
  8499. ASSERT_TRUE(res);
  8500. EXPECT_EQ(StatusCode::OK_200, res->status);
  8501. EXPECT_EQ(content_size, res->body.length());
  8502. }
  8503. #endif
  8504. #ifdef CPPHTTPLIB_SSL_ENABLED
  8505. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8506. Client cli("http://yahoo.com");
  8507. auto res = cli.Get("/");
  8508. ASSERT_TRUE(res);
  8509. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8510. cli.set_follow_location(true);
  8511. res = cli.Get("/");
  8512. ASSERT_TRUE(res);
  8513. EXPECT_EQ(StatusCode::OK_200, res->status);
  8514. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8515. }
  8516. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8517. Client cli("https://yahoo.com");
  8518. auto res = cli.Get("/");
  8519. ASSERT_TRUE(res);
  8520. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8521. cli.set_follow_location(true);
  8522. res = cli.Get("/");
  8523. ASSERT_TRUE(res);
  8524. EXPECT_EQ(StatusCode::OK_200, res->status);
  8525. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8526. }
  8527. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8528. Client cli("https://yahoo.com");
  8529. auto res = cli.Get("/");
  8530. ASSERT_TRUE(res);
  8531. ASSERT_FALSE(!res);
  8532. ASSERT_TRUE(res);
  8533. ASSERT_FALSE(res == nullptr);
  8534. ASSERT_TRUE(res != nullptr);
  8535. EXPECT_EQ(Error::Success, res.error());
  8536. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8537. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8538. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8539. cli.set_follow_location(true);
  8540. res = cli.Get("/");
  8541. ASSERT_TRUE(res);
  8542. EXPECT_EQ(Error::Success, res.error());
  8543. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8544. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8545. EXPECT_EQ(StatusCode::OK_200, res->status);
  8546. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8547. }
  8548. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8549. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8550. Client cli("https://cdnjs.cloudflare.com");
  8551. auto res =
  8552. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8553. ASSERT_TRUE(res);
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. EXPECT_EQ(287630U, res->body.size());
  8556. EXPECT_EQ("application/javascript; charset=utf-8",
  8557. res->get_header_value("Content-Type"));
  8558. }
  8559. #endif
  8560. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8561. #undef REDIR_HOST // Silence compiler warning
  8562. #define REDIR_HOST "https://httpbingo.org"
  8563. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8564. Client cli(REDIR_HOST);
  8565. cli.set_follow_location(true);
  8566. auto res =
  8567. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8568. ASSERT_TRUE(res);
  8569. EXPECT_EQ(StatusCode::OK_200, res->status);
  8570. }
  8571. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8572. Client cli(REDIR_HOST);
  8573. cli.set_follow_location(true);
  8574. Params params;
  8575. params.emplace("url", "http://example.com");
  8576. params.emplace("status_code", "302");
  8577. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8578. ASSERT_TRUE(res);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8582. Client cli(REDIR_HOST);
  8583. cli.set_follow_location(true);
  8584. Params params;
  8585. params.emplace("url", "http://example.com");
  8586. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8587. ASSERT_TRUE(res);
  8588. EXPECT_EQ(StatusCode::OK_200, res->status);
  8589. }
  8590. TEST(HttpToHttpsRedirectTest, CertFile) {
  8591. Server svr;
  8592. ASSERT_TRUE(svr.is_valid());
  8593. svr.Get("/index", [&](const Request &, Response &res) {
  8594. res.set_redirect("https://127.0.0.1:1235/index");
  8595. svr.stop();
  8596. });
  8597. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8598. ASSERT_TRUE(ssl_svr.is_valid());
  8599. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8600. res.set_content("test", "text/plain");
  8601. ssl_svr.stop();
  8602. });
  8603. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8604. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8605. auto se = detail::scope_exit([&] {
  8606. t2.join();
  8607. t.join();
  8608. ASSERT_FALSE(svr.is_running());
  8609. });
  8610. svr.wait_until_ready();
  8611. ssl_svr.wait_until_ready();
  8612. Client cli("127.0.0.1", PORT);
  8613. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8614. cli.enable_server_certificate_verification(true);
  8615. cli.set_follow_location(true);
  8616. cli.set_connection_timeout(30);
  8617. auto res = cli.Get("/index");
  8618. ASSERT_TRUE(res);
  8619. ASSERT_EQ(StatusCode::OK_200, res->status);
  8620. }
  8621. TEST(SSLClientRedirectTest, CertFile) {
  8622. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8623. ASSERT_TRUE(ssl_svr1.is_valid());
  8624. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8625. res.set_redirect("https://127.0.0.1:1235/index");
  8626. ssl_svr1.stop();
  8627. });
  8628. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8629. ASSERT_TRUE(ssl_svr2.is_valid());
  8630. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8631. res.set_content("test", "text/plain");
  8632. ssl_svr2.stop();
  8633. });
  8634. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8635. thread t2 =
  8636. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8637. auto se = detail::scope_exit([&] {
  8638. t2.join();
  8639. t.join();
  8640. ASSERT_FALSE(ssl_svr1.is_running());
  8641. });
  8642. ssl_svr1.wait_until_ready();
  8643. ssl_svr2.wait_until_ready();
  8644. SSLClient cli("127.0.0.1", PORT);
  8645. std::string cert;
  8646. read_file(SERVER_CERT2_FILE, cert);
  8647. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8648. cli.enable_server_certificate_verification(true);
  8649. cli.set_follow_location(true);
  8650. cli.set_connection_timeout(30);
  8651. auto res = cli.Get("/index");
  8652. ASSERT_TRUE(res);
  8653. ASSERT_EQ(StatusCode::OK_200, res->status);
  8654. }
  8655. #endif
  8656. #ifdef CPPHTTPLIB_SSL_ENABLED
  8657. // Test that set_ca_cert_store() skips system certs (consistent with
  8658. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8659. // should be trusted - system certs should NOT be loaded.
  8660. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8661. // Load a specific cert that is NOT a system CA cert
  8662. std::string cert;
  8663. read_file(SERVER_CERT2_FILE, cert);
  8664. SSLClient cli("google.com");
  8665. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8666. cli.enable_server_certificate_verification(true);
  8667. // This should FAIL because:
  8668. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8669. // 2. System certs should NOT be loaded when custom store is set
  8670. // If system certs WERE loaded, this would succeed
  8671. auto res = cli.Get("/");
  8672. ASSERT_FALSE(res);
  8673. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8674. }
  8675. TEST(MultipartFormDataTest, LargeData) {
  8676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8677. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8678. const ContentReader &content_reader) {
  8679. if (req.is_multipart_form_data()) {
  8680. std::vector<FormData> items;
  8681. content_reader(
  8682. [&](const FormData &file) {
  8683. items.push_back(file);
  8684. return true;
  8685. },
  8686. [&](const char *data, size_t data_length) {
  8687. items.back().content.append(data, data_length);
  8688. return true;
  8689. });
  8690. EXPECT_TRUE(std::string(items[0].name) == "document");
  8691. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8692. EXPECT_TRUE(items[0].filename == "2MB_data");
  8693. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8694. EXPECT_TRUE(items[1].name == "hello");
  8695. EXPECT_TRUE(items[1].content == "world");
  8696. EXPECT_TRUE(items[1].filename == "");
  8697. EXPECT_TRUE(items[1].content_type == "");
  8698. } else {
  8699. std::string body;
  8700. content_reader([&](const char *data, size_t data_length) {
  8701. body.append(data, data_length);
  8702. return true;
  8703. });
  8704. }
  8705. });
  8706. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8707. auto se = detail::scope_exit([&] {
  8708. svr.stop();
  8709. t.join();
  8710. ASSERT_FALSE(svr.is_running());
  8711. });
  8712. svr.wait_until_ready();
  8713. {
  8714. std::string data(1024 * 1024 * 2, '.');
  8715. std::stringstream buffer;
  8716. buffer << data;
  8717. Client cli("https://localhost:8080");
  8718. cli.enable_server_certificate_verification(false);
  8719. UploadFormDataItems items{
  8720. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8721. {"hello", "world", "", ""},
  8722. };
  8723. auto res = cli.Post("/post", items);
  8724. ASSERT_TRUE(res);
  8725. ASSERT_EQ(StatusCode::OK_200, res->status);
  8726. }
  8727. }
  8728. TEST(MultipartFormDataTest, DataProviderItems) {
  8729. std::random_device seed_gen;
  8730. std::mt19937 random(seed_gen());
  8731. std::string rand1;
  8732. rand1.resize(1000);
  8733. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8734. std::string rand2;
  8735. rand2.resize(3000);
  8736. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8738. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8739. const ContentReader &content_reader) {
  8740. ASSERT_FALSE(req.is_multipart_form_data());
  8741. std::string body;
  8742. content_reader([&](const char *data, size_t data_length) {
  8743. body.append(data, data_length);
  8744. return true;
  8745. });
  8746. EXPECT_EQ(body, "");
  8747. });
  8748. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8749. const ContentReader &content_reader) {
  8750. ASSERT_TRUE(req.is_multipart_form_data());
  8751. std::vector<FormData> items;
  8752. content_reader(
  8753. [&](const FormData &file) {
  8754. items.push_back(file);
  8755. return true;
  8756. },
  8757. [&](const char *data, size_t data_length) {
  8758. items.back().content.append(data, data_length);
  8759. return true;
  8760. });
  8761. ASSERT_TRUE(items.size() == 2);
  8762. EXPECT_EQ(std::string(items[0].name), "name1");
  8763. EXPECT_EQ(items[0].content, "Testing123");
  8764. EXPECT_EQ(items[0].filename, "filename1");
  8765. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8766. EXPECT_EQ(items[1].name, "name2");
  8767. EXPECT_EQ(items[1].content, "Testing456");
  8768. EXPECT_EQ(items[1].filename, "");
  8769. EXPECT_EQ(items[1].content_type, "");
  8770. });
  8771. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8772. const ContentReader &content_reader) {
  8773. ASSERT_TRUE(req.is_multipart_form_data());
  8774. std::vector<FormData> items;
  8775. content_reader(
  8776. [&](const FormData &file) {
  8777. items.push_back(file);
  8778. return true;
  8779. },
  8780. [&](const char *data, size_t data_length) {
  8781. items.back().content.append(data, data_length);
  8782. return true;
  8783. });
  8784. ASSERT_TRUE(items.size() == 2);
  8785. EXPECT_EQ(items[0].name, "name3");
  8786. EXPECT_EQ(items[0].content, rand1);
  8787. EXPECT_EQ(items[0].filename, "filename3");
  8788. EXPECT_EQ(items[0].content_type, "");
  8789. EXPECT_EQ(items[1].name, "name4");
  8790. EXPECT_EQ(items[1].content, rand2);
  8791. EXPECT_EQ(items[1].filename, "filename4");
  8792. EXPECT_EQ(items[1].content_type, "");
  8793. });
  8794. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8795. const ContentReader &content_reader) {
  8796. ASSERT_TRUE(req.is_multipart_form_data());
  8797. std::vector<FormData> items;
  8798. content_reader(
  8799. [&](const FormData &file) {
  8800. items.push_back(file);
  8801. return true;
  8802. },
  8803. [&](const char *data, size_t data_length) {
  8804. items.back().content.append(data, data_length);
  8805. return true;
  8806. });
  8807. ASSERT_TRUE(items.size() == 4);
  8808. EXPECT_EQ(std::string(items[0].name), "name1");
  8809. EXPECT_EQ(items[0].content, "Testing123");
  8810. EXPECT_EQ(items[0].filename, "filename1");
  8811. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8812. EXPECT_EQ(items[1].name, "name2");
  8813. EXPECT_EQ(items[1].content, "Testing456");
  8814. EXPECT_EQ(items[1].filename, "");
  8815. EXPECT_EQ(items[1].content_type, "");
  8816. EXPECT_EQ(items[2].name, "name3");
  8817. EXPECT_EQ(items[2].content, rand1);
  8818. EXPECT_EQ(items[2].filename, "filename3");
  8819. EXPECT_EQ(items[2].content_type, "");
  8820. EXPECT_EQ(items[3].name, "name4");
  8821. EXPECT_EQ(items[3].content, rand2);
  8822. EXPECT_EQ(items[3].filename, "filename4");
  8823. EXPECT_EQ(items[3].content_type, "");
  8824. });
  8825. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8826. auto se = detail::scope_exit([&] {
  8827. svr.stop();
  8828. t.join();
  8829. ASSERT_FALSE(svr.is_running());
  8830. });
  8831. svr.wait_until_ready();
  8832. {
  8833. Client cli("https://localhost:8080");
  8834. cli.enable_server_certificate_verification(false);
  8835. UploadFormDataItems items{
  8836. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8837. {"name2", "Testing456", "", ""}, // not a file
  8838. };
  8839. {
  8840. auto res = cli.Post("/post-none", {}, {}, {});
  8841. ASSERT_TRUE(res);
  8842. ASSERT_EQ(StatusCode::OK_200, res->status);
  8843. }
  8844. FormDataProviderItems providers;
  8845. {
  8846. auto res =
  8847. cli.Post("/post-items", {}, items, providers); // empty providers
  8848. ASSERT_TRUE(res);
  8849. ASSERT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. providers.push_back({"name3",
  8852. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8853. // test the offset is given correctly at each step
  8854. if (!offset)
  8855. sink.os.write(rand1.data(), 30);
  8856. else if (offset == 30)
  8857. sink.os.write(rand1.data() + 30, 300);
  8858. else if (offset == 330)
  8859. sink.os.write(rand1.data() + 330, 670);
  8860. else if (offset == rand1.size())
  8861. sink.done();
  8862. return true;
  8863. },
  8864. "filename3",
  8865. {}});
  8866. providers.push_back({"name4",
  8867. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8868. // test the offset is given correctly at each step
  8869. if (!offset)
  8870. sink.os.write(rand2.data(), 2000);
  8871. else if (offset == 2000)
  8872. sink.os.write(rand2.data() + 2000, 1);
  8873. else if (offset == 2001)
  8874. sink.os.write(rand2.data() + 2001, 999);
  8875. else if (offset == rand2.size())
  8876. sink.done();
  8877. return true;
  8878. },
  8879. "filename4",
  8880. {}});
  8881. {
  8882. auto res = cli.Post("/post-providers", {}, {}, providers);
  8883. ASSERT_TRUE(res);
  8884. ASSERT_EQ(StatusCode::OK_200, res->status);
  8885. }
  8886. {
  8887. auto res = cli.Post("/post-both", {}, items, providers);
  8888. ASSERT_TRUE(res);
  8889. ASSERT_EQ(StatusCode::OK_200, res->status);
  8890. }
  8891. }
  8892. }
  8893. TEST(MultipartFormDataTest, BadHeader) {
  8894. Server svr;
  8895. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8896. res.set_content("ok", "text/plain");
  8897. });
  8898. thread t = thread([&] { svr.listen(HOST, PORT); });
  8899. auto se = detail::scope_exit([&] {
  8900. svr.stop();
  8901. t.join();
  8902. ASSERT_FALSE(svr.is_running());
  8903. });
  8904. svr.wait_until_ready();
  8905. const std::string body =
  8906. "This is the preamble. It is to be ignored, though it\r\n"
  8907. "is a handy place for composition agents to include an\r\n"
  8908. "explanatory note to non-MIME conformant readers.\r\n"
  8909. "\r\n"
  8910. "\r\n"
  8911. "--simple boundary\r\n"
  8912. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8913. ": BAD...\r\n"
  8914. "\r\n"
  8915. "value1\r\n"
  8916. "--simple boundary\r\n"
  8917. "Content-Disposition: form-data; name=\"field2\"; "
  8918. "filename=\"example.txt\"\r\n"
  8919. "\r\n"
  8920. "value2\r\n"
  8921. "--simple boundary--\r\n"
  8922. "This is the epilogue. It is also to be ignored.\r\n";
  8923. std::string content_type =
  8924. R"(multipart/form-data; boundary="simple boundary")";
  8925. Client cli(HOST, PORT);
  8926. auto res = cli.Post("/post", body, content_type.c_str());
  8927. ASSERT_TRUE(res);
  8928. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8929. }
  8930. TEST(MultipartFormDataTest, WithPreamble) {
  8931. Server svr;
  8932. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8933. res.set_content("ok", "text/plain");
  8934. });
  8935. thread t = thread([&] { svr.listen(HOST, PORT); });
  8936. auto se = detail::scope_exit([&] {
  8937. svr.stop();
  8938. t.join();
  8939. ASSERT_FALSE(svr.is_running());
  8940. });
  8941. svr.wait_until_ready();
  8942. const std::string body =
  8943. "This is the preamble. It is to be ignored, though it\r\n"
  8944. "is a handy place for composition agents to include an\r\n"
  8945. "explanatory note to non-MIME conformant readers.\r\n"
  8946. "\r\n"
  8947. "\r\n"
  8948. "--simple boundary\r\n"
  8949. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8950. "\r\n"
  8951. "value1\r\n"
  8952. "--simple boundary\r\n"
  8953. "Content-Disposition: form-data; name=\"field2\"; "
  8954. "filename=\"example.txt\"\r\n"
  8955. "\r\n"
  8956. "value2\r\n"
  8957. "--simple boundary--\r\n"
  8958. "This is the epilogue. It is also to be ignored.\r\n";
  8959. std::string content_type =
  8960. R"(multipart/form-data; boundary="simple boundary")";
  8961. Client cli(HOST, PORT);
  8962. auto res = cli.Post("/post", body, content_type.c_str());
  8963. ASSERT_TRUE(res);
  8964. EXPECT_EQ(StatusCode::OK_200, res->status);
  8965. }
  8966. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8968. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8969. const ContentReader &content_reader) {
  8970. if (req.is_multipart_form_data()) {
  8971. std::vector<FormData> items;
  8972. content_reader(
  8973. [&](const FormData &file) {
  8974. items.push_back(file);
  8975. return true;
  8976. },
  8977. [&](const char *data, size_t data_length) {
  8978. items.back().content.append(data, data_length);
  8979. return true;
  8980. });
  8981. EXPECT_TRUE(std::string(items[0].name) == "document");
  8982. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8983. EXPECT_TRUE(items[0].filename == "2MB_data");
  8984. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8985. EXPECT_TRUE(items[1].name == "hello");
  8986. EXPECT_TRUE(items[1].content == "world");
  8987. EXPECT_TRUE(items[1].filename == "");
  8988. EXPECT_TRUE(items[1].content_type == "");
  8989. } else {
  8990. std::string body;
  8991. content_reader([&](const char *data, size_t data_length) {
  8992. body.append(data, data_length);
  8993. return true;
  8994. });
  8995. }
  8996. });
  8997. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8998. auto se = detail::scope_exit([&] {
  8999. svr.stop();
  9000. t.join();
  9001. ASSERT_FALSE(svr.is_running());
  9002. });
  9003. svr.wait_until_ready();
  9004. {
  9005. std::string data(1024 * 1024 * 2, '.');
  9006. std::stringstream buffer;
  9007. buffer << data;
  9008. Client cli("https://localhost:8080");
  9009. cli.enable_server_certificate_verification(false);
  9010. UploadFormDataItems items{
  9011. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9012. {"hello", "world", "", ""},
  9013. };
  9014. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9015. ASSERT_TRUE(res);
  9016. ASSERT_EQ(StatusCode::OK_200, res->status);
  9017. }
  9018. }
  9019. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9020. std::string data(1024 * 1024 * 2, '&');
  9021. std::stringstream buffer;
  9022. buffer << data;
  9023. Client cli("https://localhost:8080");
  9024. UploadFormDataItems items{
  9025. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9026. {"hello", "world", "", ""},
  9027. };
  9028. for (const char &c : " \t\r\n") {
  9029. auto res =
  9030. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9031. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9032. ASSERT_FALSE(res);
  9033. }
  9034. }
  9035. TEST(MultipartFormDataTest, PutFormData) {
  9036. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9037. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9038. const ContentReader &content_reader) {
  9039. if (req.is_multipart_form_data()) {
  9040. std::vector<FormData> items;
  9041. content_reader(
  9042. [&](const FormData &file) {
  9043. items.push_back(file);
  9044. return true;
  9045. },
  9046. [&](const char *data, size_t data_length) {
  9047. items.back().content.append(data, data_length);
  9048. return true;
  9049. });
  9050. EXPECT_TRUE(std::string(items[0].name) == "document");
  9051. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9052. EXPECT_TRUE(items[0].filename == "2MB_data");
  9053. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9054. EXPECT_TRUE(items[1].name == "hello");
  9055. EXPECT_TRUE(items[1].content == "world");
  9056. EXPECT_TRUE(items[1].filename == "");
  9057. EXPECT_TRUE(items[1].content_type == "");
  9058. } else {
  9059. std::string body;
  9060. content_reader([&](const char *data, size_t data_length) {
  9061. body.append(data, data_length);
  9062. return true;
  9063. });
  9064. }
  9065. });
  9066. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  9067. auto se = detail::scope_exit([&] {
  9068. svr.stop();
  9069. t.join();
  9070. ASSERT_FALSE(svr.is_running());
  9071. });
  9072. svr.wait_until_ready();
  9073. {
  9074. std::string data(1024 * 1024 * 2, '&');
  9075. std::stringstream buffer;
  9076. buffer << data;
  9077. Client cli("https://localhost:8080");
  9078. cli.enable_server_certificate_verification(false);
  9079. UploadFormDataItems items{
  9080. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9081. {"hello", "world", "", ""},
  9082. };
  9083. auto res = cli.Put("/put", items);
  9084. ASSERT_TRUE(res);
  9085. ASSERT_EQ(StatusCode::OK_200, res->status);
  9086. }
  9087. }
  9088. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9090. svr.Put("/put_customboundary",
  9091. [&](const Request &req, const Response & /*res*/,
  9092. const ContentReader &content_reader) {
  9093. if (req.is_multipart_form_data()) {
  9094. std::vector<FormData> items;
  9095. content_reader(
  9096. [&](const FormData &file) {
  9097. items.push_back(file);
  9098. return true;
  9099. },
  9100. [&](const char *data, size_t data_length) {
  9101. items.back().content.append(data, data_length);
  9102. return true;
  9103. });
  9104. EXPECT_TRUE(std::string(items[0].name) == "document");
  9105. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9106. EXPECT_TRUE(items[0].filename == "2MB_data");
  9107. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9108. EXPECT_TRUE(items[1].name == "hello");
  9109. EXPECT_TRUE(items[1].content == "world");
  9110. EXPECT_TRUE(items[1].filename == "");
  9111. EXPECT_TRUE(items[1].content_type == "");
  9112. } else {
  9113. std::string body;
  9114. content_reader([&](const char *data, size_t data_length) {
  9115. body.append(data, data_length);
  9116. return true;
  9117. });
  9118. }
  9119. });
  9120. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  9121. auto se = detail::scope_exit([&] {
  9122. svr.stop();
  9123. t.join();
  9124. ASSERT_FALSE(svr.is_running());
  9125. });
  9126. svr.wait_until_ready();
  9127. {
  9128. std::string data(1024 * 1024 * 2, '&');
  9129. std::stringstream buffer;
  9130. buffer << data;
  9131. Client cli("https://localhost:8080");
  9132. cli.enable_server_certificate_verification(false);
  9133. UploadFormDataItems items{
  9134. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9135. {"hello", "world", "", ""},
  9136. };
  9137. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9138. ASSERT_TRUE(res);
  9139. ASSERT_EQ(StatusCode::OK_200, res->status);
  9140. }
  9141. }
  9142. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9143. std::string data(1024 * 1024 * 2, '&');
  9144. std::stringstream buffer;
  9145. buffer << data;
  9146. Client cli("https://localhost:8080");
  9147. cli.enable_server_certificate_verification(false);
  9148. UploadFormDataItems items{
  9149. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9150. {"hello", "world", "", ""},
  9151. };
  9152. for (const char &c : " \t\r\n") {
  9153. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9154. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9155. ASSERT_FALSE(res);
  9156. }
  9157. }
  9158. TEST(MultipartFormDataTest, AlternateFilename) {
  9159. auto handled = false;
  9160. Server svr;
  9161. svr.Post("/test", [&](const Request &req, Response &res) {
  9162. ASSERT_EQ(2u, req.form.files.size());
  9163. ASSERT_EQ(1u, req.form.fields.size());
  9164. // Test files
  9165. const auto &file1 = req.form.get_file("file1");
  9166. ASSERT_EQ("file1", file1.name);
  9167. ASSERT_EQ("A.txt", file1.filename);
  9168. ASSERT_EQ("text/plain", file1.content_type);
  9169. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9170. const auto &file2 = req.form.get_file("file2");
  9171. ASSERT_EQ("file2", file2.name);
  9172. ASSERT_EQ("a.html", file2.filename);
  9173. ASSERT_EQ("text/html", file2.content_type);
  9174. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9175. file2.content);
  9176. // Test text field
  9177. const auto &text = req.form.get_field("text");
  9178. ASSERT_EQ("text default", text);
  9179. res.set_content("ok", "text/plain");
  9180. handled = true;
  9181. });
  9182. thread t = thread([&] { svr.listen(HOST, PORT); });
  9183. auto se = detail::scope_exit([&] {
  9184. svr.stop();
  9185. t.join();
  9186. ASSERT_FALSE(svr.is_running());
  9187. ASSERT_TRUE(handled);
  9188. });
  9189. svr.wait_until_ready();
  9190. auto req = "POST /test HTTP/1.1\r\n"
  9191. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9192. "Content-Length: 399\r\n"
  9193. "\r\n"
  9194. "----------\r\n"
  9195. "Content-Disposition: form-data; name=\"text\"\r\n"
  9196. "\r\n"
  9197. "text default\r\n"
  9198. "----------\r\n"
  9199. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9200. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9201. "Content-Type: text/plain\r\n"
  9202. "\r\n"
  9203. "Content of a.txt.\r\n"
  9204. "\r\n"
  9205. "----------\r\n"
  9206. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9207. "\"a.html\"\r\n"
  9208. "Content-Type: text/html\r\n"
  9209. "\r\n"
  9210. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9211. "\r\n"
  9212. "------------\r\n";
  9213. ASSERT_TRUE(send_request(1, req));
  9214. }
  9215. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9216. auto handled = false;
  9217. Server svr;
  9218. svr.Post("/test", [&](const Request &req, Response &) {
  9219. ASSERT_EQ(2u, req.form.fields.size());
  9220. const auto &text1 = req.form.get_field("text1");
  9221. ASSERT_EQ("text1", text1);
  9222. const auto &text2 = req.form.get_field("text2");
  9223. ASSERT_EQ("text2", text2);
  9224. handled = true;
  9225. });
  9226. thread t = thread([&] { svr.listen(HOST, PORT); });
  9227. auto se = detail::scope_exit([&] {
  9228. svr.stop();
  9229. t.join();
  9230. ASSERT_FALSE(svr.is_running());
  9231. ASSERT_TRUE(handled);
  9232. });
  9233. svr.wait_until_ready();
  9234. auto req = "POST /test HTTP/1.1\r\n"
  9235. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9236. "Content-Length: 146\r\n"
  9237. "\r\n----------\r\n"
  9238. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9239. "\r\n"
  9240. "text1"
  9241. "\r\n----------\r\n"
  9242. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9243. "\r\n"
  9244. "text2"
  9245. "\r\n------------";
  9246. std::string response;
  9247. ASSERT_TRUE(send_request(1, req, &response));
  9248. ASSERT_EQ("200", response.substr(9, 3));
  9249. }
  9250. TEST(MultipartFormDataTest, ContentLength) {
  9251. auto handled = false;
  9252. Server svr;
  9253. svr.Post("/test", [&](const Request &req, Response &) {
  9254. ASSERT_EQ(2u, req.form.fields.size());
  9255. const auto &text1 = req.form.get_field("text1");
  9256. ASSERT_EQ("text1", text1);
  9257. const auto &text2 = req.form.get_field("text2");
  9258. ASSERT_EQ("text2", text2);
  9259. handled = true;
  9260. });
  9261. thread t = thread([&] { svr.listen(HOST, PORT); });
  9262. auto se = detail::scope_exit([&] {
  9263. svr.stop();
  9264. t.join();
  9265. ASSERT_FALSE(svr.is_running());
  9266. ASSERT_TRUE(handled);
  9267. });
  9268. svr.wait_until_ready();
  9269. auto req = "POST /test HTTP/1.1\r\n"
  9270. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9271. "Content-Length: 167\r\n"
  9272. "\r\n----------\r\n"
  9273. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9274. "Content-Length: 5\r\n"
  9275. "\r\n"
  9276. "text1"
  9277. "\r\n----------\r\n"
  9278. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9279. "\r\n"
  9280. "text2"
  9281. "\r\n------------\r\n";
  9282. std::string response;
  9283. ASSERT_TRUE(send_request(1, req, &response));
  9284. ASSERT_EQ("200", response.substr(9, 3));
  9285. }
  9286. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9287. auto handled = false;
  9288. Server svr;
  9289. svr.Post("/test", [&](const Request &req, Response &) {
  9290. ASSERT_EQ(2u, req.form.fields.size());
  9291. const auto &text1 = req.form.get_field("text1");
  9292. ASSERT_EQ("text1", text1);
  9293. // TODO: Add header access for text fields if needed
  9294. const auto &text2 = req.form.get_field("text2");
  9295. ASSERT_EQ("text2", text2);
  9296. // TODO: Header access for text fields needs to be implemented
  9297. // auto &headers = it->second.headers;
  9298. // ASSERT_EQ(3U, headers.size());
  9299. // auto custom_header = headers.find("x-whatever");
  9300. // ASSERT_TRUE(custom_header != headers.end());
  9301. // ASSERT_NE("customvalue", custom_header->second);
  9302. // ASSERT_EQ("CustomValue", custom_header->second);
  9303. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9304. handled = true;
  9305. });
  9306. thread t = thread([&] { svr.listen(HOST, PORT); });
  9307. auto se = detail::scope_exit([&] {
  9308. svr.stop();
  9309. t.join();
  9310. ASSERT_FALSE(svr.is_running());
  9311. ASSERT_TRUE(handled);
  9312. });
  9313. svr.wait_until_ready();
  9314. auto req = "POST /test HTTP/1.1\r\n"
  9315. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9316. "Content-Length: 232\r\n"
  9317. "\r\n----------\r\n"
  9318. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9319. "Content-Length: 5\r\n"
  9320. "X-Test: 1\r\n"
  9321. "\r\n"
  9322. "text1"
  9323. "\r\n----------\r\n"
  9324. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9325. "Content-Type: text/plain\r\n"
  9326. "X-Whatever: CustomValue\r\n"
  9327. "\r\n"
  9328. "text2"
  9329. "\r\n------------\r\n"
  9330. "That should be disregarded. Not even read";
  9331. std::string response;
  9332. ASSERT_TRUE(send_request(1, req, &response));
  9333. ASSERT_EQ("200", response.substr(9, 3));
  9334. }
  9335. TEST(MultipartFormDataTest, LargeHeader) {
  9336. auto handled = false;
  9337. Server svr;
  9338. svr.Post("/test", [&](const Request &req, Response &) {
  9339. ASSERT_EQ(1u, req.form.fields.size());
  9340. const auto &text = req.form.get_field("name1");
  9341. ASSERT_EQ("text1", text);
  9342. handled = true;
  9343. });
  9344. thread t = thread([&] { svr.listen(HOST, PORT); });
  9345. auto se = detail::scope_exit([&] {
  9346. svr.stop();
  9347. t.join();
  9348. ASSERT_FALSE(svr.is_running());
  9349. ASSERT_TRUE(handled);
  9350. });
  9351. svr.wait_until_ready();
  9352. auto boundary = std::string("cpp-httplib-multipart-data");
  9353. std::string content = "--" + boundary +
  9354. "\r\n"
  9355. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9356. "\r\n"
  9357. "text1\r\n"
  9358. "--" +
  9359. boundary + "--\r\n";
  9360. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9361. "Content-Type: multipart/form-data;boundary=" +
  9362. boundary +
  9363. "\r\n"
  9364. "Content-Length: " +
  9365. std::to_string(content.size()) +
  9366. "\r\n"
  9367. "Dummy-Header: ";
  9368. std::string header_suffix = "\r\n"
  9369. "\r\n";
  9370. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9371. size_t header_dummy_size =
  9372. read_buff_size -
  9373. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9374. auto header_dummy = std::string(header_dummy_size, '@');
  9375. auto req = header_prefix + header_dummy + header_suffix + content;
  9376. std::string response;
  9377. ASSERT_TRUE(send_request(1, req, &response));
  9378. ASSERT_EQ("200", response.substr(9, 3));
  9379. }
  9380. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9381. static constexpr unsigned int number_of_tasks{1000000};
  9382. std::atomic_uint count{0};
  9383. std::unique_ptr<TaskQueue> task_queue{
  9384. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9385. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9386. auto queued = task_queue->enqueue(
  9387. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9388. EXPECT_TRUE(queued);
  9389. }
  9390. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9391. task_queue->shutdown();
  9392. #else
  9393. EXPECT_NO_THROW(task_queue->shutdown());
  9394. #endif
  9395. EXPECT_EQ(number_of_tasks, count.load());
  9396. }
  9397. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9398. static constexpr unsigned int number_of_tasks{1000000};
  9399. static constexpr unsigned int qlimit{2};
  9400. unsigned int queued_count{0};
  9401. std::atomic_uint count{0};
  9402. std::unique_ptr<TaskQueue> task_queue{
  9403. new ThreadPool{/*num_threads=*/1, qlimit}};
  9404. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9405. if (task_queue->enqueue(
  9406. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9407. queued_count++;
  9408. }
  9409. }
  9410. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9411. task_queue->shutdown();
  9412. #else
  9413. EXPECT_NO_THROW(task_queue->shutdown());
  9414. #endif
  9415. EXPECT_EQ(queued_count, count.load());
  9416. EXPECT_TRUE(queued_count <= number_of_tasks);
  9417. EXPECT_TRUE(queued_count >= qlimit);
  9418. }
  9419. TEST(TaskQueueTest, MaxQueuedRequests) {
  9420. static constexpr unsigned int qlimit{3};
  9421. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9422. std::condition_variable sem_cv;
  9423. std::mutex sem_mtx;
  9424. int credits = 0;
  9425. bool queued;
  9426. /* Fill up the queue with tasks that will block until we give them credits to
  9427. * complete. */
  9428. for (unsigned int n = 0; n <= qlimit;) {
  9429. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9430. std::unique_lock<std::mutex> lock(sem_mtx);
  9431. while (credits <= 0) {
  9432. sem_cv.wait(lock);
  9433. }
  9434. /* Consume the credit and signal the test code if they are all gone. */
  9435. if (--credits == 0) { sem_cv.notify_one(); }
  9436. });
  9437. if (n < qlimit) {
  9438. /* The first qlimit enqueues must succeed. */
  9439. EXPECT_TRUE(queued);
  9440. } else {
  9441. /* The last one will succeed only when the worker thread
  9442. * starts and dequeues the first blocking task. Although
  9443. * not necessary for the correctness of this test, we sleep for
  9444. * a short while to avoid busy waiting. */
  9445. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9446. }
  9447. if (queued) { n++; }
  9448. }
  9449. /* Further enqueues must fail since the queue is full. */
  9450. for (auto i = 0; i < 4; i++) {
  9451. queued = task_queue->enqueue([] {});
  9452. EXPECT_FALSE(queued);
  9453. }
  9454. /* Give the credits to allow the previous tasks to complete. */
  9455. {
  9456. std::unique_lock<std::mutex> lock(sem_mtx);
  9457. credits += qlimit + 1;
  9458. }
  9459. sem_cv.notify_all();
  9460. /* Wait for all the credits to be consumed. */
  9461. {
  9462. std::unique_lock<std::mutex> lock(sem_mtx);
  9463. while (credits > 0) {
  9464. sem_cv.wait(lock);
  9465. }
  9466. }
  9467. /* Check that we are able again to enqueue at least qlimit tasks. */
  9468. for (unsigned int i = 0; i < qlimit; i++) {
  9469. queued = task_queue->enqueue([] {});
  9470. EXPECT_TRUE(queued);
  9471. }
  9472. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9473. task_queue->shutdown();
  9474. #else
  9475. EXPECT_NO_THROW(task_queue->shutdown());
  9476. #endif
  9477. }
  9478. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9479. Server svr;
  9480. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9481. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9482. });
  9483. svr.Get("/hello", [](const Request &req, Response &res) {
  9484. res.set_content(req.get_param_value("key"), "text/plain");
  9485. });
  9486. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9487. auto se = detail::scope_exit([&] {
  9488. svr.stop();
  9489. thread.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. {
  9494. Client cli(HOST, PORT);
  9495. cli.set_follow_location(true);
  9496. auto res = cli.Get("/");
  9497. ASSERT_TRUE(res);
  9498. EXPECT_EQ(StatusCode::OK_200, res->status);
  9499. EXPECT_EQ("val&key2=val2", res->body);
  9500. }
  9501. }
  9502. #endif
  9503. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9504. Server svr;
  9505. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9506. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9507. });
  9508. svr.Get("/hello", [](const Request &req, Response &res) {
  9509. res.set_content(req.get_param_value("key"), "text/plain");
  9510. });
  9511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9512. auto se = detail::scope_exit([&] {
  9513. svr.stop();
  9514. thread.join();
  9515. ASSERT_FALSE(svr.is_running());
  9516. });
  9517. svr.wait_until_ready();
  9518. {
  9519. Client cli(HOST, PORT);
  9520. cli.set_follow_location(true);
  9521. auto res = cli.Get("/");
  9522. ASSERT_TRUE(res);
  9523. EXPECT_EQ(StatusCode::OK_200, res->status);
  9524. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9525. }
  9526. }
  9527. #ifdef CPPHTTPLIB_SSL_ENABLED
  9528. TEST(RedirectTest, Issue2185_Online) {
  9529. SSLClient client("github.com");
  9530. client.set_follow_location(true);
  9531. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9532. "Coollab-Windows.zip");
  9533. ASSERT_TRUE(res);
  9534. EXPECT_EQ(StatusCode::OK_200, res->status);
  9535. EXPECT_EQ(9920427U, res->body.size());
  9536. }
  9537. #endif
  9538. TEST(VulnerabilityTest, CRLFInjection) {
  9539. Server svr;
  9540. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9541. res.set_content("Hello 1", "text/plain");
  9542. });
  9543. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9544. res.set_content("Hello 2", "text/plain");
  9545. });
  9546. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9547. res.set_content("Hello 3", "text/plain");
  9548. });
  9549. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9550. res.set_content("Hello 4", "text/plain");
  9551. });
  9552. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9553. for (const auto &x : req.headers) {
  9554. auto key = x.first;
  9555. EXPECT_STRNE("evil", key.c_str());
  9556. }
  9557. });
  9558. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9559. auto se = detail::scope_exit([&] {
  9560. svr.stop();
  9561. thread.join();
  9562. ASSERT_FALSE(svr.is_running());
  9563. });
  9564. svr.wait_until_ready();
  9565. {
  9566. Client cli(HOST, PORT);
  9567. cli.Post("/test1", "A=B",
  9568. "application/x-www-form-urlencoded\r\nevil: hello1");
  9569. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9570. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9571. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9572. }
  9573. }
  9574. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9575. auto server_thread = std::thread([] {
  9576. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9577. default_socket_options(srv);
  9578. sockaddr_in addr{};
  9579. addr.sin_family = AF_INET;
  9580. addr.sin_port = htons(PORT + 1);
  9581. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9582. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9583. ::listen(srv, 1);
  9584. sockaddr_in cli_addr{};
  9585. socklen_t cli_len = sizeof(cli_addr);
  9586. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9587. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9588. std::string buf_all;
  9589. char buf[2048];
  9590. ssize_t n;
  9591. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9592. buf_all.append(buf, static_cast<size_t>(n));
  9593. size_t pos;
  9594. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9595. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9596. auto e = request_block.find("\r\n");
  9597. if (e != std::string::npos) {
  9598. auto request_line = request_block.substr(0, e);
  9599. std::string msg =
  9600. "CRLF injection detected in request line: '" + request_line + "'";
  9601. EXPECT_FALSE(true) << msg;
  9602. }
  9603. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9604. ::send(cli,
  9605. #ifdef _WIN32
  9606. static_cast<const char *>(resp.c_str()),
  9607. static_cast<int>(resp.size()),
  9608. #else
  9609. resp.c_str(), resp.size(),
  9610. #endif
  9611. 0);
  9612. buf_all.erase(0, pos + 4);
  9613. }
  9614. }
  9615. detail::close_socket(cli);
  9616. detail::close_socket(srv);
  9617. });
  9618. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9619. auto cli = Client("127.0.0.1", PORT + 1);
  9620. auto headers = Headers{
  9621. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9622. {"Connection", "keep-alive"}};
  9623. auto res = cli.Get("/hi", headers);
  9624. EXPECT_FALSE(res);
  9625. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9626. server_thread.join();
  9627. }
  9628. TEST(PathParamsTest, StaticMatch) {
  9629. const auto pattern = "/users/all";
  9630. detail::PathParamsMatcher matcher(pattern);
  9631. Request request;
  9632. request.path = "/users/all";
  9633. ASSERT_TRUE(matcher.match(request));
  9634. std::unordered_map<std::string, std::string> expected_params = {};
  9635. EXPECT_EQ(request.path_params, expected_params);
  9636. }
  9637. TEST(PathParamsTest, StaticMismatch) {
  9638. const auto pattern = "/users/all";
  9639. detail::PathParamsMatcher matcher(pattern);
  9640. Request request;
  9641. request.path = "/users/1";
  9642. ASSERT_FALSE(matcher.match(request));
  9643. }
  9644. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9645. const auto pattern = "/users/:id/subscriptions";
  9646. detail::PathParamsMatcher matcher(pattern);
  9647. Request request;
  9648. request.path = "/users/42/subscriptions";
  9649. ASSERT_TRUE(matcher.match(request));
  9650. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9651. EXPECT_EQ(request.path_params, expected_params);
  9652. }
  9653. TEST(PathParamsTest, SingleParamInTheEnd) {
  9654. const auto pattern = "/users/:id";
  9655. detail::PathParamsMatcher matcher(pattern);
  9656. Request request;
  9657. request.path = "/users/24";
  9658. ASSERT_TRUE(matcher.match(request));
  9659. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9660. EXPECT_EQ(request.path_params, expected_params);
  9661. }
  9662. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9663. const auto pattern = "/users/:id/";
  9664. detail::PathParamsMatcher matcher(pattern);
  9665. Request request;
  9666. request.path = "/users/42/";
  9667. ASSERT_TRUE(matcher.match(request));
  9668. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9669. EXPECT_EQ(request.path_params, expected_params);
  9670. }
  9671. TEST(PathParamsTest, EmptyParam) {
  9672. const auto pattern = "/users/:id/";
  9673. detail::PathParamsMatcher matcher(pattern);
  9674. Request request;
  9675. request.path = "/users//";
  9676. ASSERT_TRUE(matcher.match(request));
  9677. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9678. EXPECT_EQ(request.path_params, expected_params);
  9679. }
  9680. TEST(PathParamsTest, FragmentMismatch) {
  9681. const auto pattern = "/users/:id/";
  9682. detail::PathParamsMatcher matcher(pattern);
  9683. Request request;
  9684. request.path = "/admins/24/";
  9685. ASSERT_FALSE(matcher.match(request));
  9686. }
  9687. TEST(PathParamsTest, ExtraFragments) {
  9688. const auto pattern = "/users/:id";
  9689. detail::PathParamsMatcher matcher(pattern);
  9690. Request request;
  9691. request.path = "/users/42/subscriptions";
  9692. ASSERT_FALSE(matcher.match(request));
  9693. }
  9694. TEST(PathParamsTest, MissingTrailingParam) {
  9695. const auto pattern = "/users/:id";
  9696. detail::PathParamsMatcher matcher(pattern);
  9697. Request request;
  9698. request.path = "/users";
  9699. ASSERT_FALSE(matcher.match(request));
  9700. }
  9701. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9702. const auto pattern = "/users/:id/subscriptions";
  9703. detail::PathParamsMatcher matcher(pattern);
  9704. Request request;
  9705. request.path = "/users/subscriptions";
  9706. ASSERT_FALSE(matcher.match(request));
  9707. }
  9708. TEST(PathParamsTest, MultipleParams) {
  9709. const auto pattern = "/users/:userid/subscriptions/:subid";
  9710. detail::PathParamsMatcher matcher(pattern);
  9711. Request request;
  9712. request.path = "/users/42/subscriptions/2";
  9713. ASSERT_TRUE(matcher.match(request));
  9714. std::unordered_map<std::string, std::string> expected_params = {
  9715. {"userid", "42"}, {"subid", "2"}};
  9716. EXPECT_EQ(request.path_params, expected_params);
  9717. }
  9718. TEST(PathParamsTest, SequenceOfParams) {
  9719. const auto pattern = "/values/:x/:y/:z";
  9720. detail::PathParamsMatcher matcher(pattern);
  9721. Request request;
  9722. request.path = "/values/1/2/3";
  9723. ASSERT_TRUE(matcher.match(request));
  9724. std::unordered_map<std::string, std::string> expected_params = {
  9725. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9726. EXPECT_EQ(request.path_params, expected_params);
  9727. }
  9728. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9729. const auto pattern = "/prefix:suffix";
  9730. detail::PathParamsMatcher matcher(pattern);
  9731. Request request;
  9732. request.path = "/prefix:suffix";
  9733. ASSERT_TRUE(matcher.match(request));
  9734. const std::unordered_map<std::string, std::string> expected_params = {};
  9735. EXPECT_EQ(request.path_params, expected_params);
  9736. }
  9737. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9738. // If ipv6 regex working, regex match codepath is taken.
  9739. // else port will default to 80 in Client impl
  9740. int clientImplMagicPort = 80;
  9741. int port = 4321;
  9742. // above ports must be different to avoid false negative
  9743. EXPECT_NE(clientImplMagicPort, port);
  9744. std::string ipV6TestURL = "http://[ff06::c3]";
  9745. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9746. CLIENT_PRIVATE_KEY_FILE);
  9747. EXPECT_EQ(cli.port(), port);
  9748. }
  9749. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9750. auto file_path = "./www/dir/index.html";
  9751. auto dir_path = "./www/dir";
  9752. detail::FileStat stat_file(file_path);
  9753. EXPECT_TRUE(stat_file.is_file());
  9754. EXPECT_FALSE(stat_file.is_dir());
  9755. detail::FileStat stat_dir(dir_path);
  9756. EXPECT_FALSE(stat_dir.is_file());
  9757. EXPECT_TRUE(stat_dir.is_dir());
  9758. }
  9759. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9760. // IPv4 with default HTTP port (80)
  9761. EXPECT_EQ("example.com",
  9762. detail::make_host_and_port_string("example.com", 80, false));
  9763. // IPv4 with default HTTPS port (443)
  9764. EXPECT_EQ("example.com",
  9765. detail::make_host_and_port_string("example.com", 443, true));
  9766. // IPv4 with non-default HTTP port
  9767. EXPECT_EQ("example.com:8080",
  9768. detail::make_host_and_port_string("example.com", 8080, false));
  9769. // IPv4 with non-default HTTPS port
  9770. EXPECT_EQ("example.com:8443",
  9771. detail::make_host_and_port_string("example.com", 8443, true));
  9772. // IPv6 with default HTTP port (80)
  9773. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9774. // IPv6 with default HTTPS port (443)
  9775. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9776. // IPv6 with non-default HTTP port
  9777. EXPECT_EQ("[::1]:8080",
  9778. detail::make_host_and_port_string("::1", 8080, false));
  9779. // IPv6 with non-default HTTPS port
  9780. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9781. // IPv6 full address with default port
  9782. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9783. detail::make_host_and_port_string(
  9784. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9785. // IPv6 full address with non-default port
  9786. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9787. detail::make_host_and_port_string(
  9788. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9789. // IPv6 localhost with non-default port
  9790. EXPECT_EQ("[::1]:3000",
  9791. detail::make_host_and_port_string("::1", 3000, false));
  9792. // IPv6 with zone ID (link-local address) with default port
  9793. EXPECT_EQ("[fe80::1%eth0]",
  9794. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9795. // IPv6 with zone ID (link-local address) with non-default port
  9796. EXPECT_EQ("[fe80::1%eth0]:8080",
  9797. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9798. // Edge case: Port 443 with is_ssl=false (should add port)
  9799. EXPECT_EQ("example.com:443",
  9800. detail::make_host_and_port_string("example.com", 443, false));
  9801. // Edge case: Port 80 with is_ssl=true (should add port)
  9802. EXPECT_EQ("example.com:80",
  9803. detail::make_host_and_port_string("example.com", 80, true));
  9804. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9805. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9806. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9807. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9808. // Security fix: Already bracketed IPv6 should not get double brackets
  9809. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9810. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9811. EXPECT_EQ("[::1]:8080",
  9812. detail::make_host_and_port_string("[::1]", 8080, false));
  9813. EXPECT_EQ("[2001:db8::1]:8080",
  9814. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9815. EXPECT_EQ("[fe80::1%eth0]",
  9816. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9817. EXPECT_EQ("[fe80::1%eth0]:8080",
  9818. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9819. // Edge case: Empty host (should return as-is)
  9820. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9821. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9822. // This is a known limitation but shouldn't crash
  9823. EXPECT_EQ("[host:name]",
  9824. detail::make_host_and_port_string("host:name", 80, false));
  9825. // Port number edge cases (no validation, but should not crash)
  9826. EXPECT_EQ("example.com:0",
  9827. detail::make_host_and_port_string("example.com", 0, false));
  9828. EXPECT_EQ("example.com:-1",
  9829. detail::make_host_and_port_string("example.com", -1, false));
  9830. EXPECT_EQ("example.com:65535",
  9831. detail::make_host_and_port_string("example.com", 65535, false));
  9832. EXPECT_EQ("example.com:65536",
  9833. detail::make_host_and_port_string("example.com", 65536, false));
  9834. }
  9835. #ifdef CPPHTTPLIB_SSL_ENABLED
  9836. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9837. httplib::SSLClient cli("roblox.com", 443);
  9838. cli.set_follow_location(true);
  9839. auto res = cli.Get("/");
  9840. ASSERT_TRUE(res);
  9841. EXPECT_EQ(StatusCode::OK_200, res->status);
  9842. }
  9843. #endif
  9844. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9845. Server svr;
  9846. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9847. EXPECT_EQ(res.status, 400);
  9848. });
  9849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9850. auto se = detail::scope_exit([&] {
  9851. svr.stop();
  9852. thread.join();
  9853. ASSERT_FALSE(svr.is_running());
  9854. });
  9855. svr.wait_until_ready();
  9856. Client cli(HOST, PORT);
  9857. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9858. }
  9859. TEST(InvalidHeaderCharsTest, is_field_name) {
  9860. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9861. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9862. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9863. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9864. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9865. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9866. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9867. EXPECT_FALSE(detail::fields::is_field_name(""));
  9868. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9869. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9870. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9871. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9872. }
  9873. TEST(InvalidHeaderCharsTest, is_field_value) {
  9874. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9875. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9876. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9877. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9878. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9879. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9880. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9881. EXPECT_TRUE(detail::fields::is_field_value(""));
  9882. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9883. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9884. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9885. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9886. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9887. }
  9888. TEST(InvalidHeaderCharsTest, OnServer) {
  9889. Server svr;
  9890. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9891. std::string header = "Not Set";
  9892. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9893. res.set_header(header, "value");
  9894. res.set_content("Page Content Page Content", "text/plain");
  9895. });
  9896. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9897. std::string header = "Not Set";
  9898. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9899. res.set_header("X-Test", header);
  9900. res.set_content("Page Content Page Content", "text/plain");
  9901. });
  9902. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. thread.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. Client cli(HOST, PORT);
  9910. {
  9911. auto res = cli.Get(
  9912. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9913. ASSERT_TRUE(res);
  9914. EXPECT_EQ("Page Content Page Content", res->body);
  9915. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9916. }
  9917. {
  9918. auto res = cli.Get(
  9919. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9920. ASSERT_TRUE(res);
  9921. EXPECT_EQ("Page Content Page Content", res->body);
  9922. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9923. }
  9924. }
  9925. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9926. auto handled = false;
  9927. Server svr;
  9928. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9929. thread t = thread([&] { svr.listen(HOST, PORT); });
  9930. auto se = detail::scope_exit([&] {
  9931. svr.stop();
  9932. t.join();
  9933. ASSERT_FALSE(svr.is_running());
  9934. ASSERT_FALSE(handled);
  9935. });
  9936. svr.wait_until_ready();
  9937. auto req = "POST /test HTTP/1.1\r\n"
  9938. "Content-Length: x\r\n"
  9939. "\r\n";
  9940. std::string response;
  9941. ASSERT_TRUE(send_request(1, req, &response));
  9942. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9943. response.substr(0, response.find("\r\n")));
  9944. }
  9945. #ifndef _WIN32
  9946. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9947. static constexpr char reject[] = "Unauthorized";
  9948. static constexpr char accept[] = "Upload accepted";
  9949. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9950. Server svr;
  9951. svr.set_expect_100_continue_handler(
  9952. [](const Request & /*req*/, Response &res) {
  9953. res.status = StatusCode::Unauthorized_401;
  9954. res.set_content(reject, "text/plain");
  9955. return res.status;
  9956. });
  9957. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9958. res.set_content(accept, "text/plain");
  9959. });
  9960. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9961. auto se = detail::scope_exit([&] {
  9962. svr.stop();
  9963. thread.join();
  9964. ASSERT_FALSE(svr.is_running());
  9965. });
  9966. svr.wait_until_ready();
  9967. {
  9968. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9969. curl_easy_init(), &curl_easy_cleanup};
  9970. ASSERT_NE(curl, nullptr);
  9971. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9972. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9973. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9974. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9975. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9976. &curl_slist_free_all};
  9977. ASSERT_NE(list, nullptr);
  9978. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9979. struct read_data {
  9980. size_t read_size;
  9981. size_t total_size;
  9982. } data = {0, total_size};
  9983. using read_callback_t =
  9984. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9985. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9986. void *userdata) -> size_t {
  9987. read_data *data = (read_data *)userdata;
  9988. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9989. std::fill_n(ptr, size * nmemb, 'A');
  9990. data->read_size += size * nmemb;
  9991. return size * nmemb;
  9992. };
  9993. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9994. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9995. std::vector<char> buffer;
  9996. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9997. using write_callback_t =
  9998. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9999. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10000. void *userdata) -> size_t {
  10001. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10002. buffer->reserve(buffer->size() + size * nmemb + 1);
  10003. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10004. return size * nmemb;
  10005. };
  10006. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10007. {
  10008. const auto res = curl_easy_perform(curl.get());
  10009. ASSERT_EQ(res, CURLE_OK);
  10010. }
  10011. {
  10012. auto response_code = long{};
  10013. const auto res =
  10014. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10015. ASSERT_EQ(res, CURLE_OK);
  10016. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10017. }
  10018. {
  10019. auto dl = curl_off_t{};
  10020. const auto res =
  10021. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10022. ASSERT_EQ(res, CURLE_OK);
  10023. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10024. }
  10025. {
  10026. buffer.push_back('\0');
  10027. ASSERT_STRCASEEQ(buffer.data(), reject);
  10028. }
  10029. }
  10030. }
  10031. #endif
  10032. template <typename S, typename C>
  10033. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10034. svr.Get("/stream", [&](const Request &, Response &res) {
  10035. auto data = new std::string("01234567890123456789");
  10036. res.set_content_provider(
  10037. data->size(), "text/plain",
  10038. [&, data](size_t offset, size_t length, DataSink &sink) {
  10039. const size_t DATA_CHUNK_SIZE = 4;
  10040. const auto &d = *data;
  10041. std::this_thread::sleep_for(std::chrono::seconds(1));
  10042. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10043. return true;
  10044. },
  10045. [data](bool success) {
  10046. EXPECT_FALSE(success);
  10047. delete data;
  10048. });
  10049. });
  10050. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10051. auto i = new size_t(0);
  10052. res.set_content_provider(
  10053. "text/plain",
  10054. [i](size_t, DataSink &sink) {
  10055. if (*i < 5) {
  10056. std::this_thread::sleep_for(std::chrono::seconds(1));
  10057. sink.write("abcd", 4);
  10058. (*i)++;
  10059. } else {
  10060. sink.done();
  10061. }
  10062. return true;
  10063. },
  10064. [i](bool success) {
  10065. EXPECT_FALSE(success);
  10066. delete i;
  10067. });
  10068. });
  10069. svr.Get("/chunked", [&](const Request &, Response &res) {
  10070. auto i = new size_t(0);
  10071. res.set_chunked_content_provider(
  10072. "text/plain",
  10073. [i](size_t, DataSink &sink) {
  10074. if (*i < 5) {
  10075. std::this_thread::sleep_for(std::chrono::seconds(1));
  10076. sink.os << "abcd";
  10077. (*i)++;
  10078. } else {
  10079. sink.done();
  10080. }
  10081. return true;
  10082. },
  10083. [i](bool success) {
  10084. EXPECT_FALSE(success);
  10085. delete i;
  10086. });
  10087. });
  10088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10089. auto se = detail::scope_exit([&] {
  10090. svr.stop();
  10091. listen_thread.join();
  10092. ASSERT_FALSE(svr.is_running());
  10093. });
  10094. svr.wait_until_ready();
  10095. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10096. {
  10097. auto start = std::chrono::steady_clock::now();
  10098. auto res = cli.Get("/stream");
  10099. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10100. std::chrono::steady_clock::now() - start)
  10101. .count();
  10102. ASSERT_FALSE(res);
  10103. EXPECT_EQ(Error::Read, res.error());
  10104. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10105. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10106. }
  10107. {
  10108. auto start = std::chrono::steady_clock::now();
  10109. auto res = cli.Get("/stream_without_length");
  10110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10111. std::chrono::steady_clock::now() - start)
  10112. .count();
  10113. ASSERT_FALSE(res);
  10114. EXPECT_EQ(Error::Read, res.error());
  10115. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10116. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10117. }
  10118. {
  10119. auto start = std::chrono::steady_clock::now();
  10120. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10121. EXPECT_EQ("abcd", string(data, data_length));
  10122. return true;
  10123. });
  10124. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10125. std::chrono::steady_clock::now() - start)
  10126. .count();
  10127. ASSERT_FALSE(res);
  10128. EXPECT_EQ(Error::Read, res.error());
  10129. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10130. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10131. }
  10132. }
  10133. TEST(MaxTimeoutTest, ContentStream) {
  10134. time_t timeout = 2000;
  10135. time_t threshold = 200;
  10136. Server svr;
  10137. Client cli("localhost", PORT);
  10138. max_timeout_test(svr, cli, timeout, threshold);
  10139. }
  10140. #ifdef CPPHTTPLIB_SSL_ENABLED
  10141. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10142. time_t timeout = 2000;
  10143. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10145. SSLClient cli("localhost", PORT);
  10146. cli.enable_server_certificate_verification(false);
  10147. max_timeout_test(svr, cli, timeout, threshold);
  10148. }
  10149. #endif
  10150. class EventDispatcher {
  10151. public:
  10152. EventDispatcher() {}
  10153. bool wait_event(DataSink *sink) {
  10154. unique_lock<mutex> lk(m_);
  10155. int id = id_;
  10156. // Wait with timeout to prevent hanging if client disconnects
  10157. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10158. [&] { return cid_ == id; })) {
  10159. return false; // Timeout occurred
  10160. }
  10161. sink->write(message_.data(), message_.size());
  10162. return true;
  10163. }
  10164. void send_event(const string &message) {
  10165. lock_guard<mutex> lk(m_);
  10166. cid_ = id_++;
  10167. message_ = message;
  10168. cv_.notify_all();
  10169. }
  10170. private:
  10171. mutex m_;
  10172. condition_variable cv_;
  10173. atomic_int id_{0};
  10174. atomic_int cid_{-1};
  10175. string message_;
  10176. };
  10177. TEST(ClientInThreadTest, Issue2068) {
  10178. EventDispatcher ed;
  10179. Server svr;
  10180. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10181. res.set_chunked_content_provider("text/event-stream",
  10182. [&](size_t /*offset*/, DataSink &sink) {
  10183. return ed.wait_event(&sink);
  10184. });
  10185. });
  10186. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10187. svr.wait_until_ready();
  10188. thread event_thread([&] {
  10189. int id = 0;
  10190. while (svr.is_running()) {
  10191. this_thread::sleep_for(chrono::milliseconds(500));
  10192. std::stringstream ss;
  10193. ss << "data: " << id << "\n\n";
  10194. ed.send_event(ss.str());
  10195. id++;
  10196. }
  10197. });
  10198. auto se = detail::scope_exit([&] {
  10199. svr.stop();
  10200. listen_thread.join();
  10201. event_thread.join();
  10202. ASSERT_FALSE(svr.is_running());
  10203. });
  10204. {
  10205. auto client = detail::make_unique<Client>(HOST, PORT);
  10206. client->set_read_timeout(std::chrono::minutes(10));
  10207. std::atomic<bool> stop{false};
  10208. std::thread t([&] {
  10209. client->Get("/event1",
  10210. [&](const char *, size_t) -> bool { return !stop; });
  10211. });
  10212. std::this_thread::sleep_for(std::chrono::seconds(2));
  10213. stop = true;
  10214. client->stop();
  10215. t.join();
  10216. // Reset client after thread has finished
  10217. client.reset();
  10218. }
  10219. }
  10220. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10221. Server svr;
  10222. svr.Get("/", [](const Request &req, Response &res) {
  10223. EXPECT_EQ(2U, req.trailers.size());
  10224. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10225. // Denied
  10226. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10227. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10228. // Accepted
  10229. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10230. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10231. EXPECT_TRUE(req.has_trailer("X-World"));
  10232. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10233. res.set_content("ok", "text/plain");
  10234. });
  10235. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. t.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. const std::string req = "GET / HTTP/1.1\r\n"
  10243. "Transfer-Encoding: chunked\r\n"
  10244. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10245. "\r\n"
  10246. "0\r\n"
  10247. "Content-Length: 10\r\n"
  10248. "Host: internal.local\r\n"
  10249. "Content-Type: malicious/content\r\n"
  10250. "Cookie: any\r\n"
  10251. "Set-Cookie: any\r\n"
  10252. "X-Forwarded-For: attacker.com\r\n"
  10253. "X-Real-Ip: 1.1.1.1\r\n"
  10254. "X-Hello: hello\r\n"
  10255. "X-World: world\r\n"
  10256. "\r\n";
  10257. std::string res;
  10258. ASSERT_TRUE(send_request(1, req, &res));
  10259. }
  10260. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10261. Server svr;
  10262. std::string observed_remote_addr;
  10263. std::string observed_xff;
  10264. svr.Get("/ip", [&](const Request &req, Response &res) {
  10265. observed_remote_addr = req.remote_addr;
  10266. observed_xff = req.get_header_value("X-Forwarded-For");
  10267. res.set_content("ok", "text/plain");
  10268. });
  10269. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10270. auto se = detail::scope_exit([&] {
  10271. svr.stop();
  10272. t.join();
  10273. ASSERT_FALSE(svr.is_running());
  10274. });
  10275. svr.wait_until_ready();
  10276. Client cli(HOST, PORT);
  10277. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10278. ASSERT_TRUE(res);
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. EXPECT_EQ(observed_xff, "203.0.113.66");
  10281. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10282. observed_remote_addr == "127.0.0.1");
  10283. }
  10284. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10285. Server svr;
  10286. svr.set_trusted_proxies({"203.0.113.66"});
  10287. std::string observed_remote_addr;
  10288. std::string observed_xff;
  10289. svr.Get("/ip", [&](const Request &req, Response &res) {
  10290. observed_remote_addr = req.remote_addr;
  10291. observed_xff = req.get_header_value("X-Forwarded-For");
  10292. res.set_content("ok", "text/plain");
  10293. });
  10294. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. t.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.wait_until_ready();
  10301. Client cli(HOST, PORT);
  10302. auto res = cli.Get("/ip");
  10303. ASSERT_TRUE(res);
  10304. EXPECT_EQ(StatusCode::OK_200, res->status);
  10305. EXPECT_EQ(observed_xff, "");
  10306. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10307. observed_remote_addr == "127.0.0.1");
  10308. }
  10309. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10310. Server svr;
  10311. svr.set_trusted_proxies({"203.0.113.66"});
  10312. std::string observed_remote_addr;
  10313. std::string observed_xff;
  10314. svr.Get("/ip", [&](const Request &req, Response &res) {
  10315. observed_remote_addr = req.remote_addr;
  10316. observed_xff = req.get_header_value("X-Forwarded-For");
  10317. res.set_content("ok", "text/plain");
  10318. });
  10319. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10320. auto se = detail::scope_exit([&] {
  10321. svr.stop();
  10322. t.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. svr.wait_until_ready();
  10326. Client cli(HOST, PORT);
  10327. auto res =
  10328. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10329. ASSERT_TRUE(res);
  10330. EXPECT_EQ(StatusCode::OK_200, res->status);
  10331. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10332. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10333. }
  10334. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10335. Server svr;
  10336. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10337. std::string observed_remote_addr;
  10338. std::string observed_xff;
  10339. svr.Get("/ip", [&](const Request &req, Response &res) {
  10340. observed_remote_addr = req.remote_addr;
  10341. observed_xff = req.get_header_value("X-Forwarded-For");
  10342. res.set_content("ok", "text/plain");
  10343. });
  10344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. ASSERT_FALSE(svr.is_running());
  10349. });
  10350. svr.wait_until_ready();
  10351. Client cli(HOST, PORT);
  10352. auto res = cli.Get(
  10353. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10354. ASSERT_TRUE(res);
  10355. EXPECT_EQ(StatusCode::OK_200, res->status);
  10356. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10357. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10358. }
  10359. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10360. Server svr;
  10361. svr.set_trusted_proxies({"192.0.2.45"});
  10362. std::string observed_remote_addr;
  10363. std::string observed_xff;
  10364. svr.Get("/ip", [&](const Request &req, Response &res) {
  10365. observed_remote_addr = req.remote_addr;
  10366. observed_xff = req.get_header_value("X-Forwarded-For");
  10367. res.set_content("ok", "text/plain");
  10368. });
  10369. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10370. auto se = detail::scope_exit([&] {
  10371. svr.stop();
  10372. t.join();
  10373. ASSERT_FALSE(svr.is_running());
  10374. });
  10375. svr.wait_until_ready();
  10376. Client cli(HOST, PORT);
  10377. auto res =
  10378. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10379. ASSERT_TRUE(res);
  10380. EXPECT_EQ(StatusCode::OK_200, res->status);
  10381. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10382. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10383. }
  10384. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10385. Server svr;
  10386. svr.set_trusted_proxies({"192.0.2.45"});
  10387. std::string observed_remote_addr;
  10388. std::string observed_xff;
  10389. svr.Get("/ip", [&](const Request &req, Response &res) {
  10390. observed_remote_addr = req.remote_addr;
  10391. observed_xff = req.get_header_value("X-Forwarded-For");
  10392. res.set_content("ok", "text/plain");
  10393. });
  10394. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10395. auto se = detail::scope_exit([&] {
  10396. svr.stop();
  10397. t.join();
  10398. ASSERT_FALSE(svr.is_running());
  10399. });
  10400. svr.wait_until_ready();
  10401. Client cli(HOST, PORT);
  10402. auto res = cli.Get(
  10403. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10404. ASSERT_TRUE(res);
  10405. EXPECT_EQ(StatusCode::OK_200, res->status);
  10406. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10407. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10408. }
  10409. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10410. Server svr;
  10411. svr.set_trusted_proxies({"192.0.2.45"});
  10412. std::string observed_remote_addr;
  10413. std::string observed_xff;
  10414. svr.Get("/ip", [&](const Request &req, Response &res) {
  10415. observed_remote_addr = req.remote_addr;
  10416. observed_xff = req.get_header_value("X-Forwarded-For");
  10417. res.set_content("ok", "text/plain");
  10418. });
  10419. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10420. auto se = detail::scope_exit([&] {
  10421. svr.stop();
  10422. t.join();
  10423. ASSERT_FALSE(svr.is_running());
  10424. });
  10425. svr.wait_until_ready();
  10426. std::string raw_req =
  10427. "GET /ip HTTP/1.1\r\n"
  10428. "Host: localhost\r\n"
  10429. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10430. "Connection: close\r\n"
  10431. "\r\n";
  10432. std::string out;
  10433. ASSERT_TRUE(send_request(5, raw_req, &out));
  10434. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10435. // Header parser trims surrounding whitespace of the header value
  10436. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10437. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10438. }
  10439. #ifndef _WIN32
  10440. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10441. Server svr;
  10442. svr.Post("/post", [&](const Request &req, Response &res) {
  10443. res.set_content(req.body, "text/plain");
  10444. });
  10445. svr.Put("/put", [&](const Request &req, Response &res) {
  10446. res.set_content(req.body, "text/plain");
  10447. });
  10448. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10449. res.set_content(req.body, "text/plain");
  10450. });
  10451. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10452. res.set_content(req.body, "text/plain");
  10453. });
  10454. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10455. auto se = detail::scope_exit([&] {
  10456. svr.stop();
  10457. t.join();
  10458. ASSERT_FALSE(svr.is_running());
  10459. });
  10460. svr.wait_until_ready();
  10461. std::string resp;
  10462. // POST without Content-Length
  10463. ASSERT_TRUE(send_request(5,
  10464. "POST /post HTTP/1.1\r\n"
  10465. "Host: localhost\r\n"
  10466. "Connection: close\r\n"
  10467. "\r\n",
  10468. &resp));
  10469. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10470. // PUT without Content-Length
  10471. resp.clear();
  10472. ASSERT_TRUE(send_request(5,
  10473. "PUT /put HTTP/1.1\r\n"
  10474. "Host: localhost\r\n"
  10475. "Connection: close\r\n"
  10476. "\r\n",
  10477. &resp));
  10478. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10479. // PATCH without Content-Length
  10480. resp.clear();
  10481. ASSERT_TRUE(send_request(5,
  10482. "PATCH /patch HTTP/1.1\r\n"
  10483. "Host: localhost\r\n"
  10484. "Connection: close\r\n"
  10485. "\r\n",
  10486. &resp));
  10487. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10488. // DELETE without Content-Length
  10489. resp.clear();
  10490. ASSERT_TRUE(send_request(5,
  10491. "DELETE /delete HTTP/1.1\r\n"
  10492. "Host: localhost\r\n"
  10493. "Connection: close\r\n"
  10494. "\r\n",
  10495. &resp));
  10496. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10497. }
  10498. #endif
  10499. //==============================================================================
  10500. // open_stream() Tests
  10501. //==============================================================================
  10502. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10503. std::string result;
  10504. char buf[8192];
  10505. ssize_t n;
  10506. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10507. result.append(buf, static_cast<size_t>(n));
  10508. }
  10509. return result;
  10510. }
  10511. // Mock stream for unit tests
  10512. class MockStream : public Stream {
  10513. public:
  10514. std::string data;
  10515. size_t pos = 0;
  10516. ssize_t error_after = -1; // -1 = no error
  10517. explicit MockStream(const std::string &d, ssize_t err = -1)
  10518. : data(d), error_after(err) {}
  10519. bool is_readable() const override { return true; }
  10520. bool wait_readable() const override { return true; }
  10521. bool wait_writable() const override { return true; }
  10522. ssize_t read(char *ptr, size_t size) override {
  10523. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10524. if (pos >= data.size()) return 0;
  10525. size_t limit =
  10526. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10527. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10528. std::memcpy(ptr, data.data() + pos, to_read);
  10529. pos += to_read;
  10530. return static_cast<ssize_t>(to_read);
  10531. }
  10532. ssize_t write(const char *, size_t) override { return -1; }
  10533. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10534. ip = "127.0.0.1";
  10535. port = 0;
  10536. }
  10537. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10538. ip = "127.0.0.1";
  10539. port = 0;
  10540. }
  10541. socket_t socket() const override { return INVALID_SOCKET; }
  10542. time_t duration() const override { return 0; }
  10543. };
  10544. TEST(StreamHandleTest, Basic) {
  10545. ClientImpl::StreamHandle handle;
  10546. EXPECT_FALSE(handle.is_valid());
  10547. handle.response = detail::make_unique<Response>();
  10548. handle.error = Error::Connection;
  10549. EXPECT_FALSE(handle.is_valid());
  10550. handle.error = Error::Success;
  10551. EXPECT_TRUE(handle.is_valid());
  10552. }
  10553. TEST(BodyReaderTest, Basic) {
  10554. MockStream stream("Hello, World!");
  10555. detail::BodyReader reader;
  10556. reader.stream = &stream;
  10557. reader.content_length = 13;
  10558. char buf[32];
  10559. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10560. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10561. EXPECT_TRUE(reader.eof);
  10562. }
  10563. TEST(BodyReaderTest, NoStream) {
  10564. detail::BodyReader reader;
  10565. char buf[32];
  10566. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10567. EXPECT_EQ(Error::Connection, reader.last_error);
  10568. }
  10569. TEST(BodyReaderTest, Error) {
  10570. MockStream stream("Hello, World!", 5);
  10571. detail::BodyReader reader;
  10572. reader.stream = &stream;
  10573. reader.content_length = 13;
  10574. char buf[32];
  10575. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10576. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10577. EXPECT_EQ(Error::Read, reader.last_error);
  10578. }
  10579. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10580. // Mock-based StreamHandle tests relying on private internals are removed.
  10581. class OpenStreamTest : public ::testing::Test {
  10582. protected:
  10583. void SetUp() override {
  10584. svr_.Get("/hello", [](const Request &, Response &res) {
  10585. res.set_content("Hello World!", "text/plain");
  10586. });
  10587. svr_.Get("/large", [](const Request &, Response &res) {
  10588. res.set_content(std::string(10000, 'X'), "text/plain");
  10589. });
  10590. svr_.Get("/chunked", [](const Request &, Response &res) {
  10591. res.set_chunked_content_provider("text/plain",
  10592. [](size_t offset, DataSink &sink) {
  10593. if (offset < 15) {
  10594. sink.write("chunk", 5);
  10595. return true;
  10596. }
  10597. sink.done();
  10598. return true;
  10599. });
  10600. });
  10601. svr_.Get("/compressible", [](const Request &, Response &res) {
  10602. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10603. DataSink &sink) {
  10604. if (offset < 100 * 1024) {
  10605. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10606. sink.write(chunk.data(), chunk.size());
  10607. return true;
  10608. }
  10609. sink.done();
  10610. return true;
  10611. });
  10612. });
  10613. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10614. [](const Request & /*req*/, Response &res) {
  10615. auto i = new int(0);
  10616. res.set_header("Trailer", "Content-Length, X-Allowed");
  10617. res.set_chunked_content_provider(
  10618. "text/plain",
  10619. [i](size_t /*offset*/, DataSink &sink) {
  10620. switch (*i) {
  10621. case 0: sink.os << "123"; break;
  10622. case 1: sink.os << "456"; break;
  10623. case 2: sink.os << "789"; break;
  10624. case 3: {
  10625. sink.done_with_trailer(
  10626. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10627. } break;
  10628. }
  10629. (*i)++;
  10630. return true;
  10631. },
  10632. [i](bool success) {
  10633. EXPECT_TRUE(success);
  10634. delete i;
  10635. });
  10636. });
  10637. // Echo headers endpoint for header-related tests
  10638. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10639. std::string body;
  10640. for (const auto &h : req.headers) {
  10641. body.append(h.first);
  10642. body.push_back(':');
  10643. body.append(h.second);
  10644. body.push_back('\n');
  10645. }
  10646. res.set_content(body, "text/plain");
  10647. });
  10648. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10649. std::string body;
  10650. for (const auto &h : req.headers) {
  10651. body.append(h.first);
  10652. body.push_back(':');
  10653. body.append(h.second);
  10654. body.push_back('\n');
  10655. }
  10656. res.set_content(body, "text/plain");
  10657. });
  10658. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10659. svr_.wait_until_ready();
  10660. }
  10661. void TearDown() override {
  10662. svr_.stop();
  10663. if (thread_.joinable()) thread_.join();
  10664. }
  10665. Server svr_;
  10666. std::thread thread_;
  10667. };
  10668. TEST_F(OpenStreamTest, Basic) {
  10669. Client cli("127.0.0.1", 8787);
  10670. auto handle = cli.open_stream("GET", "/hello");
  10671. EXPECT_TRUE(handle.is_valid());
  10672. EXPECT_EQ("Hello World!", read_all(handle));
  10673. }
  10674. TEST_F(OpenStreamTest, SmallBuffer) {
  10675. Client cli("127.0.0.1", 8787);
  10676. auto handle = cli.open_stream("GET", "/hello");
  10677. std::string result;
  10678. char buf[4];
  10679. ssize_t n;
  10680. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10681. result.append(buf, static_cast<size_t>(n));
  10682. EXPECT_EQ("Hello World!", result);
  10683. }
  10684. TEST_F(OpenStreamTest, DefaultHeaders) {
  10685. Client cli("127.0.0.1", 8787);
  10686. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10687. {
  10688. auto handle = cli.open_stream("GET", "/echo-headers");
  10689. ASSERT_TRUE(handle.is_valid());
  10690. auto body = read_all(handle);
  10691. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10692. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10693. std::string::npos);
  10694. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10695. }
  10696. // open_stream POST with body and no explicit content_type should NOT add
  10697. // text/plain Content-Type (behavior differs from non-streaming path), but
  10698. // should include Content-Length
  10699. {
  10700. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10701. ASSERT_TRUE(handle.is_valid());
  10702. auto body = read_all(handle);
  10703. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10704. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10705. }
  10706. // open_stream POST with explicit Content-Type should preserve it
  10707. {
  10708. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10709. {{"Content-Type", "application/custom"}},
  10710. "{}", "application/custom");
  10711. ASSERT_TRUE(handle.is_valid());
  10712. auto body = read_all(handle);
  10713. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10714. }
  10715. // User-specified User-Agent must not be overwritten for stream API
  10716. {
  10717. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10718. {{"User-Agent", "MyAgent/1.2"}});
  10719. ASSERT_TRUE(handle.is_valid());
  10720. auto body = read_all(handle);
  10721. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10722. }
  10723. }
  10724. TEST_F(OpenStreamTest, Large) {
  10725. Client cli("127.0.0.1", 8787);
  10726. auto handle = cli.open_stream("GET", "/large");
  10727. EXPECT_EQ(10000u, read_all(handle).size());
  10728. }
  10729. TEST_F(OpenStreamTest, ConnectionError) {
  10730. Client cli("127.0.0.1", 9999);
  10731. auto handle = cli.open_stream("GET", "/hello");
  10732. EXPECT_FALSE(handle.is_valid());
  10733. }
  10734. TEST_F(OpenStreamTest, Chunked) {
  10735. Client cli("127.0.0.1", 8787);
  10736. auto handle = cli.open_stream("GET", "/chunked");
  10737. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10738. "Transfer-Encoding") == "chunked");
  10739. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10740. }
  10741. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10742. Client cli("127.0.0.1", 8787);
  10743. auto handle =
  10744. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10745. ASSERT_TRUE(handle.is_valid());
  10746. // Consume body to allow trailers to be received/parsed
  10747. auto body = read_all(handle);
  10748. // Explicitly parse trailers (ensure trailers are available for assertion)
  10749. handle.parse_trailers_if_needed();
  10750. EXPECT_EQ(std::string("123456789"), body);
  10751. // The response should include a Trailer header declaring both names
  10752. ASSERT_TRUE(handle.response);
  10753. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10754. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10755. handle.response->get_header_value("Trailer"));
  10756. // Prohibited trailer must not be present
  10757. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10758. // Allowed trailer should be present
  10759. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10760. EXPECT_EQ(std::string("yes"),
  10761. handle.response->get_trailer_value("X-Allowed"));
  10762. // Verify trailers are NOT present as regular headers
  10763. EXPECT_EQ(std::string(""),
  10764. handle.response->get_header_value("Content-Length"));
  10765. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10766. }
  10767. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10768. TEST_F(OpenStreamTest, Gzip) {
  10769. Client cli("127.0.0.1", 8787);
  10770. auto handle = cli.open_stream("GET", "/compressible", {},
  10771. {{"Accept-Encoding", "gzip"}});
  10772. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10773. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10774. }
  10775. #endif
  10776. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10777. TEST_F(OpenStreamTest, Brotli) {
  10778. Client cli("127.0.0.1", 8787);
  10779. auto handle =
  10780. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10781. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10782. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10783. }
  10784. #endif
  10785. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10786. TEST_F(OpenStreamTest, Zstd) {
  10787. Client cli("127.0.0.1", 8787);
  10788. auto handle = cli.open_stream("GET", "/compressible", {},
  10789. {{"Accept-Encoding", "zstd"}});
  10790. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10791. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10792. }
  10793. #endif
  10794. #ifdef CPPHTTPLIB_SSL_ENABLED
  10795. class SSLOpenStreamTest : public ::testing::Test {
  10796. protected:
  10797. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10798. void SetUp() override {
  10799. svr_.Get("/hello", [](const Request &, Response &res) {
  10800. res.set_content("Hello SSL World!", "text/plain");
  10801. });
  10802. svr_.Get("/chunked", [](const Request &, Response &res) {
  10803. res.set_chunked_content_provider("text/plain",
  10804. [](size_t offset, DataSink &sink) {
  10805. if (offset < 15) {
  10806. sink.write("chunk", 5);
  10807. return true;
  10808. }
  10809. sink.done();
  10810. return true;
  10811. });
  10812. });
  10813. svr_.Post("/echo", [](const Request &req, Response &res) {
  10814. res.set_content(req.body, req.get_header_value("Content-Type"));
  10815. });
  10816. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10817. std::string body = req.body;
  10818. res.set_chunked_content_provider(
  10819. "text/plain", [body](size_t offset, DataSink &sink) {
  10820. if (offset < body.size()) {
  10821. sink.write(body.data() + offset, body.size() - offset);
  10822. }
  10823. sink.done();
  10824. return true;
  10825. });
  10826. });
  10827. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10828. svr_.wait_until_ready();
  10829. }
  10830. void TearDown() override {
  10831. svr_.stop();
  10832. if (thread_.joinable()) thread_.join();
  10833. }
  10834. SSLServer svr_;
  10835. std::thread thread_;
  10836. };
  10837. TEST_F(SSLOpenStreamTest, Basic) {
  10838. SSLClient cli("127.0.0.1", 8788);
  10839. cli.enable_server_certificate_verification(false);
  10840. auto handle = cli.open_stream("GET", "/hello");
  10841. ASSERT_TRUE(handle.is_valid());
  10842. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10843. }
  10844. TEST_F(SSLOpenStreamTest, Chunked) {
  10845. SSLClient cli("127.0.0.1", 8788);
  10846. cli.enable_server_certificate_verification(false);
  10847. auto handle = cli.open_stream("GET", "/chunked");
  10848. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10849. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10850. "Transfer-Encoding") == "chunked");
  10851. auto body = read_all(handle);
  10852. EXPECT_EQ("chunkchunkchunk", body);
  10853. }
  10854. TEST_F(SSLOpenStreamTest, Post) {
  10855. SSLClient cli("127.0.0.1", 8788);
  10856. cli.enable_server_certificate_verification(false);
  10857. auto handle =
  10858. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10859. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10860. EXPECT_EQ(200, handle.response->status);
  10861. auto body = read_all(handle);
  10862. EXPECT_EQ("Hello SSL POST", body);
  10863. }
  10864. TEST_F(SSLOpenStreamTest, PostChunked) {
  10865. SSLClient cli("127.0.0.1", 8788);
  10866. cli.enable_server_certificate_verification(false);
  10867. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10868. "Chunked SSL Data", "text/plain");
  10869. ASSERT_TRUE(handle.is_valid());
  10870. EXPECT_EQ(200, handle.response->status);
  10871. auto body = read_all(handle);
  10872. EXPECT_EQ("Chunked SSL Data", body);
  10873. }
  10874. #endif // CPPHTTPLIB_SSL_ENABLED
  10875. //==============================================================================
  10876. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10877. // results for various scenarios.
  10878. //==============================================================================
  10879. TEST(ParityTest, GetVsOpenStream) {
  10880. Server svr;
  10881. const std::string path = "/parity";
  10882. const std::string content = "Parity test content: hello world";
  10883. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10884. res.set_content(content, "text/plain");
  10885. });
  10886. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10887. auto se = detail::scope_exit([&] {
  10888. svr.stop();
  10889. t.join();
  10890. ASSERT_FALSE(svr.is_running());
  10891. });
  10892. svr.wait_until_ready();
  10893. Client cli(HOST, PORT);
  10894. // Non-stream path
  10895. auto r1 = cli.Get(path);
  10896. ASSERT_TRUE(r1);
  10897. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10898. // Stream path
  10899. auto h = cli.open_stream("GET", path);
  10900. ASSERT_TRUE(h.is_valid());
  10901. EXPECT_EQ(r1->body, read_all(h));
  10902. }
  10903. // Helper to compress data with provided compressor type T
  10904. template <typename Compressor>
  10905. static std::string compress_payload_for_parity(const std::string &in) {
  10906. std::string out;
  10907. Compressor compressor;
  10908. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10909. [&](const char *data, size_t n) {
  10910. out.append(data, n);
  10911. return true;
  10912. });
  10913. EXPECT_TRUE(ok);
  10914. return out;
  10915. }
  10916. // Helper function for compression parity tests
  10917. template <typename Compressor>
  10918. static void test_compression_parity(const std::string &original,
  10919. const std::string &path,
  10920. const std::string &encoding) {
  10921. const std::string compressed =
  10922. compress_payload_for_parity<Compressor>(original);
  10923. Server svr;
  10924. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10925. res.set_content(compressed, "application/octet-stream");
  10926. res.set_header("Content-Encoding", encoding);
  10927. });
  10928. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. t.join();
  10932. ASSERT_FALSE(svr.is_running());
  10933. });
  10934. svr.wait_until_ready();
  10935. Client cli(HOST, PORT);
  10936. // Non-streaming
  10937. {
  10938. auto res = cli.Get(path);
  10939. ASSERT_TRUE(res);
  10940. EXPECT_EQ(StatusCode::OK_200, res->status);
  10941. EXPECT_EQ(original, res->body);
  10942. }
  10943. // Streaming
  10944. {
  10945. auto h = cli.open_stream("GET", path);
  10946. ASSERT_TRUE(h.is_valid());
  10947. EXPECT_EQ(original, read_all(h));
  10948. }
  10949. }
  10950. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10951. TEST(ParityTest, Gzip) {
  10952. test_compression_parity<detail::gzip_compressor>(
  10953. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10954. }
  10955. #endif
  10956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10957. TEST(ParityTest, Brotli) {
  10958. test_compression_parity<detail::brotli_compressor>(
  10959. "Hello, brotli parity test payload", "/parity-br", "br");
  10960. }
  10961. #endif
  10962. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10963. TEST(ParityTest, Zstd) {
  10964. test_compression_parity<detail::zstd_compressor>(
  10965. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10966. }
  10967. #endif
  10968. //==============================================================================
  10969. // New Stream API Tests
  10970. //==============================================================================
  10971. inline std::string read_body(httplib::stream::Result &result) {
  10972. std::string body;
  10973. while (result.next()) {
  10974. body.append(result.data(), result.size());
  10975. }
  10976. return body;
  10977. }
  10978. TEST(ClientConnectionTest, Basic) {
  10979. httplib::ClientConnection conn;
  10980. EXPECT_FALSE(conn.is_open());
  10981. conn.sock = 1;
  10982. EXPECT_TRUE(conn.is_open());
  10983. httplib::ClientConnection conn2(std::move(conn));
  10984. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10985. conn2.sock = INVALID_SOCKET;
  10986. }
  10987. // Unified test server for all stream::* tests
  10988. class StreamApiTest : public ::testing::Test {
  10989. protected:
  10990. void SetUp() override {
  10991. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10992. res.set_content("Hello World!", "text/plain");
  10993. });
  10994. svr_.Get("/echo-params",
  10995. [](const httplib::Request &req, httplib::Response &res) {
  10996. std::string r;
  10997. for (const auto &p : req.params) {
  10998. if (!r.empty()) r += "&";
  10999. r += p.first + "=" + p.second;
  11000. }
  11001. res.set_content(r, "text/plain");
  11002. });
  11003. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11004. res.set_content(req.body, req.get_header_value("Content-Type"));
  11005. });
  11006. svr_.Post("/echo-headers",
  11007. [](const httplib::Request &req, httplib::Response &res) {
  11008. std::string r;
  11009. for (const auto &h : req.headers)
  11010. r += h.first + ": " + h.second + "\n";
  11011. res.set_content(r, "text/plain");
  11012. });
  11013. svr_.Post("/echo-params",
  11014. [](const httplib::Request &req, httplib::Response &res) {
  11015. std::string r = "params:";
  11016. for (const auto &p : req.params)
  11017. r += p.first + "=" + p.second + ";";
  11018. res.set_content(r + " body:" + req.body, "text/plain");
  11019. });
  11020. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11021. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11022. });
  11023. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11024. res.set_content("PUT:" + req.body, "text/plain");
  11025. });
  11026. svr_.Patch("/echo",
  11027. [](const httplib::Request &req, httplib::Response &res) {
  11028. res.set_content("PATCH:" + req.body, "text/plain");
  11029. });
  11030. svr_.Delete(
  11031. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11032. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11033. "text/plain");
  11034. });
  11035. svr_.Get("/head-test",
  11036. [](const httplib::Request &, httplib::Response &res) {
  11037. res.set_content("body for HEAD", "text/plain");
  11038. });
  11039. svr_.Options("/options",
  11040. [](const httplib::Request &, httplib::Response &res) {
  11041. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11042. });
  11043. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11044. svr_.wait_until_ready();
  11045. }
  11046. void TearDown() override {
  11047. svr_.stop();
  11048. if (thread_.joinable()) thread_.join();
  11049. }
  11050. httplib::Server svr_;
  11051. std::thread thread_;
  11052. };
  11053. // stream::Get tests
  11054. TEST_F(StreamApiTest, GetBasic) {
  11055. httplib::Client cli(HOST, PORT);
  11056. auto result = httplib::stream::Get(cli, "/hello");
  11057. ASSERT_TRUE(result.is_valid());
  11058. EXPECT_EQ(200, result.status());
  11059. EXPECT_EQ("Hello World!", read_body(result));
  11060. }
  11061. TEST_F(StreamApiTest, GetWithParams) {
  11062. httplib::Client cli(HOST, PORT);
  11063. httplib::Params params{{"foo", "bar"}};
  11064. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11065. ASSERT_TRUE(result.is_valid());
  11066. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11067. }
  11068. TEST_F(StreamApiTest, GetConnectionError) {
  11069. httplib::Client cli(HOST, 9999);
  11070. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11071. }
  11072. TEST_F(StreamApiTest, Get404) {
  11073. httplib::Client cli(HOST, PORT);
  11074. auto result = httplib::stream::Get(cli, "/nonexistent");
  11075. EXPECT_TRUE(result.is_valid());
  11076. EXPECT_EQ(404, result.status());
  11077. }
  11078. // stream::Post tests
  11079. TEST_F(StreamApiTest, PostBasic) {
  11080. httplib::Client cli(HOST, PORT);
  11081. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11082. "application/json");
  11083. ASSERT_TRUE(result.is_valid());
  11084. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11085. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11086. }
  11087. TEST_F(StreamApiTest, PostWithHeaders) {
  11088. httplib::Client cli(HOST, PORT);
  11089. httplib::Headers headers{{"X-Custom", "value"}};
  11090. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11091. "text/plain");
  11092. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11093. }
  11094. TEST_F(StreamApiTest, PostWithParams) {
  11095. httplib::Client cli(HOST, PORT);
  11096. httplib::Params params{{"k", "v"}};
  11097. auto result =
  11098. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11099. auto body = read_body(result);
  11100. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11101. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11102. }
  11103. TEST_F(StreamApiTest, PostLarge) {
  11104. httplib::Client cli(HOST, PORT);
  11105. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11106. size_t total = 0;
  11107. while (result.next()) {
  11108. total += result.size();
  11109. }
  11110. EXPECT_EQ(100u * 1024u, total);
  11111. }
  11112. // stream::Put/Patch tests
  11113. TEST_F(StreamApiTest, PutAndPatch) {
  11114. httplib::Client cli(HOST, PORT);
  11115. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11116. EXPECT_EQ("PUT:test", read_body(put));
  11117. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11118. EXPECT_EQ("PATCH:test", read_body(patch));
  11119. }
  11120. // stream::Delete tests
  11121. TEST_F(StreamApiTest, Delete) {
  11122. httplib::Client cli(HOST, PORT);
  11123. auto del1 = httplib::stream::Delete(cli, "/resource");
  11124. EXPECT_EQ("Deleted", read_body(del1));
  11125. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11126. EXPECT_EQ("Deleted:data", read_body(del2));
  11127. }
  11128. // stream::Head/Options tests
  11129. TEST_F(StreamApiTest, HeadAndOptions) {
  11130. httplib::Client cli(HOST, PORT);
  11131. auto head = httplib::stream::Head(cli, "/head-test");
  11132. EXPECT_TRUE(head.is_valid());
  11133. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11134. auto opts = httplib::stream::Options(cli, "/options");
  11135. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11136. }
  11137. // SSL stream::* tests
  11138. #ifdef CPPHTTPLIB_SSL_ENABLED
  11139. class SSLStreamApiTest : public ::testing::Test {
  11140. protected:
  11141. void SetUp() override {
  11142. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11143. res.set_content("Hello SSL!", "text/plain");
  11144. });
  11145. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11146. res.set_content(req.body, "text/plain");
  11147. });
  11148. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  11149. svr_.wait_until_ready();
  11150. }
  11151. void TearDown() override {
  11152. svr_.stop();
  11153. if (thread_.joinable()) thread_.join();
  11154. }
  11155. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11156. std::thread thread_;
  11157. };
  11158. TEST_F(SSLStreamApiTest, GetAndPost) {
  11159. httplib::SSLClient cli("127.0.0.1", 8803);
  11160. cli.enable_server_certificate_verification(false);
  11161. auto get = httplib::stream::Get(cli, "/hello");
  11162. EXPECT_EQ("Hello SSL!", read_body(get));
  11163. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11164. EXPECT_EQ("test", read_body(post));
  11165. }
  11166. #endif
  11167. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11168. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11169. // BodyReader
  11170. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11171. // Test that read timeout during streaming is detected
  11172. // Use a large content-length response where server delays mid-stream
  11173. Server svr;
  11174. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11175. // Send a large response with delay in the middle
  11176. res.set_content_provider(
  11177. 1000, // content_length
  11178. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11179. if (offset < 100) {
  11180. // Send first 100 bytes immediately
  11181. std::string data(100, 'A');
  11182. sink.write(data.c_str(), data.size());
  11183. return true;
  11184. }
  11185. // Then delay longer than client timeout
  11186. std::this_thread::sleep_for(std::chrono::seconds(3));
  11187. std::string data(900, 'B');
  11188. sink.write(data.c_str(), data.size());
  11189. return true;
  11190. });
  11191. });
  11192. auto port = 8091;
  11193. std::thread t([&]() { svr.listen("localhost", port); });
  11194. svr.wait_until_ready();
  11195. Client cli("localhost", port);
  11196. cli.set_read_timeout(1, 0); // 1 second timeout
  11197. auto handle = cli.open_stream("GET", "/slow-stream");
  11198. ASSERT_TRUE(handle.is_valid());
  11199. char buf[256];
  11200. ssize_t total = 0;
  11201. ssize_t n;
  11202. bool got_error = false;
  11203. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11204. total += n;
  11205. }
  11206. if (n < 0) {
  11207. got_error = true;
  11208. // Should be timeout or read error
  11209. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11210. handle.get_read_error() == Error::Read)
  11211. << "Actual error: " << to_string(handle.get_read_error());
  11212. }
  11213. // Either we got an error, or we got less data than expected
  11214. EXPECT_TRUE(got_error || total < 1000)
  11215. << "Expected timeout but got all " << total << " bytes";
  11216. svr.stop();
  11217. t.join();
  11218. }
  11219. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11220. // Test connection closed detection via BodyReader
  11221. Server svr;
  11222. std::atomic<bool> close_now{false};
  11223. svr.Get("/will-close", [&](const Request &, Response &res) {
  11224. res.set_content_provider(
  11225. 10000, // Large content_length that we won't fully send
  11226. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11227. if (offset < 100) {
  11228. std::string data(100, 'X');
  11229. sink.write(data.c_str(), data.size());
  11230. return true;
  11231. }
  11232. // Wait for signal then abort
  11233. while (!close_now) {
  11234. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11235. }
  11236. return false; // Abort - server will close connection
  11237. });
  11238. });
  11239. auto port = 8092;
  11240. std::thread t([&]() { svr.listen("localhost", port); });
  11241. svr.wait_until_ready();
  11242. Client cli("localhost", port);
  11243. auto handle = cli.open_stream("GET", "/will-close");
  11244. ASSERT_TRUE(handle.is_valid());
  11245. char buf[256];
  11246. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11247. EXPECT_GT(n, 0) << "First read should succeed";
  11248. // Signal server to close
  11249. close_now = true;
  11250. // Keep reading until error or EOF
  11251. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11252. // Keep reading
  11253. }
  11254. // Should get an error since content_length wasn't satisfied
  11255. if (n < 0) {
  11256. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11257. handle.get_read_error() == Error::Read)
  11258. << "Actual error: " << to_string(handle.get_read_error());
  11259. }
  11260. svr.stop();
  11261. t.join();
  11262. }
  11263. #ifdef CPPHTTPLIB_SSL_ENABLED
  11264. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11265. // Test that read timeout during SSL streaming is detected
  11266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11267. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11268. res.set_content_provider(
  11269. 1000, "text/plain",
  11270. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11271. if (offset < 100) {
  11272. std::string data(100, 'A');
  11273. sink.write(data.c_str(), data.size());
  11274. return true;
  11275. }
  11276. std::this_thread::sleep_for(std::chrono::seconds(3));
  11277. std::string data(900, 'B');
  11278. sink.write(data.c_str(), data.size());
  11279. return true;
  11280. });
  11281. });
  11282. auto port = 8093;
  11283. std::thread t([&]() { svr.listen("localhost", port); });
  11284. svr.wait_until_ready();
  11285. SSLClient cli("localhost", port);
  11286. cli.enable_server_certificate_verification(false);
  11287. cli.set_read_timeout(1, 0); // 1 second timeout
  11288. auto handle = cli.open_stream("GET", "/slow-stream");
  11289. ASSERT_TRUE(handle.is_valid());
  11290. char buf[256];
  11291. ssize_t total = 0;
  11292. ssize_t n;
  11293. bool got_error = false;
  11294. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11295. total += n;
  11296. }
  11297. if (n < 0) {
  11298. got_error = true;
  11299. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11300. handle.get_read_error() == Error::Read)
  11301. << "Actual error: " << to_string(handle.get_read_error());
  11302. }
  11303. EXPECT_TRUE(got_error || total < 1000)
  11304. << "Expected timeout but got all " << total << " bytes";
  11305. svr.stop();
  11306. t.join();
  11307. }
  11308. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11309. // Test SSL connection closed detection
  11310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11311. std::atomic<bool> close_now{false};
  11312. svr.Get("/will-close", [&](const Request &, Response &res) {
  11313. res.set_content_provider(
  11314. 10000, "text/plain",
  11315. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11316. if (offset < 100) {
  11317. std::string data(100, 'X');
  11318. sink.write(data.c_str(), data.size());
  11319. return true;
  11320. }
  11321. while (!close_now) {
  11322. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11323. }
  11324. return false;
  11325. });
  11326. });
  11327. auto port = 8094;
  11328. std::thread t([&]() { svr.listen("localhost", port); });
  11329. svr.wait_until_ready();
  11330. SSLClient cli("localhost", port);
  11331. cli.enable_server_certificate_verification(false);
  11332. auto handle = cli.open_stream("GET", "/will-close");
  11333. ASSERT_TRUE(handle.is_valid());
  11334. char buf[256];
  11335. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11336. EXPECT_GT(n, 0);
  11337. // Signal server to close
  11338. close_now = true;
  11339. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11340. // Keep reading
  11341. }
  11342. if (n < 0) {
  11343. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11344. handle.get_read_error() == Error::Read)
  11345. << "Actual error: " << to_string(handle.get_read_error());
  11346. }
  11347. svr.stop();
  11348. t.join();
  11349. }
  11350. #endif
  11351. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11352. using namespace httplib;
  11353. // Create a test file
  11354. const char *fname = "etag_testfile.txt";
  11355. const char *content = "etag-content";
  11356. {
  11357. std::ofstream ofs(fname);
  11358. ofs << content;
  11359. ASSERT_TRUE(ofs.good());
  11360. }
  11361. Server svr;
  11362. svr.set_mount_point("/static", ".");
  11363. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11364. svr.wait_until_ready();
  11365. Client cli(HOST, PORT);
  11366. // First request: should get 200 with ETag header
  11367. auto res1 = cli.Get("/static/etag_testfile.txt");
  11368. ASSERT_TRUE(res1);
  11369. ASSERT_EQ(200, res1->status);
  11370. ASSERT_TRUE(res1->has_header("ETag"));
  11371. std::string etag = res1->get_header_value("ETag");
  11372. EXPECT_FALSE(etag.empty());
  11373. // Verify ETag format: W/"hex-hex"
  11374. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11375. EXPECT_EQ('W', etag[0]);
  11376. EXPECT_EQ('/', etag[1]);
  11377. EXPECT_EQ('"', etag[2]);
  11378. EXPECT_EQ('"', etag.back());
  11379. // Exact match: expect 304 Not Modified
  11380. Headers h2 = {{"If-None-Match", etag}};
  11381. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11382. ASSERT_TRUE(res2);
  11383. EXPECT_EQ(304, res2->status);
  11384. // Wildcard match: expect 304 Not Modified
  11385. Headers h3 = {{"If-None-Match", "*"}};
  11386. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11387. ASSERT_TRUE(res3);
  11388. EXPECT_EQ(304, res3->status);
  11389. // Non-matching ETag: expect 200
  11390. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11391. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11392. ASSERT_TRUE(res4);
  11393. EXPECT_EQ(200, res4->status);
  11394. // Multiple ETags with one matching: expect 304
  11395. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11396. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11397. ASSERT_TRUE(res5);
  11398. EXPECT_EQ(304, res5->status);
  11399. svr.stop();
  11400. t.join();
  11401. std::remove(fname);
  11402. }
  11403. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11404. using namespace httplib;
  11405. Server svr;
  11406. svr.set_mount_point("/static", ".");
  11407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11408. svr.wait_until_ready();
  11409. Client cli(HOST, PORT);
  11410. // Send If-None-Match: * to a non-existent file
  11411. Headers h = {{"If-None-Match", "*"}};
  11412. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11413. ASSERT_TRUE(res);
  11414. EXPECT_EQ(404, res->status);
  11415. svr.stop();
  11416. t.join();
  11417. }
  11418. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11419. using namespace httplib;
  11420. // Create a test file
  11421. const char *fname = "ims_testfile.txt";
  11422. const char *content = "if-modified-since-test";
  11423. {
  11424. std::ofstream ofs(fname);
  11425. ofs << content;
  11426. ASSERT_TRUE(ofs.good());
  11427. }
  11428. Server svr;
  11429. svr.set_mount_point("/static", ".");
  11430. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11431. svr.wait_until_ready();
  11432. Client cli(HOST, PORT);
  11433. // First request: should get 200 with Last-Modified header
  11434. auto res1 = cli.Get("/static/ims_testfile.txt");
  11435. ASSERT_TRUE(res1);
  11436. ASSERT_EQ(200, res1->status);
  11437. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11438. std::string last_modified = res1->get_header_value("Last-Modified");
  11439. EXPECT_FALSE(last_modified.empty());
  11440. // If-Modified-Since with same time: expect 304
  11441. Headers h2 = {{"If-Modified-Since", last_modified}};
  11442. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11443. ASSERT_TRUE(res2);
  11444. EXPECT_EQ(304, res2->status);
  11445. // If-Modified-Since with future time: expect 304
  11446. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11447. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11448. ASSERT_TRUE(res3);
  11449. EXPECT_EQ(304, res3->status);
  11450. // If-Modified-Since with past time: expect 200
  11451. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11452. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11453. ASSERT_TRUE(res4);
  11454. EXPECT_EQ(200, res4->status);
  11455. // If-None-Match takes precedence over If-Modified-Since
  11456. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11457. ASSERT_TRUE(res1->has_header("ETag"));
  11458. std::string etag = res1->get_header_value("ETag");
  11459. Headers h5 = {{"If-None-Match", etag},
  11460. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11461. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11462. ASSERT_TRUE(res5);
  11463. EXPECT_EQ(304, res5->status);
  11464. svr.stop();
  11465. t.join();
  11466. std::remove(fname);
  11467. }
  11468. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11469. using namespace httplib;
  11470. Server svr;
  11471. // Endpoint that returns compressible content
  11472. svr.Get("/compressible", [](const Request &, Response &res) {
  11473. // Return a large enough body to trigger compression
  11474. std::string body(1000, 'a');
  11475. res.set_content(body, "text/plain");
  11476. });
  11477. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11478. svr.wait_until_ready();
  11479. Client cli(HOST, PORT);
  11480. // Request with gzip support: should get Vary header when compressed
  11481. cli.set_compress(true);
  11482. auto res1 = cli.Get("/compressible");
  11483. ASSERT_TRUE(res1);
  11484. EXPECT_EQ(200, res1->status);
  11485. // If Content-Encoding is set, Vary should also be set
  11486. if (res1->has_header("Content-Encoding")) {
  11487. EXPECT_TRUE(res1->has_header("Vary"));
  11488. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11489. }
  11490. // Request without Accept-Encoding header: should not have compression
  11491. Headers h_no_compress;
  11492. auto res2 = cli.Get("/compressible", h_no_compress);
  11493. ASSERT_TRUE(res2);
  11494. EXPECT_EQ(200, res2->status);
  11495. // Verify Vary header is present when compression is applied
  11496. // (the exact behavior depends on server configuration)
  11497. svr.stop();
  11498. t.join();
  11499. }
  11500. TEST(ETagTest, IfRangeWithETag) {
  11501. using namespace httplib;
  11502. // Create a test file with known content
  11503. const char *fname = "if_range_testfile.txt";
  11504. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11505. {
  11506. std::ofstream ofs(fname);
  11507. ofs << content;
  11508. ASSERT_TRUE(ofs.good());
  11509. }
  11510. Server svr;
  11511. svr.set_mount_point("/static", ".");
  11512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11513. svr.wait_until_ready();
  11514. Client cli(HOST, PORT);
  11515. // First request: get ETag
  11516. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11517. ASSERT_TRUE(res1);
  11518. ASSERT_EQ(200, res1->status);
  11519. ASSERT_TRUE(res1->has_header("ETag"));
  11520. std::string etag = res1->get_header_value("ETag");
  11521. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11522. // Since our server generates weak ETags (W/"..."), If-Range with our
  11523. // ETag should NOT result in partial content - it should return full content.
  11524. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11525. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11526. ASSERT_TRUE(res2);
  11527. // Weak ETag in If-Range -> full content (200), not partial (206)
  11528. EXPECT_EQ(200, res2->status);
  11529. EXPECT_EQ(content, res2->body);
  11530. EXPECT_FALSE(res2->has_header("Content-Range"));
  11531. // Range request with non-matching If-Range (ETag): should get 200 (full
  11532. // content)
  11533. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11534. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11535. ASSERT_TRUE(res3);
  11536. EXPECT_EQ(200, res3->status);
  11537. EXPECT_EQ(content, res3->body);
  11538. EXPECT_FALSE(res3->has_header("Content-Range"));
  11539. // Range request with strong ETag (hypothetical - our server doesn't generate
  11540. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11541. // should return full content)
  11542. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11543. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11544. ASSERT_TRUE(res4);
  11545. EXPECT_EQ(200, res4->status);
  11546. EXPECT_EQ(content, res4->body);
  11547. EXPECT_FALSE(res4->has_header("Content-Range"));
  11548. svr.stop();
  11549. t.join();
  11550. std::remove(fname);
  11551. }
  11552. TEST(ETagTest, IfRangeWithDate) {
  11553. using namespace httplib;
  11554. // Create a test file
  11555. const char *fname = "if_range_date_testfile.txt";
  11556. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11557. {
  11558. std::ofstream ofs(fname);
  11559. ofs << content;
  11560. ASSERT_TRUE(ofs.good());
  11561. }
  11562. Server svr;
  11563. svr.set_mount_point("/static", ".");
  11564. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11565. svr.wait_until_ready();
  11566. Client cli(HOST, PORT);
  11567. // First request: get Last-Modified
  11568. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11569. ASSERT_TRUE(res1);
  11570. ASSERT_EQ(200, res1->status);
  11571. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11572. std::string last_modified = res1->get_header_value("Last-Modified");
  11573. // Range request with matching If-Range (date): should get 206
  11574. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11575. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11576. ASSERT_TRUE(res2);
  11577. EXPECT_EQ(206, res2->status);
  11578. EXPECT_EQ("FGHIJ", res2->body);
  11579. // Range request with old If-Range date: should get 200 (full content)
  11580. Headers h3 = {{"Range", "bytes=5-9"},
  11581. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11582. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11583. ASSERT_TRUE(res3);
  11584. EXPECT_EQ(200, res3->status);
  11585. EXPECT_EQ(content, res3->body);
  11586. // Range request with future If-Range date: should get 206
  11587. Headers h4 = {{"Range", "bytes=0-4"},
  11588. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11589. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11590. ASSERT_TRUE(res4);
  11591. EXPECT_EQ(206, res4->status);
  11592. EXPECT_EQ("ABCDE", res4->body);
  11593. svr.stop();
  11594. t.join();
  11595. std::remove(fname);
  11596. }
  11597. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11598. using namespace httplib;
  11599. const char *fname = "etag_malformed.txt";
  11600. const char *content = "malformed-etag";
  11601. {
  11602. std::ofstream ofs(fname);
  11603. ofs << content;
  11604. ASSERT_TRUE(ofs.good());
  11605. }
  11606. Server svr;
  11607. svr.set_mount_point("/static", ".");
  11608. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11609. svr.wait_until_ready();
  11610. Client cli(HOST, PORT);
  11611. // baseline: should get 200 and an ETag
  11612. auto res1 = cli.Get("/static/etag_malformed.txt");
  11613. ASSERT_TRUE(res1);
  11614. ASSERT_EQ(200, res1->status);
  11615. ASSERT_TRUE(res1->has_header("ETag"));
  11616. // Malformed ETag value (missing quotes) should be treated as non-matching
  11617. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11618. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11619. ASSERT_TRUE(res_bad);
  11620. EXPECT_EQ(200, res_bad->status);
  11621. // Whitespace-only header value should be considered invalid / non-matching
  11622. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11623. "Host: localhost\r\n"
  11624. "If-None-Match: \r\n"
  11625. "Connection: close\r\n"
  11626. "\r\n";
  11627. std::string out;
  11628. ASSERT_TRUE(send_request(5, raw_req, &out));
  11629. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11630. svr.stop();
  11631. t.join();
  11632. std::remove(fname);
  11633. }
  11634. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11635. using namespace httplib;
  11636. const char *fname = "ims_invalid_format.txt";
  11637. const char *content = "ims-bad-format";
  11638. {
  11639. std::ofstream ofs(fname);
  11640. ofs << content;
  11641. ASSERT_TRUE(ofs.good());
  11642. }
  11643. Server svr;
  11644. svr.set_mount_point("/static", ".");
  11645. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11646. svr.wait_until_ready();
  11647. Client cli(HOST, PORT);
  11648. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11649. ASSERT_TRUE(res1);
  11650. ASSERT_EQ(200, res1->status);
  11651. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11652. // If-Modified-Since with invalid format should not result in 304
  11653. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11654. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11655. ASSERT_TRUE(res_bad);
  11656. EXPECT_EQ(200, res_bad->status);
  11657. // If-Range with invalid date format should be treated as mismatch -> full
  11658. // content (200)
  11659. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11660. {"If-Range", "invalid-date"}};
  11661. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11662. ASSERT_TRUE(res_ifrange);
  11663. EXPECT_EQ(200, res_ifrange->status);
  11664. svr.stop();
  11665. t.join();
  11666. std::remove(fname);
  11667. }
  11668. TEST(ETagTest, IfRangeWithMalformedETag) {
  11669. using namespace httplib;
  11670. const char *fname = "ifrange_malformed.txt";
  11671. const std::string content = "0123456789";
  11672. {
  11673. std::ofstream ofs(fname);
  11674. ofs << content;
  11675. ASSERT_TRUE(ofs.good());
  11676. }
  11677. Server svr;
  11678. svr.set_mount_point("/static", ".");
  11679. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11680. svr.wait_until_ready();
  11681. Client cli(HOST, PORT);
  11682. // First request: get ETag
  11683. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11684. ASSERT_TRUE(res1);
  11685. ASSERT_EQ(200, res1->status);
  11686. ASSERT_TRUE(res1->has_header("ETag"));
  11687. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11688. // full content (200)
  11689. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11690. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11691. ASSERT_TRUE(res2);
  11692. EXPECT_EQ(200, res2->status);
  11693. EXPECT_EQ(content, res2->body);
  11694. svr.stop();
  11695. t.join();
  11696. std::remove(fname);
  11697. }
  11698. TEST(ETagTest, ExtremeLargeDateValues) {
  11699. using namespace httplib;
  11700. const char *fname = "ims_extreme_date.txt";
  11701. const char *content = "ims-extreme-date";
  11702. {
  11703. std::ofstream ofs(fname);
  11704. ofs << content;
  11705. ASSERT_TRUE(ofs.good());
  11706. }
  11707. Server svr;
  11708. svr.set_mount_point("/static", ".");
  11709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11710. svr.wait_until_ready();
  11711. Client cli(HOST, PORT);
  11712. auto res1 = cli.Get(std::string("/static/") + fname);
  11713. ASSERT_TRUE(res1);
  11714. ASSERT_EQ(200, res1->status);
  11715. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11716. // Extremely large year that may overflow date parsing routines.
  11717. Headers h_large_date = {
  11718. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11719. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11720. ASSERT_TRUE(res_bad);
  11721. // Expect server to treat this as invalid/mismatch and return full content
  11722. EXPECT_EQ(200, res_bad->status);
  11723. // If-Range with extremely large date should be treated as mismatch -> full
  11724. // content (200)
  11725. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11726. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11727. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11728. ASSERT_TRUE(res_ifrange);
  11729. EXPECT_EQ(200, res_ifrange->status);
  11730. svr.stop();
  11731. t.join();
  11732. std::remove(fname);
  11733. }
  11734. TEST(ETagTest, NegativeFileModificationTime) {
  11735. using namespace httplib;
  11736. const char *fname = "ims_negative_mtime.txt";
  11737. const std::string content = "negative-mtime";
  11738. {
  11739. std::ofstream ofs(fname);
  11740. ofs << content;
  11741. ASSERT_TRUE(ofs.good());
  11742. }
  11743. // Try to set file mtime to a negative value. This may fail on some
  11744. // platforms/filesystems; if it fails, the test will still verify server
  11745. // behaves safely by performing a regular conditional request.
  11746. #if defined(__APPLE__) || defined(__linux__)
  11747. bool set_negative = false;
  11748. do {
  11749. struct timeval times[2];
  11750. // access time: now
  11751. times[0].tv_sec = time(nullptr);
  11752. times[0].tv_usec = 0;
  11753. // modification time: negative (e.g., -1)
  11754. times[1].tv_sec = -1;
  11755. times[1].tv_usec = 0;
  11756. if (utimes(fname, times) == 0) { set_negative = true; }
  11757. } while (0);
  11758. #else
  11759. bool set_negative = false;
  11760. #endif
  11761. Server svr;
  11762. svr.set_mount_point("/static", ".");
  11763. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11764. svr.wait_until_ready();
  11765. Client cli(HOST, PORT);
  11766. auto res1 = cli.Get(std::string("/static/") + fname);
  11767. ASSERT_TRUE(res1);
  11768. ASSERT_EQ(200, res1->status);
  11769. bool has_last_modified = res1->has_header("Last-Modified");
  11770. std::string last_modified;
  11771. if (has_last_modified) {
  11772. last_modified = res1->get_header_value("Last-Modified");
  11773. }
  11774. if (set_negative) {
  11775. // If we successfully set a negative mtime, ensure server returns a
  11776. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11777. // with an old date and ensure server handles it without crash.
  11778. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11779. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11780. ASSERT_TRUE(res2);
  11781. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11782. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11783. } else {
  11784. // Could not set negative mtime on this platform; fall back to verifying
  11785. // that normal invalid/malformed dates are treated safely (non-304).
  11786. Headers h_bad_date = {
  11787. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11788. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11789. ASSERT_TRUE(res_bad);
  11790. EXPECT_EQ(200, res_bad->status);
  11791. }
  11792. svr.stop();
  11793. t.join();
  11794. std::remove(fname);
  11795. }
  11796. //==============================================================================
  11797. // SSE Parsing Tests
  11798. //==============================================================================
  11799. class SSEParsingTest : public ::testing::Test {
  11800. protected:
  11801. // Test helper that mimics SSE parsing behavior
  11802. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11803. int &retry_ms) {
  11804. // Blank line signals end of event
  11805. if (line.empty() || line == "\r") { return true; }
  11806. // Lines starting with ':' are comments (ignored)
  11807. if (!line.empty() && line[0] == ':') { return false; }
  11808. // Find the colon separator
  11809. auto colon_pos = line.find(':');
  11810. if (colon_pos == std::string::npos) {
  11811. // Line with no colon is treated as field name with empty value
  11812. return false;
  11813. }
  11814. std::string field = line.substr(0, colon_pos);
  11815. std::string value;
  11816. // Value starts after colon, skip optional single space
  11817. if (colon_pos + 1 < line.size()) {
  11818. size_t value_start = colon_pos + 1;
  11819. if (line[value_start] == ' ') { value_start++; }
  11820. value = line.substr(value_start);
  11821. // Remove trailing \r if present
  11822. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11823. }
  11824. // Handle known fields
  11825. if (field == "event") {
  11826. msg.event = value;
  11827. } else if (field == "data") {
  11828. // Multiple data lines are concatenated with newlines
  11829. if (!msg.data.empty()) { msg.data += "\n"; }
  11830. msg.data += value;
  11831. } else if (field == "id") {
  11832. // Empty id is valid (clears the last event ID)
  11833. msg.id = value;
  11834. } else if (field == "retry") {
  11835. // Parse retry interval in milliseconds
  11836. {
  11837. int v = 0;
  11838. auto res =
  11839. detail::from_chars(value.data(), value.data() + value.size(), v);
  11840. if (res.ec == std::errc{}) { retry_ms = v; }
  11841. }
  11842. }
  11843. // Unknown fields are ignored per SSE spec
  11844. return false;
  11845. }
  11846. };
  11847. // Test: Single-line data
  11848. TEST_F(SSEParsingTest, SingleLineData) {
  11849. sse::SSEMessage msg;
  11850. int retry_ms = 3000;
  11851. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11852. EXPECT_EQ(msg.data, "hello");
  11853. EXPECT_EQ(msg.event, "message");
  11854. // Blank line ends event
  11855. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11856. }
  11857. // Test: Multi-line data
  11858. TEST_F(SSEParsingTest, MultiLineData) {
  11859. sse::SSEMessage msg;
  11860. int retry_ms = 3000;
  11861. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11862. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11863. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11864. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11865. }
  11866. // Test: Custom event types
  11867. TEST_F(SSEParsingTest, CustomEventType) {
  11868. sse::SSEMessage msg;
  11869. int retry_ms = 3000;
  11870. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11871. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11872. EXPECT_EQ(msg.event, "update");
  11873. EXPECT_EQ(msg.data, "payload");
  11874. }
  11875. // Test: Event ID handling
  11876. TEST_F(SSEParsingTest, EventIdHandling) {
  11877. sse::SSEMessage msg;
  11878. int retry_ms = 3000;
  11879. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11880. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11881. EXPECT_EQ(msg.id, "12345");
  11882. }
  11883. // Test: Empty event ID (clears last event ID)
  11884. TEST_F(SSEParsingTest, EmptyEventId) {
  11885. sse::SSEMessage msg;
  11886. msg.id = "previous";
  11887. int retry_ms = 3000;
  11888. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11889. EXPECT_EQ(msg.id, "");
  11890. }
  11891. // Test: Retry field parsing
  11892. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11893. sse::SSEMessage msg;
  11894. int retry_ms = 3000;
  11895. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11896. EXPECT_EQ(retry_ms, 5000);
  11897. }
  11898. // Test: Invalid retry value
  11899. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11900. sse::SSEMessage msg;
  11901. int retry_ms = 3000;
  11902. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11903. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11904. }
  11905. // Test: Comments (lines starting with :)
  11906. TEST_F(SSEParsingTest, CommentsIgnored) {
  11907. sse::SSEMessage msg;
  11908. int retry_ms = 3000;
  11909. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11910. EXPECT_EQ(msg.data, "");
  11911. EXPECT_EQ(msg.event, "message");
  11912. }
  11913. // Test: Colon in value
  11914. TEST_F(SSEParsingTest, ColonInValue) {
  11915. sse::SSEMessage msg;
  11916. int retry_ms = 3000;
  11917. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11918. EXPECT_EQ(msg.data, "hello:world:test");
  11919. }
  11920. // Test: Line with no colon (field name only)
  11921. TEST_F(SSEParsingTest, FieldNameOnly) {
  11922. sse::SSEMessage msg;
  11923. int retry_ms = 3000;
  11924. // According to SSE spec, this is treated as field name with empty value
  11925. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11926. // Since we don't recognize "data" without colon, data should be empty
  11927. EXPECT_EQ(msg.data, "");
  11928. }
  11929. // Test: Trailing \r handling
  11930. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11931. sse::SSEMessage msg;
  11932. int retry_ms = 3000;
  11933. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11934. EXPECT_EQ(msg.data, "hello");
  11935. }
  11936. // Test: Unknown fields ignored
  11937. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11938. sse::SSEMessage msg;
  11939. int retry_ms = 3000;
  11940. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11941. EXPECT_EQ(msg.data, "");
  11942. EXPECT_EQ(msg.event, "message");
  11943. }
  11944. // Test: Space after colon is optional
  11945. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11946. sse::SSEMessage msg1, msg2;
  11947. int retry_ms = 3000;
  11948. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11949. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11950. EXPECT_EQ(msg1.data, "hello");
  11951. EXPECT_EQ(msg2.data, "hello");
  11952. }
  11953. // Test: SSEMessage clear
  11954. TEST_F(SSEParsingTest, MessageClear) {
  11955. sse::SSEMessage msg;
  11956. msg.event = "custom";
  11957. msg.data = "some data";
  11958. msg.id = "123";
  11959. msg.clear();
  11960. EXPECT_EQ(msg.event, "message");
  11961. EXPECT_EQ(msg.data, "");
  11962. EXPECT_EQ(msg.id, "");
  11963. }
  11964. // Test: Complete event parsing
  11965. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11966. sse::SSEMessage msg;
  11967. int retry_ms = 3000;
  11968. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11969. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11970. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11971. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11972. // Blank line ends event
  11973. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11974. EXPECT_EQ(msg.event, "notification");
  11975. EXPECT_EQ(msg.id, "evt-42");
  11976. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11977. EXPECT_EQ(retry_ms, 1000);
  11978. }
  11979. //==============================================================================
  11980. // Integration Tests with Server
  11981. //==============================================================================
  11982. class SSEIntegrationTest : public ::testing::Test {
  11983. protected:
  11984. void SetUp() override {
  11985. stop_server_.store(false);
  11986. events_.clear();
  11987. server_ = httplib::detail::make_unique<Server>();
  11988. setup_server();
  11989. start_server();
  11990. }
  11991. void TearDown() override {
  11992. stop_server_.store(true);
  11993. event_cv_.notify_all();
  11994. server_->stop();
  11995. if (server_thread_.joinable()) { server_thread_.join(); }
  11996. }
  11997. void setup_server() {
  11998. // Simple SSE endpoint
  11999. server_->Get("/events", [this](const Request &req, Response &res) {
  12000. auto last_id = req.get_header_value("Last-Event-ID");
  12001. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12002. res.set_chunked_content_provider(
  12003. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12004. std::unique_lock<std::mutex> lock(event_mutex_);
  12005. if (event_cv_.wait_for(
  12006. lock, std::chrono::milliseconds(200), [this] {
  12007. return !events_.empty() || stop_server_.load();
  12008. })) {
  12009. if (stop_server_.load()) { return false; }
  12010. if (!events_.empty()) {
  12011. std::string event = events_.front();
  12012. events_.erase(events_.begin());
  12013. sink.write(event.data(), event.size());
  12014. return true;
  12015. }
  12016. }
  12017. return !stop_server_.load();
  12018. });
  12019. });
  12020. // Endpoint that returns error
  12021. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12022. res.status = 500;
  12023. res.set_content("Internal Server Error", "text/plain");
  12024. });
  12025. // Endpoint for custom event types
  12026. server_->Get("/custom-events", [](const Request &, Response &res) {
  12027. res.set_chunked_content_provider(
  12028. "text/event-stream", [](size_t offset, DataSink &sink) {
  12029. if (offset == 0) {
  12030. std::string event = "event: update\ndata: updated\n\n"
  12031. "event: delete\ndata: deleted\n\n";
  12032. sink.write(event.data(), event.size());
  12033. }
  12034. return false; // End stream after sending
  12035. });
  12036. });
  12037. }
  12038. void start_server() {
  12039. port_ = server_->bind_to_any_port(HOST);
  12040. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12041. // Wait for server to start
  12042. while (!server_->is_running()) {
  12043. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12044. }
  12045. }
  12046. int get_port() const { return port_; }
  12047. void send_event(const std::string &event) {
  12048. std::lock_guard<std::mutex> lock(event_mutex_);
  12049. events_.push_back(event);
  12050. event_cv_.notify_all();
  12051. }
  12052. std::unique_ptr<Server> server_;
  12053. std::thread server_thread_;
  12054. std::mutex event_mutex_;
  12055. std::condition_variable event_cv_;
  12056. std::vector<std::string> events_;
  12057. std::atomic<bool> stop_server_{false};
  12058. std::string last_received_event_id_;
  12059. int port_ = 0;
  12060. };
  12061. // Test: Successful connection and on_open callback
  12062. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12063. // Add a simple endpoint that sends one event and closes
  12064. server_->Get("/simple-event", [](const Request &, Response &res) {
  12065. res.set_chunked_content_provider(
  12066. "text/event-stream", [](size_t offset, DataSink &sink) {
  12067. if (offset == 0) {
  12068. std::string event = "data: hello\n\n";
  12069. sink.write(event.data(), event.size());
  12070. }
  12071. return false; // Close stream after sending
  12072. });
  12073. });
  12074. Client client("localhost", get_port());
  12075. sse::SSEClient sse(client, "/simple-event");
  12076. std::atomic<bool> open_called{false};
  12077. std::atomic<bool> message_received{false};
  12078. sse.on_open([&open_called]() { open_called.store(true); });
  12079. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12080. if (msg.data == "hello") { message_received.store(true); }
  12081. });
  12082. sse.set_reconnect_interval(100);
  12083. sse.set_max_reconnect_attempts(1);
  12084. // Start async
  12085. sse.start_async();
  12086. // Wait for message to be processed
  12087. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12088. sse.stop();
  12089. EXPECT_TRUE(open_called.load());
  12090. EXPECT_TRUE(message_received.load());
  12091. }
  12092. // Test: on_message callback
  12093. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12094. // Endpoint that sends multiple events then closes
  12095. server_->Get("/multi-event", [](const Request &, Response &res) {
  12096. res.set_chunked_content_provider(
  12097. "text/event-stream", [](size_t offset, DataSink &sink) {
  12098. if (offset == 0) {
  12099. std::string events = "data: message1\n\ndata: message2\n\n";
  12100. sink.write(events.data(), events.size());
  12101. }
  12102. return false;
  12103. });
  12104. });
  12105. Client client("localhost", get_port());
  12106. sse::SSEClient sse(client, "/multi-event");
  12107. std::vector<std::string> received_messages;
  12108. std::mutex messages_mutex;
  12109. sse.on_message([&](const sse::SSEMessage &msg) {
  12110. std::lock_guard<std::mutex> lock(messages_mutex);
  12111. received_messages.push_back(msg.data);
  12112. });
  12113. sse.set_reconnect_interval(100);
  12114. sse.set_max_reconnect_attempts(1);
  12115. sse.start_async();
  12116. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12117. sse.stop();
  12118. std::lock_guard<std::mutex> lock(messages_mutex);
  12119. EXPECT_GE(received_messages.size(), 2u);
  12120. if (received_messages.size() >= 2) {
  12121. EXPECT_EQ(received_messages[0], "message1");
  12122. EXPECT_EQ(received_messages[1], "message2");
  12123. }
  12124. }
  12125. // Test: on_event for specific types
  12126. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12127. Client client("localhost", get_port());
  12128. sse::SSEClient sse(client, "/custom-events");
  12129. std::atomic<bool> update_received{false};
  12130. std::atomic<bool> delete_received{false};
  12131. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12132. if (msg.data == "updated") { update_received.store(true); }
  12133. });
  12134. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12135. if (msg.data == "deleted") { delete_received.store(true); }
  12136. });
  12137. sse.set_max_reconnect_attempts(1);
  12138. sse.start_async();
  12139. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12140. sse.stop();
  12141. EXPECT_TRUE(update_received.load());
  12142. EXPECT_TRUE(delete_received.load());
  12143. }
  12144. // Test: on_error callback on connection failure
  12145. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12146. // Connect to a non-existent port
  12147. Client client("localhost", 59999);
  12148. sse::SSEClient sse(client, "/events");
  12149. std::atomic<bool> error_called{false};
  12150. Error received_error = Error::Success;
  12151. sse.on_error([&](Error err) {
  12152. error_called.store(true);
  12153. received_error = err;
  12154. });
  12155. sse.set_reconnect_interval(50);
  12156. sse.set_max_reconnect_attempts(1);
  12157. sse.start_async();
  12158. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12159. sse.stop();
  12160. EXPECT_TRUE(error_called.load());
  12161. EXPECT_NE(received_error, Error::Success);
  12162. }
  12163. // Test: Last-Event-ID header sent on reconnect
  12164. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12165. // Endpoint that sends event with ID
  12166. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12167. res.set_chunked_content_provider(
  12168. "text/event-stream", [](size_t offset, DataSink &sink) {
  12169. if (offset == 0) {
  12170. std::string event = "id: evt-123\ndata: test\n\n";
  12171. sink.write(event.data(), event.size());
  12172. }
  12173. return false;
  12174. });
  12175. });
  12176. Client client("localhost", get_port());
  12177. sse::SSEClient sse(client, "/event-with-id");
  12178. std::atomic<bool> id_received{false};
  12179. sse.on_message([&](const sse::SSEMessage &msg) {
  12180. if (!msg.id.empty()) { id_received.store(true); }
  12181. });
  12182. sse.set_reconnect_interval(100);
  12183. sse.set_max_reconnect_attempts(1);
  12184. sse.start_async();
  12185. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12186. sse.stop();
  12187. EXPECT_TRUE(id_received.load());
  12188. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12189. }
  12190. // Test: Manual stop
  12191. TEST_F(SSEIntegrationTest, ManualStop) {
  12192. // Endpoint that sends one event and stays open briefly
  12193. std::atomic<bool> handler_running{true};
  12194. server_->Get("/stay-open", [&handler_running](const Request &,
  12195. Response &res) {
  12196. res.set_chunked_content_provider(
  12197. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12198. if (offset == 0) {
  12199. std::string event = "data: connected\n\n";
  12200. sink.write(event.data(), event.size());
  12201. }
  12202. // Keep connection open while handler_running is true
  12203. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12204. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12205. }
  12206. return false;
  12207. });
  12208. });
  12209. Client client("localhost", get_port());
  12210. sse::SSEClient sse(client, "/stay-open");
  12211. std::atomic<bool> connected{false};
  12212. sse.on_open([&connected]() { connected.store(true); });
  12213. sse.set_reconnect_interval(100);
  12214. sse.set_max_reconnect_attempts(1);
  12215. sse.start_async();
  12216. // Wait for connection to establish
  12217. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12218. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12219. }
  12220. EXPECT_TRUE(connected.load());
  12221. EXPECT_TRUE(sse.is_connected());
  12222. // Signal handler to stop
  12223. handler_running.store(false);
  12224. // Stop SSE client
  12225. sse.stop();
  12226. EXPECT_FALSE(sse.is_connected());
  12227. }
  12228. // Test: SSEClient with custom headers
  12229. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12230. // Setup a server endpoint that checks for custom header
  12231. std::atomic<bool> header_received{false};
  12232. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12233. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12234. header_received.store(true);
  12235. }
  12236. res.set_chunked_content_provider("text/event-stream",
  12237. [](size_t, DataSink &) { return false; });
  12238. });
  12239. Client client("localhost", get_port());
  12240. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12241. sse::SSEClient sse(client, "/header-check", headers);
  12242. sse.set_max_reconnect_attempts(1);
  12243. sse.start_async();
  12244. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12245. sse.stop();
  12246. EXPECT_TRUE(header_received.load());
  12247. }
  12248. // Test: Reconnect interval configuration
  12249. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12250. Client client("localhost", get_port());
  12251. sse::SSEClient sse(client, "/events");
  12252. auto &result = sse.set_reconnect_interval(500);
  12253. // Builder pattern should return reference to self
  12254. EXPECT_EQ(&result, &sse);
  12255. }
  12256. // Test: Max reconnect attempts
  12257. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12258. // Connect to non-existent port to force reconnects
  12259. Client client("localhost", 59998);
  12260. sse::SSEClient sse(client, "/events");
  12261. std::atomic<int> error_count{0};
  12262. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12263. sse.set_reconnect_interval(50);
  12264. sse.set_max_reconnect_attempts(2);
  12265. auto start = std::chrono::steady_clock::now();
  12266. sse.start(); // Blocking call
  12267. auto end = std::chrono::steady_clock::now();
  12268. // Should have stopped after 2 failed attempts
  12269. EXPECT_GE(error_count.load(), 2);
  12270. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12271. auto duration =
  12272. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12273. #ifdef _WIN32
  12274. // Windows is much slower for socket connection failures
  12275. EXPECT_LT(duration.count(), 7000);
  12276. #else
  12277. EXPECT_LT(duration.count(), 1000);
  12278. #endif
  12279. }
  12280. // Test: Multi-line data in integration
  12281. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12282. // Endpoint with multi-line data
  12283. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12284. res.set_chunked_content_provider(
  12285. "text/event-stream", [](size_t offset, DataSink &sink) {
  12286. if (offset == 0) {
  12287. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12288. sink.write(event.data(), event.size());
  12289. }
  12290. return false;
  12291. });
  12292. });
  12293. Client client("localhost", get_port());
  12294. sse::SSEClient sse(client, "/multiline-data");
  12295. std::string received_data;
  12296. std::mutex data_mutex;
  12297. sse.on_message([&](const sse::SSEMessage &msg) {
  12298. std::lock_guard<std::mutex> lock(data_mutex);
  12299. received_data = msg.data;
  12300. });
  12301. sse.set_reconnect_interval(100);
  12302. sse.set_max_reconnect_attempts(1);
  12303. sse.start_async();
  12304. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12305. sse.stop();
  12306. std::lock_guard<std::mutex> lock(data_mutex);
  12307. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12308. }
  12309. // Test: Auto-reconnect after server disconnection
  12310. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12311. std::atomic<int> connection_count{0};
  12312. std::atomic<int> message_count{0};
  12313. // Endpoint that sends one event and closes, forcing reconnect
  12314. server_->Get("/reconnect-test",
  12315. [&connection_count](const Request &, Response &res) {
  12316. connection_count.fetch_add(1);
  12317. res.set_chunked_content_provider(
  12318. "text/event-stream", [](size_t offset, DataSink &sink) {
  12319. if (offset == 0) {
  12320. std::string event = "data: hello\n\n";
  12321. sink.write(event.data(), event.size());
  12322. }
  12323. return false; // Close connection after sending
  12324. });
  12325. });
  12326. Client client("localhost", get_port());
  12327. sse::SSEClient sse(client, "/reconnect-test");
  12328. sse.on_message([&message_count](const sse::SSEMessage &) {
  12329. message_count.fetch_add(1);
  12330. });
  12331. sse.set_reconnect_interval(100);
  12332. sse.set_max_reconnect_attempts(3);
  12333. sse.start_async();
  12334. // Wait long enough for multiple reconnects
  12335. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12336. sse.stop();
  12337. // Should have connected multiple times (initial + reconnects)
  12338. EXPECT_GE(connection_count.load(), 2);
  12339. // Should have received messages from multiple connections
  12340. EXPECT_GE(message_count.load(), 2);
  12341. }
  12342. // Test: Last-Event-ID sent on reconnect
  12343. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12344. std::atomic<int> connection_count{0};
  12345. std::vector<std::string> received_last_event_ids;
  12346. std::mutex id_mutex;
  12347. // Endpoint that checks Last-Event-ID header and sends event with ID
  12348. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12349. int conn = connection_count.fetch_add(1);
  12350. // Capture the Last-Event-ID header from each connection
  12351. {
  12352. std::lock_guard<std::mutex> lock(id_mutex);
  12353. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12354. }
  12355. res.set_chunked_content_provider(
  12356. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12357. if (offset == 0) {
  12358. std::string event =
  12359. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12360. sink.write(event.data(), event.size());
  12361. }
  12362. return false;
  12363. });
  12364. });
  12365. Client client("localhost", get_port());
  12366. sse::SSEClient sse(client, "/reconnect-with-id");
  12367. sse.set_reconnect_interval(100);
  12368. sse.set_max_reconnect_attempts(3);
  12369. sse.start_async();
  12370. // Wait for at least 2 connections
  12371. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12372. sse.stop();
  12373. // Verify behavior
  12374. std::lock_guard<std::mutex> lock(id_mutex);
  12375. EXPECT_GE(received_last_event_ids.size(), 2u);
  12376. // First connection should have no Last-Event-ID
  12377. if (!received_last_event_ids.empty()) {
  12378. EXPECT_EQ(received_last_event_ids[0], "");
  12379. }
  12380. // Second connection should have Last-Event-ID from first connection
  12381. if (received_last_event_ids.size() >= 2) {
  12382. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12383. }
  12384. }
  12385. TEST(Issue2318Test, EmptyHostString) {
  12386. {
  12387. httplib::Client cli_empty("", PORT);
  12388. auto res = cli_empty.Get("/");
  12389. ASSERT_FALSE(res);
  12390. EXPECT_EQ(httplib::Error::Connection, res.error());
  12391. }
  12392. {
  12393. httplib::Client cli(" ", PORT);
  12394. auto res = cli.Get("/");
  12395. ASSERT_FALSE(res);
  12396. EXPECT_EQ(httplib::Error::Connection, res.error());
  12397. }
  12398. }
  12399. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12400. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12401. Server svr;
  12402. // Set a small payload limit (1KB)
  12403. svr.set_payload_max_length(1024);
  12404. svr.Post("/test", [&](const Request &req, Response &res) {
  12405. res.set_content("Body size: " + std::to_string(req.body.size()),
  12406. "text/plain");
  12407. });
  12408. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12409. auto se = detail::scope_exit([&] {
  12410. svr.stop();
  12411. listen_thread.join();
  12412. });
  12413. svr.wait_until_ready();
  12414. // Create data that compresses well but exceeds limit when decompressed
  12415. // 8KB of repeated null bytes compresses to a very small size
  12416. std::string original_data(8 * 1024, '\0');
  12417. // Compress the data using gzip
  12418. std::string compressed_data;
  12419. detail::gzip_compressor compressor;
  12420. compressor.compress(original_data.data(), original_data.size(), true,
  12421. [&](const char *data, size_t size) {
  12422. compressed_data.append(data, size);
  12423. return true;
  12424. });
  12425. // Verify compression worked (compressed should be much smaller)
  12426. ASSERT_LT(compressed_data.size(), original_data.size());
  12427. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12428. // Send compressed data with Content-Encoding: gzip
  12429. Client cli(HOST, PORT);
  12430. Headers headers = {{"Content-Encoding", "gzip"}};
  12431. auto res =
  12432. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12433. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12434. ASSERT_TRUE(res);
  12435. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12436. }
  12437. #endif
  12438. // ============================================================================
  12439. // OpenSSL-Specific Tests
  12440. // ============================================================================
  12441. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12442. X509 *readCertificate(const std::string &strFileName) {
  12443. std::ifstream inStream(strFileName);
  12444. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12445. std::istreambuf_iterator<char>());
  12446. if (strCertPEM.empty()) return (nullptr);
  12447. BIO *pbCert = BIO_new(BIO_s_mem());
  12448. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12449. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12450. BIO_free(pbCert);
  12451. return (pCert);
  12452. }
  12453. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12454. std::ifstream inStream(strFileName);
  12455. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12456. std::istreambuf_iterator<char>());
  12457. if (strPrivateKeyPEM.empty()) return (nullptr);
  12458. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12459. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12460. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12461. BIO_free(pbPrivKey);
  12462. return (pPrivateKey);
  12463. }
  12464. TEST(BindServerTest, UpdateCerts) {
  12465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12466. int port = svr.bind_to_any_port("0.0.0.0");
  12467. ASSERT_TRUE(svr.is_valid());
  12468. ASSERT_TRUE(port > 0);
  12469. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12470. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12471. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12472. ASSERT_TRUE(cert != nullptr);
  12473. ASSERT_TRUE(ca_cert != nullptr);
  12474. ASSERT_TRUE(key != nullptr);
  12475. X509_STORE *cert_store = X509_STORE_new();
  12476. X509_STORE_add_cert(cert_store, ca_cert);
  12477. // svr.update_certs(cert, key, cert_store); // deprecated
  12478. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12479. CLIENT_CA_CERT_FILE);
  12480. ASSERT_TRUE(svr.is_valid());
  12481. svr.stop();
  12482. X509_free(cert);
  12483. X509_free(ca_cert);
  12484. EVP_PKEY_free(key);
  12485. }
  12486. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12487. // client CA list correctly for TLS handshake
  12488. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12489. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12490. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12491. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12492. ASSERT_TRUE(cert != nullptr);
  12493. ASSERT_TRUE(ca_cert != nullptr);
  12494. ASSERT_TRUE(key != nullptr);
  12495. X509_STORE *cert_store = X509_STORE_new();
  12496. X509_STORE_add_cert(cert_store, ca_cert);
  12497. // Use X509-based constructor (deprecated but should still work correctly)
  12498. #pragma GCC diagnostic push
  12499. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12500. SSLServer svr(cert, key, cert_store);
  12501. #pragma GCC diagnostic pop
  12502. ASSERT_TRUE(svr.is_valid());
  12503. // Verify that client CA list is set in SSL_CTX
  12504. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12505. ASSERT_TRUE(ssl_ctx != nullptr);
  12506. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12507. ASSERT_TRUE(ca_list != nullptr);
  12508. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12509. X509_free(cert);
  12510. X509_free(ca_cert);
  12511. EVP_PKEY_free(key);
  12512. }
  12513. // Test that update_certs() updates client CA list correctly
  12514. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12515. // Start with file-based constructor
  12516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12517. ASSERT_TRUE(svr.is_valid());
  12518. // Initially no client CA list should be set
  12519. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12520. ASSERT_TRUE(ssl_ctx != nullptr);
  12521. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12522. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12523. EXPECT_EQ(0, count_before);
  12524. // Now update with client CA (PEM string)
  12525. std::string cert_pem, key_pem, ca_pem;
  12526. read_file(SERVER_CERT_FILE, cert_pem);
  12527. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12528. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12529. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12530. ASSERT_TRUE(svr.is_valid());
  12531. // Now client CA list should be set
  12532. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12533. ASSERT_TRUE(ca_list_after != nullptr);
  12534. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12535. }
  12536. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12537. // Test that the file-path SSLServer constructor properly sets the client CA
  12538. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12540. ASSERT_TRUE(svr.is_valid());
  12541. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12542. ASSERT_TRUE(ssl_ctx != nullptr);
  12543. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12544. ASSERT_TRUE(ca_list != nullptr);
  12545. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12546. }
  12547. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12548. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12549. // prepare large data
  12550. std::random_device seed_gen;
  12551. std::mt19937 random(seed_gen());
  12552. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12553. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12554. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12555. // server
  12556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12557. ASSERT_TRUE(svr.is_valid());
  12558. svr.Post("/binary", [&](const Request &req, Response &res) {
  12559. EXPECT_EQ(large_size_byte, req.body.size());
  12560. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12561. res.set_content(req.body, "application/octet-stream");
  12562. });
  12563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. listen_thread.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. // client POST
  12571. SSLClient cli("localhost", PORT);
  12572. cli.enable_server_certificate_verification(false);
  12573. cli.set_read_timeout(std::chrono::seconds(100));
  12574. cli.set_write_timeout(std::chrono::seconds(100));
  12575. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12576. large_size_byte, "application/octet-stream");
  12577. // compare
  12578. EXPECT_EQ(StatusCode::OK_200, res->status);
  12579. EXPECT_EQ(large_size_byte, res->body.size());
  12580. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12581. }
  12582. #endif
  12583. // ============================================================================
  12584. // MbedTLS-Specific Tests
  12585. // ============================================================================
  12586. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12587. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12588. using namespace httplib::tls;
  12589. // Track if callback was invoked
  12590. bool callback_invoked = false;
  12591. // The callback receives void* ctx which is actually MbedTlsContext*
  12592. // We can access the mbedtls_ssl_config via the context
  12593. auto setup_callback = [&callback_invoked](void *ctx) {
  12594. callback_invoked = true;
  12595. // Cast to MbedTlsContext* to access the ssl config
  12596. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12597. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12598. // Use static variables to hold certificate data (simplified for test)
  12599. static mbedtls_x509_crt own_cert;
  12600. static mbedtls_pk_context own_key;
  12601. static mbedtls_x509_crt ca_chain;
  12602. static bool initialized = false;
  12603. if (!initialized) {
  12604. mbedtls_x509_crt_init(&own_cert);
  12605. mbedtls_pk_init(&own_key);
  12606. mbedtls_x509_crt_init(&ca_chain);
  12607. // Load server certificate
  12608. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  12609. return false;
  12610. }
  12611. // Load server private key
  12612. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  12613. #if MBEDTLS_VERSION_MAJOR >= 3
  12614. ,
  12615. mbedtls_ctr_drbg_random, nullptr
  12616. #endif
  12617. ) != 0) {
  12618. return false;
  12619. }
  12620. // Load CA chain for client verification
  12621. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  12622. return false;
  12623. }
  12624. initialized = true;
  12625. }
  12626. // Configure the SSL config
  12627. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  12628. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  12629. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12630. // Set minimum TLS version using mbedTLS native API
  12631. #if MBEDTLS_VERSION_MAJOR >= 3
  12632. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12633. #else
  12634. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12635. MBEDTLS_SSL_MINOR_VERSION_3);
  12636. #endif
  12637. return true;
  12638. };
  12639. SSLServer svr(setup_callback);
  12640. ASSERT_TRUE(svr.is_valid());
  12641. ASSERT_TRUE(callback_invoked);
  12642. svr.Get("/test", [&](const Request &req, Response &res) {
  12643. res.set_content("test", "text/plain");
  12644. auto cert = req.peer_cert();
  12645. ASSERT_TRUE(static_cast<bool>(cert));
  12646. auto common_name = cert.subject_cn();
  12647. EXPECT_EQ("Common Name", common_name);
  12648. });
  12649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12650. auto se = detail::scope_exit([&] {
  12651. svr.stop();
  12652. t.join();
  12653. ASSERT_FALSE(svr.is_running());
  12654. });
  12655. svr.wait_until_ready();
  12656. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12657. cli.enable_server_certificate_verification(false);
  12658. cli.set_connection_timeout(30);
  12659. auto res = cli.Get("/test");
  12660. ASSERT_TRUE(res);
  12661. ASSERT_EQ(StatusCode::OK_200, res->status);
  12662. }
  12663. #endif