test.cc 467 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235
  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. #ifdef _WIN32
  7335. ::shutdown(cli, SD_SEND);
  7336. #else
  7337. ::shutdown(cli, SHUT_WR);
  7338. #endif
  7339. // Drain until the client closes its end, ensuring all data is delivered
  7340. char drain[1024];
  7341. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7342. detail::close_socket(cli);
  7343. }
  7344. detail::close_socket(srv);
  7345. });
  7346. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7347. size_t total_read = 0;
  7348. {
  7349. Client cli("127.0.0.1", PORT + 2);
  7350. cli.set_read_timeout(5, 0);
  7351. cli.set_payload_max_length(0); // 0 means no limit
  7352. auto stream = cli.open_stream("GET", "/data");
  7353. ASSERT_TRUE(stream.is_valid());
  7354. char buffer[64 * 1024];
  7355. ssize_t n;
  7356. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7357. total_read += static_cast<size_t>(n);
  7358. }
  7359. }
  7360. server_thread.join();
  7361. EXPECT_EQ(total_read, DATA_SIZE)
  7362. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7363. << " bytes without truncation, but only read " << total_read << " bytes.";
  7364. }
  7365. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7366. // Regression test for "zip bomb" attack on the client side: a malicious server
  7367. // sends a small gzip-compressed response that decompresses to a huge payload.
  7368. // The client must enforce payload_max_length on the decompressed size.
  7369. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7370. constexpr size_t DECOMPRESSED_SIZE =
  7371. 10 * 1024 * 1024; // 10MB after decompression
  7372. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7373. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7374. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7375. std::string compressed;
  7376. {
  7377. httplib::detail::gzip_compressor compressor;
  7378. bool ok =
  7379. compressor.compress(uncompressed.data(), uncompressed.size(),
  7380. /*last=*/true, [&](const char *buf, size_t len) {
  7381. compressed.append(buf, len);
  7382. return true;
  7383. });
  7384. ASSERT_TRUE(ok);
  7385. }
  7386. // Sanity: compressed data should be much smaller than the decompressed size
  7387. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7388. #ifndef _WIN32
  7389. signal(SIGPIPE, SIG_IGN);
  7390. #endif
  7391. auto server_thread = std::thread([&compressed] {
  7392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7393. default_socket_options(srv);
  7394. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7395. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7396. sockaddr_in addr{};
  7397. addr.sin_family = AF_INET;
  7398. addr.sin_port = htons(PORT + 3);
  7399. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7400. int opt = 1;
  7401. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7402. #ifdef _WIN32
  7403. reinterpret_cast<const char *>(&opt),
  7404. #else
  7405. &opt,
  7406. #endif
  7407. sizeof(opt));
  7408. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7409. ::listen(srv, 1);
  7410. sockaddr_in cli_addr{};
  7411. socklen_t cli_len = sizeof(cli_addr);
  7412. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7413. if (cli != INVALID_SOCKET) {
  7414. char buf[4096];
  7415. ::recv(cli, buf, sizeof(buf), 0);
  7416. // Malicious response: gzip-compressed body, no Content-Length
  7417. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7418. "Content-Encoding: gzip\r\n"
  7419. "Connection: close\r\n"
  7420. "\r\n";
  7421. ::send(cli,
  7422. #ifdef _WIN32
  7423. static_cast<const char *>(response_header.c_str()),
  7424. static_cast<int>(response_header.size()),
  7425. #else
  7426. response_header.c_str(), response_header.size(),
  7427. #endif
  7428. 0);
  7429. // Send the compressed payload (small on the wire, huge when decompressed)
  7430. size_t total_sent = 0;
  7431. while (total_sent < compressed.size()) {
  7432. auto to_send = std::min(compressed.size() - total_sent,
  7433. static_cast<size_t>(64 * 1024));
  7434. auto sent =
  7435. ::send(cli,
  7436. #ifdef _WIN32
  7437. static_cast<const char *>(compressed.c_str() + total_sent),
  7438. static_cast<int>(to_send),
  7439. #else
  7440. compressed.c_str() + total_sent, to_send,
  7441. #endif
  7442. 0);
  7443. if (sent <= 0) break;
  7444. total_sent += static_cast<size_t>(sent);
  7445. }
  7446. detail::close_socket(cli);
  7447. }
  7448. detail::close_socket(srv);
  7449. });
  7450. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7451. size_t total_decompressed = 0;
  7452. {
  7453. Client cli("127.0.0.1", PORT + 3);
  7454. cli.set_read_timeout(5, 0);
  7455. cli.set_decompress(true);
  7456. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7457. auto stream = cli.open_stream("GET", "/zipbomb");
  7458. ASSERT_TRUE(stream.is_valid());
  7459. char buffer[64 * 1024];
  7460. ssize_t n;
  7461. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7462. total_decompressed += static_cast<size_t>(n);
  7463. }
  7464. }
  7465. server_thread.join();
  7466. // The decompressed size must be capped by payload_max_length. Without
  7467. // protection, the client would decompress the full 10MB from a tiny
  7468. // compressed payload, enabling a zip bomb DoS attack.
  7469. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7470. << "Client decompressed " << total_decompressed
  7471. << " bytes from a gzip response. The decompressed size should be "
  7472. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7473. }
  7474. #endif
  7475. TEST(HostAndPortPropertiesTest, NoSSL) {
  7476. httplib::Client cli("www.google.com", 1234);
  7477. ASSERT_EQ("www.google.com", cli.host());
  7478. ASSERT_EQ(1234, cli.port());
  7479. }
  7480. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7481. httplib::Client cli("www.google.com:1234");
  7482. ASSERT_EQ("www.google.com", cli.host());
  7483. ASSERT_EQ(1234, cli.port());
  7484. }
  7485. #ifdef CPPHTTPLIB_SSL_ENABLED
  7486. TEST(HostAndPortPropertiesTest, SSL) {
  7487. httplib::SSLClient cli("www.google.com");
  7488. ASSERT_EQ("www.google.com", cli.host());
  7489. ASSERT_EQ(443, cli.port());
  7490. }
  7491. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7492. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7493. std::string cert;
  7494. read_file(CA_CERT_FILE, cert);
  7495. httplib::SSLClient httplib_client("www.google.com");
  7496. // Load CA store first time
  7497. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7498. // Load CA store second time (update)
  7499. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7500. // Verify client is still valid and can make connections
  7501. httplib_client.enable_server_certificate_verification(true);
  7502. auto res = httplib_client.Get("/");
  7503. ASSERT_TRUE(res);
  7504. // Google may return 200 or 301 depending on various factors
  7505. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7506. res->status == StatusCode::MovedPermanently_301);
  7507. }
  7508. TEST(SSLClientTest, ServerNameIndication_Online) {
  7509. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7510. auto host = "httpcan.org";
  7511. auto path = std::string{"/get"};
  7512. #else
  7513. auto host = "nghttp2.org";
  7514. auto path = std::string{"/httpbin/get"};
  7515. #endif
  7516. SSLClient cli(host, 443);
  7517. auto res = cli.Get(path);
  7518. ASSERT_TRUE(res);
  7519. ASSERT_EQ(StatusCode::OK_200, res->status);
  7520. }
  7521. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7522. // Use a site that will cause SSL verification failure due to self-signed cert
  7523. SSLClient cli("self-signed.badssl.com", 443);
  7524. cli.enable_server_certificate_verification(true);
  7525. auto res = cli.Get("/");
  7526. ASSERT_TRUE(!res);
  7527. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7528. // Verify backend error is captured for SSLServerVerification
  7529. // This occurs when certificate verification fails
  7530. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7531. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7532. EXPECT_NE(0UL, res.ssl_backend_error());
  7533. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7534. // For OpenSSL, ssl_error is 0 for verification errors
  7535. EXPECT_EQ(0, res.ssl_error());
  7536. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7537. res.ssl_backend_error());
  7538. #endif
  7539. }
  7540. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7541. // Use a site where hostname doesn't match the certificate
  7542. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7543. SSLClient cli("wrong.host.badssl.com", 443);
  7544. cli.enable_server_certificate_verification(true);
  7545. cli.enable_server_hostname_verification(true);
  7546. auto res = cli.Get("/");
  7547. ASSERT_TRUE(!res);
  7548. // The error type depends on when hostname verification occurs:
  7549. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7550. // - Mbed TLS: SSLServerVerification (during handshake)
  7551. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7552. res.error() == Error::SSLServerVerification);
  7553. // Verify backend error is captured for hostname verification failure
  7554. EXPECT_NE(0UL, res.ssl_backend_error());
  7555. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7556. // For OpenSSL, ssl_error is 0 for verification errors
  7557. EXPECT_EQ(0, res.ssl_error());
  7558. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7559. res.ssl_backend_error());
  7560. #endif
  7561. }
  7562. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7563. Client cli("https://google.com");
  7564. auto res = cli.Get("/");
  7565. ASSERT_TRUE(res);
  7566. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7567. }
  7568. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7569. SSLClient cli("google.com");
  7570. cli.set_ca_cert_path(CA_CERT_FILE);
  7571. auto res = cli.Get("/");
  7572. ASSERT_TRUE(res);
  7573. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7574. }
  7575. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7576. SSLClient cli("google.com");
  7577. cli.enable_server_certificate_verification(true);
  7578. cli.set_ca_cert_path("hello");
  7579. auto res = cli.Get("/");
  7580. ASSERT_TRUE(!res);
  7581. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7582. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7583. // should be set
  7584. EXPECT_EQ(0, res.ssl_error());
  7585. // Verify backend error is captured for SSLLoadingCerts
  7586. // This error occurs when loading CA certificates fails
  7587. EXPECT_NE(0UL, res.ssl_backend_error());
  7588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7589. // OpenSSL specific error codes:
  7590. // > openssl errstr 0x80000002
  7591. // error:80000002:system library::No such file or directory
  7592. // > openssl errstr 0xA000126
  7593. // error:0A000126:SSL routines::unexpected eof while reading
  7594. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7595. res.ssl_backend_error() == 0xA000126);
  7596. #endif
  7597. }
  7598. TEST(SSLClientTest, ServerCertificateVerification4) {
  7599. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7600. ASSERT_TRUE(svr.is_valid());
  7601. svr.Get("/test", [&](const Request &, Response &res) {
  7602. res.set_content("test", "text/plain");
  7603. svr.stop();
  7604. ASSERT_TRUE(true);
  7605. });
  7606. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7607. auto se = detail::scope_exit([&] {
  7608. t.join();
  7609. ASSERT_FALSE(svr.is_running());
  7610. });
  7611. svr.wait_until_ready();
  7612. SSLClient cli("127.0.0.1", PORT);
  7613. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7614. cli.enable_server_certificate_verification(true);
  7615. cli.set_connection_timeout(30);
  7616. auto res = cli.Get("/test");
  7617. ASSERT_TRUE(res);
  7618. ASSERT_EQ(StatusCode::OK_200, res->status);
  7619. }
  7620. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7621. std::string cert;
  7622. read_file(CA_CERT_FILE, cert);
  7623. SSLClient cli("google.com");
  7624. cli.load_ca_cert_store(cert.data(), cert.size());
  7625. const auto res = cli.Get("/");
  7626. ASSERT_TRUE(res);
  7627. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7628. }
  7629. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7630. // clang-format off
  7631. static constexpr char cert[] =
  7632. "GlobalSign Root CA\n"
  7633. "==================\n"
  7634. "-----BEGIN CERTIFICATE-----\n"
  7635. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7636. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7637. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7638. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7639. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7640. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7641. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7642. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7643. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7644. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7645. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7646. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7647. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7648. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7649. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7650. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7651. "-----END CERTIFICATE-----\n";
  7652. // clang-format on
  7653. SSLClient cli("google.com");
  7654. cli.load_ca_cert_store(cert, sizeof(cert));
  7655. const auto res = cli.Get("/");
  7656. ASSERT_TRUE(res);
  7657. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7658. }
  7659. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7660. SSLClient cli("www.youtube.com");
  7661. cli.set_ca_cert_path(CA_CERT_FILE);
  7662. cli.enable_server_certificate_verification(true);
  7663. cli.set_follow_location(true);
  7664. auto res = cli.Get("/");
  7665. ASSERT_TRUE(res);
  7666. ASSERT_EQ(StatusCode::OK_200, res->status);
  7667. }
  7668. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7669. SSLClient cli("wWw.YouTube.Com");
  7670. cli.set_ca_cert_path(CA_CERT_FILE);
  7671. cli.enable_server_certificate_verification(true);
  7672. cli.enable_server_hostname_verification(true);
  7673. cli.set_follow_location(true);
  7674. auto res = cli.Get("/");
  7675. ASSERT_TRUE(res);
  7676. ASSERT_EQ(StatusCode::OK_200, res->status);
  7677. }
  7678. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7679. SSLClient cli("gOoGlE.COm");
  7680. cli.enable_server_certificate_verification(true);
  7681. cli.enable_server_hostname_verification(true);
  7682. cli.set_follow_location(true);
  7683. auto res = cli.Get("/");
  7684. ASSERT_TRUE(res);
  7685. ASSERT_EQ(StatusCode::OK_200, res->status);
  7686. }
  7687. TEST(SSLClientTest, Issue2004_Online) {
  7688. Client client("https://google.com");
  7689. client.set_follow_location(true);
  7690. auto res = client.Get("/");
  7691. ASSERT_TRUE(res);
  7692. ASSERT_EQ(StatusCode::OK_200, res->status);
  7693. auto body = res->body;
  7694. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7695. }
  7696. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7697. // Create SSLClient with invalid cert/key to make is_valid() return false
  7698. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7699. "nonexistent_key.pem");
  7700. // is_valid() should be false due to cert loading failure
  7701. ASSERT_FALSE(cli.is_valid());
  7702. auto res = cli.Get("/");
  7703. ASSERT_FALSE(res);
  7704. EXPECT_EQ(Error::SSLConnection, res.error());
  7705. }
  7706. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7707. // Test for Issue #2251: SSL error not properly reported when client cert
  7708. // and key paths are swapped or mismatched
  7709. // This simulates the scenario where user accidentally swaps the cert and key
  7710. // files
  7711. // Using client cert file as private key and vice versa (completely wrong)
  7712. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7713. // Should fail validation due to cert/key mismatch
  7714. ASSERT_FALSE(cli.is_valid());
  7715. // Attempt to make a request should fail with proper error
  7716. auto res = cli.Get("/");
  7717. ASSERT_FALSE(res);
  7718. EXPECT_EQ(Error::SSLConnection, res.error());
  7719. // SSL error should be recorded in the Result object (this is the key fix for
  7720. // Issue #2251)
  7721. auto backend_error = res.ssl_backend_error();
  7722. EXPECT_NE(0u, backend_error);
  7723. }
  7724. // Tests cert/key mismatch detection at the TLS context level
  7725. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7726. // Test that using mismatched cert/key causes connection failure.
  7727. // We verify this at the SSLClient level rather than through internal
  7728. // TLS API functions.
  7729. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  7730. cli.enable_server_certificate_verification(false);
  7731. cli.set_connection_timeout(2);
  7732. // The mismatch should cause a connection or handshake error
  7733. auto res = cli.Get("/test");
  7734. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  7735. // Either way, the request should fail
  7736. EXPECT_FALSE(res);
  7737. }
  7738. #endif
  7739. #if 0
  7740. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7741. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7742. ASSERT_TRUE(cli != nullptr);
  7743. cli->set_address_family(AF_INET6);
  7744. cli->set_interface("en0");
  7745. auto res = cli->Get("/get");
  7746. ASSERT_TRUE(res);
  7747. ASSERT_EQ(StatusCode::OK_200, res->status);
  7748. }
  7749. #endif
  7750. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  7751. #ifdef CPPHTTPLIB_SSL_ENABLED
  7752. void ClientCertPresent(
  7753. const std::string &client_cert_file,
  7754. const std::string &client_private_key_file,
  7755. const std::string &client_encrypted_private_key_pass = std::string()) {
  7756. using namespace httplib::tls;
  7757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7758. CLIENT_CA_CERT_DIR);
  7759. ASSERT_TRUE(svr.is_valid());
  7760. svr.Get("/test", [&](const Request &req, Response &res) {
  7761. res.set_content("test", "text/plain");
  7762. auto cert = req.peer_cert();
  7763. ASSERT_TRUE(static_cast<bool>(cert));
  7764. std::string common_name = cert.subject_cn();
  7765. EXPECT_EQ("Common Name", common_name);
  7766. });
  7767. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7768. auto se = detail::scope_exit([&] {
  7769. svr.stop();
  7770. t.join();
  7771. ASSERT_FALSE(svr.is_running());
  7772. });
  7773. svr.wait_until_ready();
  7774. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7775. client_encrypted_private_key_pass);
  7776. cli.enable_server_certificate_verification(false);
  7777. cli.set_connection_timeout(30);
  7778. auto res = cli.Get("/test");
  7779. ASSERT_TRUE(res);
  7780. ASSERT_EQ(StatusCode::OK_200, res->status);
  7781. }
  7782. TEST(SSLClientServerTest, ClientCertPresent) {
  7783. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7784. }
  7785. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7786. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7787. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7788. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7789. }
  7790. // PEM memory-based constructor tests (works with all TLS backends)
  7791. void PemMemoryClientCertPresent(
  7792. const std::string &client_cert_file,
  7793. const std::string &client_private_key_file,
  7794. const std::string &client_encrypted_private_key_pass = std::string()) {
  7795. // Read PEM files into memory
  7796. std::string server_cert_pem, server_key_pem;
  7797. std::string client_ca_pem;
  7798. std::string client_cert_pem, client_key_pem;
  7799. read_file(SERVER_CERT_FILE, server_cert_pem);
  7800. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7801. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7802. read_file(client_cert_file, client_cert_pem);
  7803. read_file(client_private_key_file, client_key_pem);
  7804. // Create server with PEM memory
  7805. SSLServer::PemMemory server_pem = {
  7806. server_cert_pem.c_str(),
  7807. server_cert_pem.size(),
  7808. server_key_pem.c_str(),
  7809. server_key_pem.size(),
  7810. client_ca_pem.c_str(),
  7811. client_ca_pem.size(),
  7812. nullptr // no password for server key
  7813. };
  7814. SSLServer svr(server_pem);
  7815. ASSERT_TRUE(svr.is_valid());
  7816. svr.Get("/test", [&](const Request &, Response &res) {
  7817. res.set_content("test", "text/plain");
  7818. });
  7819. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7820. auto se = detail::scope_exit([&] {
  7821. svr.stop();
  7822. t.join();
  7823. ASSERT_FALSE(svr.is_running());
  7824. });
  7825. svr.wait_until_ready();
  7826. // Create client with PEM memory
  7827. const char *password = client_encrypted_private_key_pass.empty()
  7828. ? nullptr
  7829. : client_encrypted_private_key_pass.c_str();
  7830. SSLClient::PemMemory client_pem = {
  7831. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7832. client_key_pem.size(), password};
  7833. SSLClient cli(HOST, PORT, client_pem);
  7834. cli.enable_server_certificate_verification(false);
  7835. cli.set_connection_timeout(30);
  7836. auto res = cli.Get("/test");
  7837. ASSERT_TRUE(res);
  7838. ASSERT_EQ(StatusCode::OK_200, res->status);
  7839. }
  7840. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7841. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7842. }
  7843. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7844. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7845. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7846. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7847. }
  7848. TEST(SSLClientServerTest, ClientCertMissing) {
  7849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7850. CLIENT_CA_CERT_DIR);
  7851. ASSERT_TRUE(svr.is_valid());
  7852. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7854. auto se = detail::scope_exit([&] {
  7855. svr.stop();
  7856. t.join();
  7857. ASSERT_FALSE(svr.is_running());
  7858. });
  7859. svr.wait_until_ready();
  7860. SSLClient cli(HOST, PORT);
  7861. cli.set_connection_timeout(30);
  7862. auto res = cli.Get("/test");
  7863. ASSERT_TRUE(!res);
  7864. // When client cert is missing and server requires it, connection fails
  7865. // Error type depends on backend implementation
  7866. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7867. res.error() == Error::SSLConnection);
  7868. // Verify backend error is captured
  7869. // Note: This test may have different error codes depending on the exact
  7870. // verification failure
  7871. EXPECT_NE(0UL, res.ssl_backend_error());
  7872. }
  7873. TEST(SSLClientServerTest, TrustDirOptional) {
  7874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7875. ASSERT_TRUE(svr.is_valid());
  7876. svr.Get("/test", [&](const Request &, Response &res) {
  7877. res.set_content("test", "text/plain");
  7878. });
  7879. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7880. auto se = detail::scope_exit([&] {
  7881. svr.stop();
  7882. t.join();
  7883. ASSERT_FALSE(svr.is_running());
  7884. });
  7885. svr.wait_until_ready();
  7886. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7887. cli.enable_server_certificate_verification(false);
  7888. cli.set_connection_timeout(30);
  7889. auto res = cli.Get("/test");
  7890. ASSERT_TRUE(res);
  7891. ASSERT_EQ(StatusCode::OK_200, res->status);
  7892. }
  7893. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7894. class NoListenSSLServer : public SSLServer {
  7895. public:
  7896. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7897. const char *client_ca_cert_file_path,
  7898. const char *client_ca_cert_dir_path = nullptr)
  7899. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7900. client_ca_cert_dir_path),
  7901. stop_(false) {}
  7902. std::atomic_bool stop_;
  7903. private:
  7904. bool process_and_close_socket(socket_t /*sock*/) override {
  7905. // Don't create SSL context
  7906. while (!stop_.load()) {
  7907. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7908. }
  7909. return true;
  7910. }
  7911. };
  7912. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7913. CLIENT_CA_CERT_FILE);
  7914. ASSERT_TRUE(svr.is_valid());
  7915. svr.Get("/test", [&](const Request &, Response &res) {
  7916. res.set_content("test", "text/plain");
  7917. });
  7918. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7919. auto se = detail::scope_exit([&] {
  7920. svr.stop_ = true;
  7921. svr.stop();
  7922. t.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7927. cli.enable_server_certificate_verification(false);
  7928. cli.set_connection_timeout(1);
  7929. auto res = cli.Get("/test");
  7930. ASSERT_TRUE(!res);
  7931. EXPECT_EQ(Error::SSLConnection, res.error());
  7932. // Timeout results in WantRead error code (maps to backend-specific value)
  7933. EXPECT_NE(0, res.ssl_error());
  7934. }
  7935. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7936. // Test SSLServer with client certificate verification using the standard
  7937. // constructor (ContextSetupCallback is tested by backend-specific tests)
  7938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7939. CLIENT_CA_CERT_DIR);
  7940. ASSERT_TRUE(svr.is_valid());
  7941. svr.Get("/test", [&](const Request &req, Response &res) {
  7942. res.set_content("test", "text/plain");
  7943. auto cert = req.peer_cert();
  7944. ASSERT_TRUE(static_cast<bool>(cert));
  7945. auto common_name = cert.subject_cn();
  7946. EXPECT_EQ("Common Name", common_name);
  7947. });
  7948. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7949. auto se = detail::scope_exit([&] {
  7950. svr.stop();
  7951. t.join();
  7952. ASSERT_FALSE(svr.is_running());
  7953. });
  7954. svr.wait_until_ready();
  7955. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7956. cli.enable_server_certificate_verification(false);
  7957. cli.set_connection_timeout(30);
  7958. auto res = cli.Get("/test");
  7959. ASSERT_TRUE(res);
  7960. ASSERT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. // Test verify_hostname for both OpenSSL and MbedTLS backends
  7963. // Verifies that wildcard matching and exact matching work consistently
  7964. TEST(SSLClientServerTest, TlsVerifyHostname) {
  7965. using namespace httplib::tls;
  7966. // We need a running server to test against
  7967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7968. ASSERT_TRUE(svr.is_valid());
  7969. svr.Get("/test", [](const Request &, Response &res) {
  7970. res.set_content("ok", "text/plain");
  7971. });
  7972. thread t([&]() { svr.listen(HOST, PORT); });
  7973. auto se = detail::scope_exit([&] {
  7974. svr.stop();
  7975. t.join();
  7976. });
  7977. svr.wait_until_ready();
  7978. bool verify_callback_called = false;
  7979. bool verify_result_wrong = false;
  7980. SSLClient cli(HOST, PORT);
  7981. cli.enable_server_certificate_verification(true);
  7982. cli.set_ca_cert_path(CA_CERT_FILE);
  7983. cli.set_connection_timeout(5);
  7984. // Note: Test certificate has CN="Common Name", not "localhost"
  7985. bool verify_result_cn = false;
  7986. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7987. verify_callback_called = true;
  7988. if (!ctx.cert) return false;
  7989. // Test 1: "Common Name" should match (our test server cert CN)
  7990. verify_result_cn = ctx.check_hostname("Common Name");
  7991. // Test 2: wrong hostname should not match
  7992. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  7993. return true; // Accept for the purpose of this test
  7994. });
  7995. auto res = cli.Get("/test");
  7996. // The request may succeed or fail depending on cert configuration
  7997. // but the callback should have been called
  7998. ASSERT_TRUE(verify_callback_called)
  7999. << "Verify callback should have been called";
  8000. // CN="Common Name" should match our test certificate
  8001. EXPECT_TRUE(verify_result_cn)
  8002. << "verify_hostname should match 'Common Name' (certificate CN)";
  8003. // Wrong hostname should not match
  8004. EXPECT_FALSE(verify_result_wrong)
  8005. << "verify_hostname should not match 'wronghost.example.com'";
  8006. }
  8007. #endif
  8008. // mbedTLS-specific callback constructor test
  8009. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8010. #ifdef CPPHTTPLIB_SSL_ENABLED
  8011. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8013. ASSERT_TRUE(svr.is_valid());
  8014. // Set up a handler to verify client certificate is present
  8015. bool client_cert_verified = false;
  8016. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8017. // Verify that client certificate was provided
  8018. client_cert_verified = true;
  8019. res.set_content("success", "text/plain");
  8020. });
  8021. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8022. auto se = detail::scope_exit([&] {
  8023. svr.stop();
  8024. t.join();
  8025. ASSERT_FALSE(svr.is_running());
  8026. });
  8027. svr.wait_until_ready();
  8028. // Client with certificate
  8029. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8030. cli.enable_server_certificate_verification(false);
  8031. cli.set_connection_timeout(30);
  8032. auto res = cli.Get("/test");
  8033. ASSERT_TRUE(res);
  8034. ASSERT_EQ(StatusCode::OK_200, res->status);
  8035. ASSERT_TRUE(client_cert_verified);
  8036. EXPECT_EQ("success", res->body);
  8037. }
  8038. #endif
  8039. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8040. // backends
  8041. #ifdef CPPHTTPLIB_SSL_ENABLED
  8042. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8043. using namespace httplib::tls;
  8044. // Test that when client CA cert file is provided,
  8045. // the server properly requests and validates client certificates
  8046. // Create a server with client authentication
  8047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8048. ASSERT_TRUE(svr.is_valid());
  8049. bool handler_called = false;
  8050. svr.Get("/test", [&](const Request &req, Response &res) {
  8051. handler_called = true;
  8052. // Verify that a client certificate was provided
  8053. auto cert = req.peer_cert();
  8054. ASSERT_TRUE(static_cast<bool>(cert));
  8055. // Get the issuer name
  8056. std::string issuer_str = cert.issuer_name();
  8057. ASSERT_FALSE(issuer_str.empty());
  8058. // The client certificate should be issued by our test CA
  8059. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8060. res.set_content("authenticated", "text/plain");
  8061. });
  8062. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8063. auto se = detail::scope_exit([&] {
  8064. svr.stop();
  8065. t.join();
  8066. ASSERT_FALSE(svr.is_running());
  8067. });
  8068. svr.wait_until_ready();
  8069. // Connect with a client certificate issued by the CA
  8070. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8071. cli.enable_server_certificate_verification(false);
  8072. cli.set_connection_timeout(30);
  8073. auto res = cli.Get("/test");
  8074. ASSERT_TRUE(res);
  8075. ASSERT_EQ(StatusCode::OK_200, res->status);
  8076. ASSERT_TRUE(handler_called);
  8077. EXPECT_EQ("authenticated", res->body);
  8078. }
  8079. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8080. using namespace httplib::tls;
  8081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8082. ASSERT_TRUE(svr.is_valid());
  8083. svr.Get("/test", [](const Request &, Response &res) {
  8084. res.set_content("ok", "text/plain");
  8085. });
  8086. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8087. auto se = detail::scope_exit([&] {
  8088. svr.stop();
  8089. t.join();
  8090. });
  8091. svr.wait_until_ready();
  8092. SSLClient cli(HOST, PORT);
  8093. cli.enable_server_certificate_verification(false);
  8094. cli.set_connection_timeout(30);
  8095. bool cert_checked = false;
  8096. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8097. if (ctx.cert) {
  8098. auto sans = ctx.sans();
  8099. // Test certificate may or may not have SANs - just verify the API
  8100. // works If SANs exist, verify the types are valid
  8101. for (const auto &san : sans) {
  8102. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8103. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8104. san.type == SanType::OTHER);
  8105. EXPECT_FALSE(san.value.empty());
  8106. }
  8107. cert_checked = true;
  8108. }
  8109. return true;
  8110. });
  8111. auto res = cli.Get("/test");
  8112. ASSERT_TRUE(res);
  8113. EXPECT_TRUE(cert_checked);
  8114. }
  8115. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8116. using namespace httplib::tls;
  8117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8118. ASSERT_TRUE(svr.is_valid());
  8119. svr.Get("/test", [](const Request &, Response &res) {
  8120. res.set_content("ok", "text/plain");
  8121. });
  8122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8123. auto se = detail::scope_exit([&] {
  8124. svr.stop();
  8125. t.join();
  8126. });
  8127. svr.wait_until_ready();
  8128. SSLClient cli(HOST, PORT);
  8129. cli.enable_server_certificate_verification(false);
  8130. cli.set_connection_timeout(30);
  8131. bool validity_checked = false;
  8132. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8133. if (ctx.cert) {
  8134. time_t not_before = 0, not_after = 0;
  8135. bool result = ctx.validity(not_before, not_after);
  8136. EXPECT_TRUE(result);
  8137. // Verify that not_before < now < not_after for a valid cert
  8138. time_t now = time(nullptr);
  8139. EXPECT_LT(not_before, now);
  8140. EXPECT_GT(not_after, now);
  8141. validity_checked = true;
  8142. }
  8143. return true;
  8144. });
  8145. auto res = cli.Get("/test");
  8146. ASSERT_TRUE(res);
  8147. EXPECT_TRUE(validity_checked);
  8148. }
  8149. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8150. using namespace httplib::tls;
  8151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8152. ASSERT_TRUE(svr.is_valid());
  8153. svr.Get("/test", [](const Request &, Response &res) {
  8154. res.set_content("ok", "text/plain");
  8155. });
  8156. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8157. auto se = detail::scope_exit([&] {
  8158. svr.stop();
  8159. t.join();
  8160. });
  8161. svr.wait_until_ready();
  8162. SSLClient cli(HOST, PORT);
  8163. cli.enable_server_certificate_verification(false);
  8164. cli.set_connection_timeout(30);
  8165. bool serial_checked = false;
  8166. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8167. if (ctx.cert) {
  8168. std::string serial = ctx.serial();
  8169. EXPECT_FALSE(serial.empty());
  8170. // Serial should be a hex string
  8171. for (char c : serial) {
  8172. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8173. (c >= 'a' && c <= 'f'));
  8174. }
  8175. serial_checked = true;
  8176. }
  8177. return true;
  8178. });
  8179. auto res = cli.Get("/test");
  8180. ASSERT_TRUE(res);
  8181. EXPECT_TRUE(serial_checked);
  8182. }
  8183. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8184. // Test 1: Valid CA file - no error should be recorded
  8185. {
  8186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8187. CLIENT_CA_CERT_FILE);
  8188. ASSERT_TRUE(svr.is_valid());
  8189. // With valid setup, last_ssl_error should be 0
  8190. EXPECT_EQ(0, svr.ssl_last_error());
  8191. }
  8192. // Test 2: Invalid CA file content
  8193. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8194. {
  8195. // Create a temporary file with completely invalid content
  8196. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8197. {
  8198. std::ofstream ofs(temp_invalid_ca);
  8199. ofs << "This is not a certificate file at all\n";
  8200. ofs << "Just plain text content\n";
  8201. }
  8202. // Create server with invalid CA file
  8203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8204. // Clean up temporary file
  8205. std::remove(temp_invalid_ca);
  8206. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8207. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8208. // Note: SSL_CTX_load_verify_locations typically fails first,
  8209. // but our error handling code path is still exercised
  8210. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8211. }
  8212. }
  8213. TEST(VerifyCallbackTest, VerifyContextFields) {
  8214. using namespace httplib::tls;
  8215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8216. ASSERT_TRUE(svr.is_valid());
  8217. svr.Get("/test", [](const Request &, Response &res) {
  8218. res.set_content("ok", "text/plain");
  8219. });
  8220. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8221. auto se = detail::scope_exit([&] {
  8222. svr.stop();
  8223. t.join();
  8224. });
  8225. svr.wait_until_ready();
  8226. SSLClient cli(HOST, PORT);
  8227. cli.enable_server_certificate_verification(false);
  8228. cli.set_connection_timeout(30);
  8229. int callback_count = 0;
  8230. bool saw_leaf_cert = false;
  8231. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8232. if (ctx.cert) {
  8233. callback_count++;
  8234. // We should see at least one certificate (the leaf)
  8235. std::string cn = ctx.subject_cn();
  8236. if (!cn.empty()) { saw_leaf_cert = true; }
  8237. // Verify context fields are populated
  8238. EXPECT_NE(ctx.session, nullptr);
  8239. EXPECT_GE(ctx.depth, 0);
  8240. }
  8241. return true;
  8242. });
  8243. auto res = cli.Get("/test");
  8244. ASSERT_TRUE(res);
  8245. EXPECT_GT(callback_count, 0);
  8246. EXPECT_TRUE(saw_leaf_cert);
  8247. }
  8248. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8249. using httplib::tls::TlsError;
  8250. // Test that verify_error_to_string returns empty for success
  8251. std::string success_str = TlsError::verify_error_to_string(0);
  8252. EXPECT_TRUE(success_str.empty());
  8253. // Test that verify_error_to_string returns non-empty for error codes
  8254. // Using a common error code (certificate expired)
  8255. std::string error_str =
  8256. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8257. EXPECT_FALSE(error_str.empty());
  8258. }
  8259. TEST(SessionVerifierTest, CertificateAccepted) {
  8260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8261. ASSERT_TRUE(svr.is_valid());
  8262. svr.Get("/test", [](const Request &, Response &res) {
  8263. res.set_content("ok", "text/plain");
  8264. });
  8265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8266. auto se = detail::scope_exit([&] {
  8267. svr.stop();
  8268. t.join();
  8269. });
  8270. svr.wait_until_ready();
  8271. SSLClient cli(HOST, PORT);
  8272. cli.enable_server_certificate_verification(false);
  8273. cli.set_connection_timeout(30);
  8274. bool callback_called = false;
  8275. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8276. EXPECT_NE(session, nullptr);
  8277. callback_called = true;
  8278. return SSLVerifierResponse::CertificateAccepted;
  8279. });
  8280. auto res = cli.Get("/test");
  8281. ASSERT_TRUE(res);
  8282. EXPECT_EQ(200, res->status);
  8283. EXPECT_TRUE(callback_called);
  8284. }
  8285. TEST(SessionVerifierTest, CertificateRejected) {
  8286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8287. ASSERT_TRUE(svr.is_valid());
  8288. svr.Get("/test", [](const Request &, Response &res) {
  8289. res.set_content("ok", "text/plain");
  8290. });
  8291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8292. auto se = detail::scope_exit([&] {
  8293. svr.stop();
  8294. t.join();
  8295. });
  8296. svr.wait_until_ready();
  8297. SSLClient cli(HOST, PORT);
  8298. cli.enable_server_certificate_verification(false);
  8299. cli.set_connection_timeout(30);
  8300. bool callback_called = false;
  8301. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8302. EXPECT_NE(session, nullptr);
  8303. callback_called = true;
  8304. return SSLVerifierResponse::CertificateRejected;
  8305. });
  8306. auto res = cli.Get("/test");
  8307. EXPECT_FALSE(res);
  8308. EXPECT_TRUE(callback_called);
  8309. }
  8310. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8312. ASSERT_TRUE(svr.is_valid());
  8313. svr.Get("/test", [](const Request &, Response &res) {
  8314. res.set_content("ok", "text/plain");
  8315. });
  8316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8317. auto se = detail::scope_exit([&] {
  8318. svr.stop();
  8319. t.join();
  8320. });
  8321. svr.wait_until_ready();
  8322. // NoDecisionMade with verification disabled should succeed (no default check)
  8323. SSLClient cli(HOST, PORT);
  8324. cli.enable_server_certificate_verification(false);
  8325. cli.set_connection_timeout(30);
  8326. bool callback_called = false;
  8327. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8328. EXPECT_NE(session, nullptr);
  8329. callback_called = true;
  8330. return SSLVerifierResponse::NoDecisionMade;
  8331. });
  8332. auto res = cli.Get("/test");
  8333. ASSERT_TRUE(res);
  8334. EXPECT_EQ(200, res->status);
  8335. EXPECT_TRUE(callback_called);
  8336. }
  8337. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8339. ASSERT_TRUE(svr.is_valid());
  8340. svr.Get("/test", [](const Request &, Response &res) {
  8341. res.set_content("ok", "text/plain");
  8342. });
  8343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8344. auto se = detail::scope_exit([&] {
  8345. svr.stop();
  8346. t.join();
  8347. });
  8348. svr.wait_until_ready();
  8349. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8350. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8351. // so we only check that the request fails, not whether the callback was
  8352. // called.
  8353. SSLClient cli(HOST, PORT);
  8354. cli.enable_server_certificate_verification(true);
  8355. cli.set_connection_timeout(30);
  8356. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8357. EXPECT_NE(session, nullptr);
  8358. return SSLVerifierResponse::NoDecisionMade;
  8359. });
  8360. auto res = cli.Get("/test");
  8361. EXPECT_FALSE(res);
  8362. }
  8363. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8364. // Test SSL server using PemMemory constructor with client CA certificates
  8365. // Read PEM files
  8366. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8367. read_file(SERVER_CERT_FILE, server_cert_pem);
  8368. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8369. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8370. // Create SSLServer with PemMemory constructor including client CA
  8371. SSLServer::PemMemory server_pem = {
  8372. server_cert_pem.c_str(),
  8373. server_cert_pem.size(),
  8374. server_key_pem.c_str(),
  8375. server_key_pem.size(),
  8376. client_ca_pem.c_str(),
  8377. client_ca_pem.size(),
  8378. nullptr // no password for server key
  8379. };
  8380. SSLServer svr(server_pem);
  8381. ASSERT_TRUE(svr.is_valid());
  8382. // No SSL error should be recorded for valid setup
  8383. EXPECT_EQ(0, svr.ssl_last_error());
  8384. // Set up server endpoints
  8385. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8386. res.set_content("ok", "text/plain");
  8387. });
  8388. // Start server in a thread
  8389. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8390. svr.wait_until_ready();
  8391. // Connect with client certificate (using constructor with paths)
  8392. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8393. cli.enable_server_certificate_verification(false);
  8394. auto res = cli.Get("/test-pem-ca");
  8395. ASSERT_TRUE(res);
  8396. EXPECT_EQ(200, res->status);
  8397. EXPECT_EQ("ok", res->body);
  8398. svr.stop();
  8399. server_thread.join();
  8400. }
  8401. #endif
  8402. #ifdef _WIN32
  8403. TEST(CleanupTest, WSACleanup) {
  8404. int ret = WSACleanup();
  8405. ASSERT_EQ(0, ret);
  8406. }
  8407. #endif
  8408. #ifndef CPPHTTPLIB_SSL_ENABLED
  8409. TEST(NoSSLSupport, SimpleInterface) {
  8410. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8411. }
  8412. #endif
  8413. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8414. TEST(InvalidScheme, SimpleInterface) {
  8415. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8416. }
  8417. #endif
  8418. TEST(NoScheme, SimpleInterface) {
  8419. Client cli("yahoo.com:80");
  8420. ASSERT_TRUE(cli.is_valid());
  8421. }
  8422. TEST(SendAPI, SimpleInterface_Online) {
  8423. Client cli("http://yahoo.com");
  8424. Request req;
  8425. req.method = "GET";
  8426. req.path = "/";
  8427. auto res = cli.send(req);
  8428. ASSERT_TRUE(res);
  8429. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8430. }
  8431. TEST(SendAPI, WithParamsInRequest) {
  8432. Server svr;
  8433. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8434. EXPECT_TRUE(req.has_param("test"));
  8435. EXPECT_EQ("test_value", req.get_param_value("test"));
  8436. });
  8437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8438. auto se = detail::scope_exit([&] {
  8439. svr.stop();
  8440. t.join();
  8441. ASSERT_FALSE(svr.is_running());
  8442. });
  8443. svr.wait_until_ready();
  8444. Client cli(HOST, PORT);
  8445. {
  8446. Request req;
  8447. req.method = "GET";
  8448. req.path = "/";
  8449. req.params.emplace("test", "test_value");
  8450. auto res = cli.send(req);
  8451. ASSERT_TRUE(res);
  8452. }
  8453. {
  8454. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8455. ASSERT_TRUE(res);
  8456. }
  8457. }
  8458. TEST(ClientImplMethods, GetSocketTest) {
  8459. httplib::Server svr;
  8460. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8461. res.status = StatusCode::OK_200;
  8462. });
  8463. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8464. auto se = detail::scope_exit([&] {
  8465. svr.stop();
  8466. thread.join();
  8467. ASSERT_FALSE(svr.is_running());
  8468. });
  8469. svr.wait_until_ready();
  8470. {
  8471. httplib::Client cli("http://127.0.0.1:3333");
  8472. cli.set_keep_alive(true);
  8473. // Use the behavior of cpp-httplib of opening the connection
  8474. // only when the first request happens. If that changes,
  8475. // this test would be obsolete.
  8476. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8477. // This also implicitly tests the server. But other tests would fail much
  8478. // earlier than this one to be considered.
  8479. auto res = cli.Get("/");
  8480. ASSERT_TRUE(res);
  8481. EXPECT_EQ(StatusCode::OK_200, res->status);
  8482. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8483. }
  8484. }
  8485. // Disabled due to out-of-memory problem on GitHub Actions
  8486. #ifdef _WIN64
  8487. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8488. // allocate content size larger than 2GB in memory
  8489. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8490. char *content = (char *)malloc(content_size);
  8491. ASSERT_TRUE(content);
  8492. Server svr;
  8493. svr.Get("/foo",
  8494. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8495. res.set_content(content, content_size, "application/octet-stream");
  8496. });
  8497. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8498. auto se = detail::scope_exit([&] {
  8499. svr.stop();
  8500. listen_thread.join();
  8501. if (content) free(content);
  8502. ASSERT_FALSE(svr.is_running());
  8503. });
  8504. svr.wait_until_ready();
  8505. Client cli(HOST, PORT);
  8506. auto res = cli.Get("/foo");
  8507. ASSERT_TRUE(res);
  8508. EXPECT_EQ(StatusCode::OK_200, res->status);
  8509. EXPECT_EQ(content_size, res->body.length());
  8510. }
  8511. #endif
  8512. #ifdef CPPHTTPLIB_SSL_ENABLED
  8513. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8514. Client cli("http://yahoo.com");
  8515. auto res = cli.Get("/");
  8516. ASSERT_TRUE(res);
  8517. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8518. cli.set_follow_location(true);
  8519. res = cli.Get("/");
  8520. ASSERT_TRUE(res);
  8521. EXPECT_EQ(StatusCode::OK_200, res->status);
  8522. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8523. }
  8524. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8525. Client cli("https://yahoo.com");
  8526. auto res = cli.Get("/");
  8527. ASSERT_TRUE(res);
  8528. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8529. cli.set_follow_location(true);
  8530. res = cli.Get("/");
  8531. ASSERT_TRUE(res);
  8532. EXPECT_EQ(StatusCode::OK_200, res->status);
  8533. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8534. }
  8535. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8536. Client cli("https://yahoo.com");
  8537. auto res = cli.Get("/");
  8538. ASSERT_TRUE(res);
  8539. ASSERT_FALSE(!res);
  8540. ASSERT_TRUE(res);
  8541. ASSERT_FALSE(res == nullptr);
  8542. ASSERT_TRUE(res != nullptr);
  8543. EXPECT_EQ(Error::Success, res.error());
  8544. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8545. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8546. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8547. cli.set_follow_location(true);
  8548. res = cli.Get("/");
  8549. ASSERT_TRUE(res);
  8550. EXPECT_EQ(Error::Success, res.error());
  8551. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8552. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8553. EXPECT_EQ(StatusCode::OK_200, res->status);
  8554. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8555. }
  8556. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8557. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8558. Client cli("https://cdnjs.cloudflare.com");
  8559. auto res =
  8560. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8561. ASSERT_TRUE(res);
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. EXPECT_EQ(287630U, res->body.size());
  8564. EXPECT_EQ("application/javascript; charset=utf-8",
  8565. res->get_header_value("Content-Type"));
  8566. }
  8567. #endif
  8568. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8569. #undef REDIR_HOST // Silence compiler warning
  8570. #define REDIR_HOST "https://httpbingo.org"
  8571. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8572. Client cli(REDIR_HOST);
  8573. cli.set_follow_location(true);
  8574. auto res =
  8575. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8576. ASSERT_TRUE(res);
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. }
  8579. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8580. Client cli(REDIR_HOST);
  8581. cli.set_follow_location(true);
  8582. Params params;
  8583. params.emplace("url", "http://example.com");
  8584. params.emplace("status_code", "302");
  8585. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8586. ASSERT_TRUE(res);
  8587. EXPECT_EQ(StatusCode::OK_200, res->status);
  8588. }
  8589. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8590. Client cli(REDIR_HOST);
  8591. cli.set_follow_location(true);
  8592. Params params;
  8593. params.emplace("url", "http://example.com");
  8594. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8595. ASSERT_TRUE(res);
  8596. EXPECT_EQ(StatusCode::OK_200, res->status);
  8597. }
  8598. TEST(HttpToHttpsRedirectTest, CertFile) {
  8599. Server svr;
  8600. ASSERT_TRUE(svr.is_valid());
  8601. svr.Get("/index", [&](const Request &, Response &res) {
  8602. res.set_redirect("https://127.0.0.1:1235/index");
  8603. svr.stop();
  8604. });
  8605. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8606. ASSERT_TRUE(ssl_svr.is_valid());
  8607. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8608. res.set_content("test", "text/plain");
  8609. ssl_svr.stop();
  8610. });
  8611. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8612. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8613. auto se = detail::scope_exit([&] {
  8614. t2.join();
  8615. t.join();
  8616. ASSERT_FALSE(svr.is_running());
  8617. });
  8618. svr.wait_until_ready();
  8619. ssl_svr.wait_until_ready();
  8620. Client cli("127.0.0.1", PORT);
  8621. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8622. cli.enable_server_certificate_verification(true);
  8623. cli.set_follow_location(true);
  8624. cli.set_connection_timeout(30);
  8625. auto res = cli.Get("/index");
  8626. ASSERT_TRUE(res);
  8627. ASSERT_EQ(StatusCode::OK_200, res->status);
  8628. }
  8629. TEST(SSLClientRedirectTest, CertFile) {
  8630. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8631. ASSERT_TRUE(ssl_svr1.is_valid());
  8632. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8633. res.set_redirect("https://127.0.0.1:1235/index");
  8634. ssl_svr1.stop();
  8635. });
  8636. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8637. ASSERT_TRUE(ssl_svr2.is_valid());
  8638. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8639. res.set_content("test", "text/plain");
  8640. ssl_svr2.stop();
  8641. });
  8642. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8643. thread t2 =
  8644. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8645. auto se = detail::scope_exit([&] {
  8646. t2.join();
  8647. t.join();
  8648. ASSERT_FALSE(ssl_svr1.is_running());
  8649. });
  8650. ssl_svr1.wait_until_ready();
  8651. ssl_svr2.wait_until_ready();
  8652. SSLClient cli("127.0.0.1", PORT);
  8653. std::string cert;
  8654. read_file(SERVER_CERT2_FILE, cert);
  8655. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8656. cli.enable_server_certificate_verification(true);
  8657. cli.set_follow_location(true);
  8658. cli.set_connection_timeout(30);
  8659. auto res = cli.Get("/index");
  8660. ASSERT_TRUE(res);
  8661. ASSERT_EQ(StatusCode::OK_200, res->status);
  8662. }
  8663. #endif
  8664. #ifdef CPPHTTPLIB_SSL_ENABLED
  8665. // Test that set_ca_cert_store() skips system certs (consistent with
  8666. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8667. // should be trusted - system certs should NOT be loaded.
  8668. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8669. // Load a specific cert that is NOT a system CA cert
  8670. std::string cert;
  8671. read_file(SERVER_CERT2_FILE, cert);
  8672. SSLClient cli("google.com");
  8673. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8674. cli.enable_server_certificate_verification(true);
  8675. // This should FAIL because:
  8676. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8677. // 2. System certs should NOT be loaded when custom store is set
  8678. // If system certs WERE loaded, this would succeed
  8679. auto res = cli.Get("/");
  8680. ASSERT_FALSE(res);
  8681. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8682. }
  8683. TEST(MultipartFormDataTest, LargeData) {
  8684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8685. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8686. const ContentReader &content_reader) {
  8687. if (req.is_multipart_form_data()) {
  8688. std::vector<FormData> items;
  8689. content_reader(
  8690. [&](const FormData &file) {
  8691. items.push_back(file);
  8692. return true;
  8693. },
  8694. [&](const char *data, size_t data_length) {
  8695. items.back().content.append(data, data_length);
  8696. return true;
  8697. });
  8698. EXPECT_TRUE(std::string(items[0].name) == "document");
  8699. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8700. EXPECT_TRUE(items[0].filename == "2MB_data");
  8701. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8702. EXPECT_TRUE(items[1].name == "hello");
  8703. EXPECT_TRUE(items[1].content == "world");
  8704. EXPECT_TRUE(items[1].filename == "");
  8705. EXPECT_TRUE(items[1].content_type == "");
  8706. } else {
  8707. std::string body;
  8708. content_reader([&](const char *data, size_t data_length) {
  8709. body.append(data, data_length);
  8710. return true;
  8711. });
  8712. }
  8713. });
  8714. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. t.join();
  8718. ASSERT_FALSE(svr.is_running());
  8719. });
  8720. svr.wait_until_ready();
  8721. {
  8722. std::string data(1024 * 1024 * 2, '.');
  8723. std::stringstream buffer;
  8724. buffer << data;
  8725. Client cli("https://localhost:8080");
  8726. cli.enable_server_certificate_verification(false);
  8727. UploadFormDataItems items{
  8728. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8729. {"hello", "world", "", ""},
  8730. };
  8731. auto res = cli.Post("/post", items);
  8732. ASSERT_TRUE(res);
  8733. ASSERT_EQ(StatusCode::OK_200, res->status);
  8734. }
  8735. }
  8736. TEST(MultipartFormDataTest, DataProviderItems) {
  8737. std::random_device seed_gen;
  8738. std::mt19937 random(seed_gen());
  8739. std::string rand1;
  8740. rand1.resize(1000);
  8741. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8742. std::string rand2;
  8743. rand2.resize(3000);
  8744. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8747. const ContentReader &content_reader) {
  8748. ASSERT_FALSE(req.is_multipart_form_data());
  8749. std::string body;
  8750. content_reader([&](const char *data, size_t data_length) {
  8751. body.append(data, data_length);
  8752. return true;
  8753. });
  8754. EXPECT_EQ(body, "");
  8755. });
  8756. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8757. const ContentReader &content_reader) {
  8758. ASSERT_TRUE(req.is_multipart_form_data());
  8759. std::vector<FormData> items;
  8760. content_reader(
  8761. [&](const FormData &file) {
  8762. items.push_back(file);
  8763. return true;
  8764. },
  8765. [&](const char *data, size_t data_length) {
  8766. items.back().content.append(data, data_length);
  8767. return true;
  8768. });
  8769. ASSERT_TRUE(items.size() == 2);
  8770. EXPECT_EQ(std::string(items[0].name), "name1");
  8771. EXPECT_EQ(items[0].content, "Testing123");
  8772. EXPECT_EQ(items[0].filename, "filename1");
  8773. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8774. EXPECT_EQ(items[1].name, "name2");
  8775. EXPECT_EQ(items[1].content, "Testing456");
  8776. EXPECT_EQ(items[1].filename, "");
  8777. EXPECT_EQ(items[1].content_type, "");
  8778. });
  8779. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8780. const ContentReader &content_reader) {
  8781. ASSERT_TRUE(req.is_multipart_form_data());
  8782. std::vector<FormData> items;
  8783. content_reader(
  8784. [&](const FormData &file) {
  8785. items.push_back(file);
  8786. return true;
  8787. },
  8788. [&](const char *data, size_t data_length) {
  8789. items.back().content.append(data, data_length);
  8790. return true;
  8791. });
  8792. ASSERT_TRUE(items.size() == 2);
  8793. EXPECT_EQ(items[0].name, "name3");
  8794. EXPECT_EQ(items[0].content, rand1);
  8795. EXPECT_EQ(items[0].filename, "filename3");
  8796. EXPECT_EQ(items[0].content_type, "");
  8797. EXPECT_EQ(items[1].name, "name4");
  8798. EXPECT_EQ(items[1].content, rand2);
  8799. EXPECT_EQ(items[1].filename, "filename4");
  8800. EXPECT_EQ(items[1].content_type, "");
  8801. });
  8802. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8803. const ContentReader &content_reader) {
  8804. ASSERT_TRUE(req.is_multipart_form_data());
  8805. std::vector<FormData> items;
  8806. content_reader(
  8807. [&](const FormData &file) {
  8808. items.push_back(file);
  8809. return true;
  8810. },
  8811. [&](const char *data, size_t data_length) {
  8812. items.back().content.append(data, data_length);
  8813. return true;
  8814. });
  8815. ASSERT_TRUE(items.size() == 4);
  8816. EXPECT_EQ(std::string(items[0].name), "name1");
  8817. EXPECT_EQ(items[0].content, "Testing123");
  8818. EXPECT_EQ(items[0].filename, "filename1");
  8819. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8820. EXPECT_EQ(items[1].name, "name2");
  8821. EXPECT_EQ(items[1].content, "Testing456");
  8822. EXPECT_EQ(items[1].filename, "");
  8823. EXPECT_EQ(items[1].content_type, "");
  8824. EXPECT_EQ(items[2].name, "name3");
  8825. EXPECT_EQ(items[2].content, rand1);
  8826. EXPECT_EQ(items[2].filename, "filename3");
  8827. EXPECT_EQ(items[2].content_type, "");
  8828. EXPECT_EQ(items[3].name, "name4");
  8829. EXPECT_EQ(items[3].content, rand2);
  8830. EXPECT_EQ(items[3].filename, "filename4");
  8831. EXPECT_EQ(items[3].content_type, "");
  8832. });
  8833. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. t.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. {
  8841. Client cli("https://localhost:8080");
  8842. cli.enable_server_certificate_verification(false);
  8843. UploadFormDataItems items{
  8844. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8845. {"name2", "Testing456", "", ""}, // not a file
  8846. };
  8847. {
  8848. auto res = cli.Post("/post-none", {}, {}, {});
  8849. ASSERT_TRUE(res);
  8850. ASSERT_EQ(StatusCode::OK_200, res->status);
  8851. }
  8852. FormDataProviderItems providers;
  8853. {
  8854. auto res =
  8855. cli.Post("/post-items", {}, items, providers); // empty providers
  8856. ASSERT_TRUE(res);
  8857. ASSERT_EQ(StatusCode::OK_200, res->status);
  8858. }
  8859. providers.push_back({"name3",
  8860. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8861. // test the offset is given correctly at each step
  8862. if (!offset)
  8863. sink.os.write(rand1.data(), 30);
  8864. else if (offset == 30)
  8865. sink.os.write(rand1.data() + 30, 300);
  8866. else if (offset == 330)
  8867. sink.os.write(rand1.data() + 330, 670);
  8868. else if (offset == rand1.size())
  8869. sink.done();
  8870. return true;
  8871. },
  8872. "filename3",
  8873. {}});
  8874. providers.push_back({"name4",
  8875. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8876. // test the offset is given correctly at each step
  8877. if (!offset)
  8878. sink.os.write(rand2.data(), 2000);
  8879. else if (offset == 2000)
  8880. sink.os.write(rand2.data() + 2000, 1);
  8881. else if (offset == 2001)
  8882. sink.os.write(rand2.data() + 2001, 999);
  8883. else if (offset == rand2.size())
  8884. sink.done();
  8885. return true;
  8886. },
  8887. "filename4",
  8888. {}});
  8889. {
  8890. auto res = cli.Post("/post-providers", {}, {}, providers);
  8891. ASSERT_TRUE(res);
  8892. ASSERT_EQ(StatusCode::OK_200, res->status);
  8893. }
  8894. {
  8895. auto res = cli.Post("/post-both", {}, items, providers);
  8896. ASSERT_TRUE(res);
  8897. ASSERT_EQ(StatusCode::OK_200, res->status);
  8898. }
  8899. }
  8900. }
  8901. TEST(MultipartFormDataTest, BadHeader) {
  8902. Server svr;
  8903. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8904. res.set_content("ok", "text/plain");
  8905. });
  8906. thread t = thread([&] { svr.listen(HOST, PORT); });
  8907. auto se = detail::scope_exit([&] {
  8908. svr.stop();
  8909. t.join();
  8910. ASSERT_FALSE(svr.is_running());
  8911. });
  8912. svr.wait_until_ready();
  8913. const std::string body =
  8914. "This is the preamble. It is to be ignored, though it\r\n"
  8915. "is a handy place for composition agents to include an\r\n"
  8916. "explanatory note to non-MIME conformant readers.\r\n"
  8917. "\r\n"
  8918. "\r\n"
  8919. "--simple boundary\r\n"
  8920. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8921. ": BAD...\r\n"
  8922. "\r\n"
  8923. "value1\r\n"
  8924. "--simple boundary\r\n"
  8925. "Content-Disposition: form-data; name=\"field2\"; "
  8926. "filename=\"example.txt\"\r\n"
  8927. "\r\n"
  8928. "value2\r\n"
  8929. "--simple boundary--\r\n"
  8930. "This is the epilogue. It is also to be ignored.\r\n";
  8931. std::string content_type =
  8932. R"(multipart/form-data; boundary="simple boundary")";
  8933. Client cli(HOST, PORT);
  8934. auto res = cli.Post("/post", body, content_type.c_str());
  8935. ASSERT_TRUE(res);
  8936. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8937. }
  8938. TEST(MultipartFormDataTest, WithPreamble) {
  8939. Server svr;
  8940. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8941. res.set_content("ok", "text/plain");
  8942. });
  8943. thread t = thread([&] { svr.listen(HOST, PORT); });
  8944. auto se = detail::scope_exit([&] {
  8945. svr.stop();
  8946. t.join();
  8947. ASSERT_FALSE(svr.is_running());
  8948. });
  8949. svr.wait_until_ready();
  8950. const std::string body =
  8951. "This is the preamble. It is to be ignored, though it\r\n"
  8952. "is a handy place for composition agents to include an\r\n"
  8953. "explanatory note to non-MIME conformant readers.\r\n"
  8954. "\r\n"
  8955. "\r\n"
  8956. "--simple boundary\r\n"
  8957. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8958. "\r\n"
  8959. "value1\r\n"
  8960. "--simple boundary\r\n"
  8961. "Content-Disposition: form-data; name=\"field2\"; "
  8962. "filename=\"example.txt\"\r\n"
  8963. "\r\n"
  8964. "value2\r\n"
  8965. "--simple boundary--\r\n"
  8966. "This is the epilogue. It is also to be ignored.\r\n";
  8967. std::string content_type =
  8968. R"(multipart/form-data; boundary="simple boundary")";
  8969. Client cli(HOST, PORT);
  8970. auto res = cli.Post("/post", body, content_type.c_str());
  8971. ASSERT_TRUE(res);
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. }
  8974. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8976. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8977. const ContentReader &content_reader) {
  8978. if (req.is_multipart_form_data()) {
  8979. std::vector<FormData> items;
  8980. content_reader(
  8981. [&](const FormData &file) {
  8982. items.push_back(file);
  8983. return true;
  8984. },
  8985. [&](const char *data, size_t data_length) {
  8986. items.back().content.append(data, data_length);
  8987. return true;
  8988. });
  8989. EXPECT_TRUE(std::string(items[0].name) == "document");
  8990. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8991. EXPECT_TRUE(items[0].filename == "2MB_data");
  8992. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8993. EXPECT_TRUE(items[1].name == "hello");
  8994. EXPECT_TRUE(items[1].content == "world");
  8995. EXPECT_TRUE(items[1].filename == "");
  8996. EXPECT_TRUE(items[1].content_type == "");
  8997. } else {
  8998. std::string body;
  8999. content_reader([&](const char *data, size_t data_length) {
  9000. body.append(data, data_length);
  9001. return true;
  9002. });
  9003. }
  9004. });
  9005. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  9006. auto se = detail::scope_exit([&] {
  9007. svr.stop();
  9008. t.join();
  9009. ASSERT_FALSE(svr.is_running());
  9010. });
  9011. svr.wait_until_ready();
  9012. {
  9013. std::string data(1024 * 1024 * 2, '.');
  9014. std::stringstream buffer;
  9015. buffer << data;
  9016. Client cli("https://localhost:8080");
  9017. cli.enable_server_certificate_verification(false);
  9018. UploadFormDataItems items{
  9019. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9020. {"hello", "world", "", ""},
  9021. };
  9022. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9023. ASSERT_TRUE(res);
  9024. ASSERT_EQ(StatusCode::OK_200, res->status);
  9025. }
  9026. }
  9027. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9028. std::string data(1024 * 1024 * 2, '&');
  9029. std::stringstream buffer;
  9030. buffer << data;
  9031. Client cli("https://localhost:8080");
  9032. UploadFormDataItems items{
  9033. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9034. {"hello", "world", "", ""},
  9035. };
  9036. for (const char &c : " \t\r\n") {
  9037. auto res =
  9038. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9039. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9040. ASSERT_FALSE(res);
  9041. }
  9042. }
  9043. TEST(MultipartFormDataTest, PutFormData) {
  9044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9045. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9046. const ContentReader &content_reader) {
  9047. if (req.is_multipart_form_data()) {
  9048. std::vector<FormData> items;
  9049. content_reader(
  9050. [&](const FormData &file) {
  9051. items.push_back(file);
  9052. return true;
  9053. },
  9054. [&](const char *data, size_t data_length) {
  9055. items.back().content.append(data, data_length);
  9056. return true;
  9057. });
  9058. EXPECT_TRUE(std::string(items[0].name) == "document");
  9059. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9060. EXPECT_TRUE(items[0].filename == "2MB_data");
  9061. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9062. EXPECT_TRUE(items[1].name == "hello");
  9063. EXPECT_TRUE(items[1].content == "world");
  9064. EXPECT_TRUE(items[1].filename == "");
  9065. EXPECT_TRUE(items[1].content_type == "");
  9066. } else {
  9067. std::string body;
  9068. content_reader([&](const char *data, size_t data_length) {
  9069. body.append(data, data_length);
  9070. return true;
  9071. });
  9072. }
  9073. });
  9074. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  9075. auto se = detail::scope_exit([&] {
  9076. svr.stop();
  9077. t.join();
  9078. ASSERT_FALSE(svr.is_running());
  9079. });
  9080. svr.wait_until_ready();
  9081. {
  9082. std::string data(1024 * 1024 * 2, '&');
  9083. std::stringstream buffer;
  9084. buffer << data;
  9085. Client cli("https://localhost:8080");
  9086. cli.enable_server_certificate_verification(false);
  9087. UploadFormDataItems items{
  9088. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9089. {"hello", "world", "", ""},
  9090. };
  9091. auto res = cli.Put("/put", items);
  9092. ASSERT_TRUE(res);
  9093. ASSERT_EQ(StatusCode::OK_200, res->status);
  9094. }
  9095. }
  9096. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9098. svr.Put("/put_customboundary",
  9099. [&](const Request &req, const Response & /*res*/,
  9100. const ContentReader &content_reader) {
  9101. if (req.is_multipart_form_data()) {
  9102. std::vector<FormData> items;
  9103. content_reader(
  9104. [&](const FormData &file) {
  9105. items.push_back(file);
  9106. return true;
  9107. },
  9108. [&](const char *data, size_t data_length) {
  9109. items.back().content.append(data, data_length);
  9110. return true;
  9111. });
  9112. EXPECT_TRUE(std::string(items[0].name) == "document");
  9113. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9114. EXPECT_TRUE(items[0].filename == "2MB_data");
  9115. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9116. EXPECT_TRUE(items[1].name == "hello");
  9117. EXPECT_TRUE(items[1].content == "world");
  9118. EXPECT_TRUE(items[1].filename == "");
  9119. EXPECT_TRUE(items[1].content_type == "");
  9120. } else {
  9121. std::string body;
  9122. content_reader([&](const char *data, size_t data_length) {
  9123. body.append(data, data_length);
  9124. return true;
  9125. });
  9126. }
  9127. });
  9128. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  9129. auto se = detail::scope_exit([&] {
  9130. svr.stop();
  9131. t.join();
  9132. ASSERT_FALSE(svr.is_running());
  9133. });
  9134. svr.wait_until_ready();
  9135. {
  9136. std::string data(1024 * 1024 * 2, '&');
  9137. std::stringstream buffer;
  9138. buffer << data;
  9139. Client cli("https://localhost:8080");
  9140. cli.enable_server_certificate_verification(false);
  9141. UploadFormDataItems items{
  9142. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9143. {"hello", "world", "", ""},
  9144. };
  9145. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9146. ASSERT_TRUE(res);
  9147. ASSERT_EQ(StatusCode::OK_200, res->status);
  9148. }
  9149. }
  9150. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9151. std::string data(1024 * 1024 * 2, '&');
  9152. std::stringstream buffer;
  9153. buffer << data;
  9154. Client cli("https://localhost:8080");
  9155. cli.enable_server_certificate_verification(false);
  9156. UploadFormDataItems items{
  9157. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9158. {"hello", "world", "", ""},
  9159. };
  9160. for (const char &c : " \t\r\n") {
  9161. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9162. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9163. ASSERT_FALSE(res);
  9164. }
  9165. }
  9166. TEST(MultipartFormDataTest, AlternateFilename) {
  9167. auto handled = false;
  9168. Server svr;
  9169. svr.Post("/test", [&](const Request &req, Response &res) {
  9170. ASSERT_EQ(2u, req.form.files.size());
  9171. ASSERT_EQ(1u, req.form.fields.size());
  9172. // Test files
  9173. const auto &file1 = req.form.get_file("file1");
  9174. ASSERT_EQ("file1", file1.name);
  9175. ASSERT_EQ("A.txt", file1.filename);
  9176. ASSERT_EQ("text/plain", file1.content_type);
  9177. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9178. const auto &file2 = req.form.get_file("file2");
  9179. ASSERT_EQ("file2", file2.name);
  9180. ASSERT_EQ("a.html", file2.filename);
  9181. ASSERT_EQ("text/html", file2.content_type);
  9182. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9183. file2.content);
  9184. // Test text field
  9185. const auto &text = req.form.get_field("text");
  9186. ASSERT_EQ("text default", text);
  9187. res.set_content("ok", "text/plain");
  9188. handled = true;
  9189. });
  9190. thread t = thread([&] { svr.listen(HOST, PORT); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. t.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. ASSERT_TRUE(handled);
  9196. });
  9197. svr.wait_until_ready();
  9198. auto req = "POST /test HTTP/1.1\r\n"
  9199. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9200. "Content-Length: 399\r\n"
  9201. "\r\n"
  9202. "----------\r\n"
  9203. "Content-Disposition: form-data; name=\"text\"\r\n"
  9204. "\r\n"
  9205. "text default\r\n"
  9206. "----------\r\n"
  9207. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9208. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9209. "Content-Type: text/plain\r\n"
  9210. "\r\n"
  9211. "Content of a.txt.\r\n"
  9212. "\r\n"
  9213. "----------\r\n"
  9214. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9215. "\"a.html\"\r\n"
  9216. "Content-Type: text/html\r\n"
  9217. "\r\n"
  9218. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9219. "\r\n"
  9220. "------------\r\n";
  9221. ASSERT_TRUE(send_request(1, req));
  9222. }
  9223. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9224. auto handled = false;
  9225. Server svr;
  9226. svr.Post("/test", [&](const Request &req, Response &) {
  9227. ASSERT_EQ(2u, req.form.fields.size());
  9228. const auto &text1 = req.form.get_field("text1");
  9229. ASSERT_EQ("text1", text1);
  9230. const auto &text2 = req.form.get_field("text2");
  9231. ASSERT_EQ("text2", text2);
  9232. handled = true;
  9233. });
  9234. thread t = thread([&] { svr.listen(HOST, PORT); });
  9235. auto se = detail::scope_exit([&] {
  9236. svr.stop();
  9237. t.join();
  9238. ASSERT_FALSE(svr.is_running());
  9239. ASSERT_TRUE(handled);
  9240. });
  9241. svr.wait_until_ready();
  9242. auto req = "POST /test HTTP/1.1\r\n"
  9243. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9244. "Content-Length: 146\r\n"
  9245. "\r\n----------\r\n"
  9246. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9247. "\r\n"
  9248. "text1"
  9249. "\r\n----------\r\n"
  9250. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9251. "\r\n"
  9252. "text2"
  9253. "\r\n------------";
  9254. std::string response;
  9255. ASSERT_TRUE(send_request(1, req, &response));
  9256. ASSERT_EQ("200", response.substr(9, 3));
  9257. }
  9258. TEST(MultipartFormDataTest, ContentLength) {
  9259. auto handled = false;
  9260. Server svr;
  9261. svr.Post("/test", [&](const Request &req, Response &) {
  9262. ASSERT_EQ(2u, req.form.fields.size());
  9263. const auto &text1 = req.form.get_field("text1");
  9264. ASSERT_EQ("text1", text1);
  9265. const auto &text2 = req.form.get_field("text2");
  9266. ASSERT_EQ("text2", text2);
  9267. handled = true;
  9268. });
  9269. thread t = thread([&] { svr.listen(HOST, PORT); });
  9270. auto se = detail::scope_exit([&] {
  9271. svr.stop();
  9272. t.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. ASSERT_TRUE(handled);
  9275. });
  9276. svr.wait_until_ready();
  9277. auto req = "POST /test HTTP/1.1\r\n"
  9278. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9279. "Content-Length: 167\r\n"
  9280. "\r\n----------\r\n"
  9281. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9282. "Content-Length: 5\r\n"
  9283. "\r\n"
  9284. "text1"
  9285. "\r\n----------\r\n"
  9286. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9287. "\r\n"
  9288. "text2"
  9289. "\r\n------------\r\n";
  9290. std::string response;
  9291. ASSERT_TRUE(send_request(1, req, &response));
  9292. ASSERT_EQ("200", response.substr(9, 3));
  9293. }
  9294. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9295. auto handled = false;
  9296. Server svr;
  9297. svr.Post("/test", [&](const Request &req, Response &) {
  9298. ASSERT_EQ(2u, req.form.fields.size());
  9299. const auto &text1 = req.form.get_field("text1");
  9300. ASSERT_EQ("text1", text1);
  9301. // TODO: Add header access for text fields if needed
  9302. const auto &text2 = req.form.get_field("text2");
  9303. ASSERT_EQ("text2", text2);
  9304. // TODO: Header access for text fields needs to be implemented
  9305. // auto &headers = it->second.headers;
  9306. // ASSERT_EQ(3U, headers.size());
  9307. // auto custom_header = headers.find("x-whatever");
  9308. // ASSERT_TRUE(custom_header != headers.end());
  9309. // ASSERT_NE("customvalue", custom_header->second);
  9310. // ASSERT_EQ("CustomValue", custom_header->second);
  9311. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9312. handled = true;
  9313. });
  9314. thread t = thread([&] { svr.listen(HOST, PORT); });
  9315. auto se = detail::scope_exit([&] {
  9316. svr.stop();
  9317. t.join();
  9318. ASSERT_FALSE(svr.is_running());
  9319. ASSERT_TRUE(handled);
  9320. });
  9321. svr.wait_until_ready();
  9322. auto req = "POST /test HTTP/1.1\r\n"
  9323. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9324. "Content-Length: 232\r\n"
  9325. "\r\n----------\r\n"
  9326. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9327. "Content-Length: 5\r\n"
  9328. "X-Test: 1\r\n"
  9329. "\r\n"
  9330. "text1"
  9331. "\r\n----------\r\n"
  9332. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9333. "Content-Type: text/plain\r\n"
  9334. "X-Whatever: CustomValue\r\n"
  9335. "\r\n"
  9336. "text2"
  9337. "\r\n------------\r\n"
  9338. "That should be disregarded. Not even read";
  9339. std::string response;
  9340. ASSERT_TRUE(send_request(1, req, &response));
  9341. ASSERT_EQ("200", response.substr(9, 3));
  9342. }
  9343. TEST(MultipartFormDataTest, LargeHeader) {
  9344. auto handled = false;
  9345. Server svr;
  9346. svr.Post("/test", [&](const Request &req, Response &) {
  9347. ASSERT_EQ(1u, req.form.fields.size());
  9348. const auto &text = req.form.get_field("name1");
  9349. ASSERT_EQ("text1", text);
  9350. handled = true;
  9351. });
  9352. thread t = thread([&] { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. ASSERT_TRUE(handled);
  9358. });
  9359. svr.wait_until_ready();
  9360. auto boundary = std::string("cpp-httplib-multipart-data");
  9361. std::string content = "--" + boundary +
  9362. "\r\n"
  9363. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9364. "\r\n"
  9365. "text1\r\n"
  9366. "--" +
  9367. boundary + "--\r\n";
  9368. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9369. "Content-Type: multipart/form-data;boundary=" +
  9370. boundary +
  9371. "\r\n"
  9372. "Content-Length: " +
  9373. std::to_string(content.size()) +
  9374. "\r\n"
  9375. "Dummy-Header: ";
  9376. std::string header_suffix = "\r\n"
  9377. "\r\n";
  9378. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9379. size_t header_dummy_size =
  9380. read_buff_size -
  9381. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9382. auto header_dummy = std::string(header_dummy_size, '@');
  9383. auto req = header_prefix + header_dummy + header_suffix + content;
  9384. std::string response;
  9385. ASSERT_TRUE(send_request(1, req, &response));
  9386. ASSERT_EQ("200", response.substr(9, 3));
  9387. }
  9388. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9389. static constexpr unsigned int number_of_tasks{1000000};
  9390. std::atomic_uint count{0};
  9391. std::unique_ptr<TaskQueue> task_queue{
  9392. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9393. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9394. auto queued = task_queue->enqueue(
  9395. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9396. EXPECT_TRUE(queued);
  9397. }
  9398. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9399. task_queue->shutdown();
  9400. #else
  9401. EXPECT_NO_THROW(task_queue->shutdown());
  9402. #endif
  9403. EXPECT_EQ(number_of_tasks, count.load());
  9404. }
  9405. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9406. static constexpr unsigned int number_of_tasks{1000000};
  9407. static constexpr unsigned int qlimit{2};
  9408. unsigned int queued_count{0};
  9409. std::atomic_uint count{0};
  9410. std::unique_ptr<TaskQueue> task_queue{
  9411. new ThreadPool{/*num_threads=*/1, qlimit}};
  9412. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9413. if (task_queue->enqueue(
  9414. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9415. queued_count++;
  9416. }
  9417. }
  9418. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9419. task_queue->shutdown();
  9420. #else
  9421. EXPECT_NO_THROW(task_queue->shutdown());
  9422. #endif
  9423. EXPECT_EQ(queued_count, count.load());
  9424. EXPECT_TRUE(queued_count <= number_of_tasks);
  9425. EXPECT_TRUE(queued_count >= qlimit);
  9426. }
  9427. TEST(TaskQueueTest, MaxQueuedRequests) {
  9428. static constexpr unsigned int qlimit{3};
  9429. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9430. std::condition_variable sem_cv;
  9431. std::mutex sem_mtx;
  9432. int credits = 0;
  9433. bool queued;
  9434. /* Fill up the queue with tasks that will block until we give them credits to
  9435. * complete. */
  9436. for (unsigned int n = 0; n <= qlimit;) {
  9437. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9438. std::unique_lock<std::mutex> lock(sem_mtx);
  9439. while (credits <= 0) {
  9440. sem_cv.wait(lock);
  9441. }
  9442. /* Consume the credit and signal the test code if they are all gone. */
  9443. if (--credits == 0) { sem_cv.notify_one(); }
  9444. });
  9445. if (n < qlimit) {
  9446. /* The first qlimit enqueues must succeed. */
  9447. EXPECT_TRUE(queued);
  9448. } else {
  9449. /* The last one will succeed only when the worker thread
  9450. * starts and dequeues the first blocking task. Although
  9451. * not necessary for the correctness of this test, we sleep for
  9452. * a short while to avoid busy waiting. */
  9453. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9454. }
  9455. if (queued) { n++; }
  9456. }
  9457. /* Further enqueues must fail since the queue is full. */
  9458. for (auto i = 0; i < 4; i++) {
  9459. queued = task_queue->enqueue([] {});
  9460. EXPECT_FALSE(queued);
  9461. }
  9462. /* Give the credits to allow the previous tasks to complete. */
  9463. {
  9464. std::unique_lock<std::mutex> lock(sem_mtx);
  9465. credits += qlimit + 1;
  9466. }
  9467. sem_cv.notify_all();
  9468. /* Wait for all the credits to be consumed. */
  9469. {
  9470. std::unique_lock<std::mutex> lock(sem_mtx);
  9471. while (credits > 0) {
  9472. sem_cv.wait(lock);
  9473. }
  9474. }
  9475. /* Check that we are able again to enqueue at least qlimit tasks. */
  9476. for (unsigned int i = 0; i < qlimit; i++) {
  9477. queued = task_queue->enqueue([] {});
  9478. EXPECT_TRUE(queued);
  9479. }
  9480. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9481. task_queue->shutdown();
  9482. #else
  9483. EXPECT_NO_THROW(task_queue->shutdown());
  9484. #endif
  9485. }
  9486. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9487. Server svr;
  9488. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9489. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9490. });
  9491. svr.Get("/hello", [](const Request &req, Response &res) {
  9492. res.set_content(req.get_param_value("key"), "text/plain");
  9493. });
  9494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9495. auto se = detail::scope_exit([&] {
  9496. svr.stop();
  9497. thread.join();
  9498. ASSERT_FALSE(svr.is_running());
  9499. });
  9500. svr.wait_until_ready();
  9501. {
  9502. Client cli(HOST, PORT);
  9503. cli.set_follow_location(true);
  9504. auto res = cli.Get("/");
  9505. ASSERT_TRUE(res);
  9506. EXPECT_EQ(StatusCode::OK_200, res->status);
  9507. EXPECT_EQ("val&key2=val2", res->body);
  9508. }
  9509. }
  9510. #endif
  9511. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9512. Server svr;
  9513. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9514. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9515. });
  9516. svr.Get("/hello", [](const Request &req, Response &res) {
  9517. res.set_content(req.get_param_value("key"), "text/plain");
  9518. });
  9519. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9520. auto se = detail::scope_exit([&] {
  9521. svr.stop();
  9522. thread.join();
  9523. ASSERT_FALSE(svr.is_running());
  9524. });
  9525. svr.wait_until_ready();
  9526. {
  9527. Client cli(HOST, PORT);
  9528. cli.set_follow_location(true);
  9529. auto res = cli.Get("/");
  9530. ASSERT_TRUE(res);
  9531. EXPECT_EQ(StatusCode::OK_200, res->status);
  9532. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9533. }
  9534. }
  9535. #ifdef CPPHTTPLIB_SSL_ENABLED
  9536. TEST(RedirectTest, Issue2185_Online) {
  9537. SSLClient client("github.com");
  9538. client.set_follow_location(true);
  9539. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9540. "Coollab-Windows.zip");
  9541. ASSERT_TRUE(res);
  9542. EXPECT_EQ(StatusCode::OK_200, res->status);
  9543. EXPECT_EQ(9920427U, res->body.size());
  9544. }
  9545. #endif
  9546. TEST(VulnerabilityTest, CRLFInjection) {
  9547. Server svr;
  9548. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9549. res.set_content("Hello 1", "text/plain");
  9550. });
  9551. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9552. res.set_content("Hello 2", "text/plain");
  9553. });
  9554. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9555. res.set_content("Hello 3", "text/plain");
  9556. });
  9557. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9558. res.set_content("Hello 4", "text/plain");
  9559. });
  9560. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9561. for (const auto &x : req.headers) {
  9562. auto key = x.first;
  9563. EXPECT_STRNE("evil", key.c_str());
  9564. }
  9565. });
  9566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9567. auto se = detail::scope_exit([&] {
  9568. svr.stop();
  9569. thread.join();
  9570. ASSERT_FALSE(svr.is_running());
  9571. });
  9572. svr.wait_until_ready();
  9573. {
  9574. Client cli(HOST, PORT);
  9575. cli.Post("/test1", "A=B",
  9576. "application/x-www-form-urlencoded\r\nevil: hello1");
  9577. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9578. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9579. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9580. }
  9581. }
  9582. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9583. auto server_thread = std::thread([] {
  9584. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9585. default_socket_options(srv);
  9586. sockaddr_in addr{};
  9587. addr.sin_family = AF_INET;
  9588. addr.sin_port = htons(PORT + 1);
  9589. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9590. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9591. ::listen(srv, 1);
  9592. sockaddr_in cli_addr{};
  9593. socklen_t cli_len = sizeof(cli_addr);
  9594. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9595. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9596. std::string buf_all;
  9597. char buf[2048];
  9598. ssize_t n;
  9599. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9600. buf_all.append(buf, static_cast<size_t>(n));
  9601. size_t pos;
  9602. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9603. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9604. auto e = request_block.find("\r\n");
  9605. if (e != std::string::npos) {
  9606. auto request_line = request_block.substr(0, e);
  9607. std::string msg =
  9608. "CRLF injection detected in request line: '" + request_line + "'";
  9609. EXPECT_FALSE(true) << msg;
  9610. }
  9611. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9612. ::send(cli,
  9613. #ifdef _WIN32
  9614. static_cast<const char *>(resp.c_str()),
  9615. static_cast<int>(resp.size()),
  9616. #else
  9617. resp.c_str(), resp.size(),
  9618. #endif
  9619. 0);
  9620. buf_all.erase(0, pos + 4);
  9621. }
  9622. }
  9623. detail::close_socket(cli);
  9624. detail::close_socket(srv);
  9625. });
  9626. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9627. auto cli = Client("127.0.0.1", PORT + 1);
  9628. auto headers = Headers{
  9629. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9630. {"Connection", "keep-alive"}};
  9631. auto res = cli.Get("/hi", headers);
  9632. EXPECT_FALSE(res);
  9633. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9634. server_thread.join();
  9635. }
  9636. TEST(PathParamsTest, StaticMatch) {
  9637. const auto pattern = "/users/all";
  9638. detail::PathParamsMatcher matcher(pattern);
  9639. Request request;
  9640. request.path = "/users/all";
  9641. ASSERT_TRUE(matcher.match(request));
  9642. std::unordered_map<std::string, std::string> expected_params = {};
  9643. EXPECT_EQ(request.path_params, expected_params);
  9644. }
  9645. TEST(PathParamsTest, StaticMismatch) {
  9646. const auto pattern = "/users/all";
  9647. detail::PathParamsMatcher matcher(pattern);
  9648. Request request;
  9649. request.path = "/users/1";
  9650. ASSERT_FALSE(matcher.match(request));
  9651. }
  9652. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9653. const auto pattern = "/users/:id/subscriptions";
  9654. detail::PathParamsMatcher matcher(pattern);
  9655. Request request;
  9656. request.path = "/users/42/subscriptions";
  9657. ASSERT_TRUE(matcher.match(request));
  9658. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9659. EXPECT_EQ(request.path_params, expected_params);
  9660. }
  9661. TEST(PathParamsTest, SingleParamInTheEnd) {
  9662. const auto pattern = "/users/:id";
  9663. detail::PathParamsMatcher matcher(pattern);
  9664. Request request;
  9665. request.path = "/users/24";
  9666. ASSERT_TRUE(matcher.match(request));
  9667. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9668. EXPECT_EQ(request.path_params, expected_params);
  9669. }
  9670. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9671. const auto pattern = "/users/:id/";
  9672. detail::PathParamsMatcher matcher(pattern);
  9673. Request request;
  9674. request.path = "/users/42/";
  9675. ASSERT_TRUE(matcher.match(request));
  9676. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9677. EXPECT_EQ(request.path_params, expected_params);
  9678. }
  9679. TEST(PathParamsTest, EmptyParam) {
  9680. const auto pattern = "/users/:id/";
  9681. detail::PathParamsMatcher matcher(pattern);
  9682. Request request;
  9683. request.path = "/users//";
  9684. ASSERT_TRUE(matcher.match(request));
  9685. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9686. EXPECT_EQ(request.path_params, expected_params);
  9687. }
  9688. TEST(PathParamsTest, FragmentMismatch) {
  9689. const auto pattern = "/users/:id/";
  9690. detail::PathParamsMatcher matcher(pattern);
  9691. Request request;
  9692. request.path = "/admins/24/";
  9693. ASSERT_FALSE(matcher.match(request));
  9694. }
  9695. TEST(PathParamsTest, ExtraFragments) {
  9696. const auto pattern = "/users/:id";
  9697. detail::PathParamsMatcher matcher(pattern);
  9698. Request request;
  9699. request.path = "/users/42/subscriptions";
  9700. ASSERT_FALSE(matcher.match(request));
  9701. }
  9702. TEST(PathParamsTest, MissingTrailingParam) {
  9703. const auto pattern = "/users/:id";
  9704. detail::PathParamsMatcher matcher(pattern);
  9705. Request request;
  9706. request.path = "/users";
  9707. ASSERT_FALSE(matcher.match(request));
  9708. }
  9709. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9710. const auto pattern = "/users/:id/subscriptions";
  9711. detail::PathParamsMatcher matcher(pattern);
  9712. Request request;
  9713. request.path = "/users/subscriptions";
  9714. ASSERT_FALSE(matcher.match(request));
  9715. }
  9716. TEST(PathParamsTest, MultipleParams) {
  9717. const auto pattern = "/users/:userid/subscriptions/:subid";
  9718. detail::PathParamsMatcher matcher(pattern);
  9719. Request request;
  9720. request.path = "/users/42/subscriptions/2";
  9721. ASSERT_TRUE(matcher.match(request));
  9722. std::unordered_map<std::string, std::string> expected_params = {
  9723. {"userid", "42"}, {"subid", "2"}};
  9724. EXPECT_EQ(request.path_params, expected_params);
  9725. }
  9726. TEST(PathParamsTest, SequenceOfParams) {
  9727. const auto pattern = "/values/:x/:y/:z";
  9728. detail::PathParamsMatcher matcher(pattern);
  9729. Request request;
  9730. request.path = "/values/1/2/3";
  9731. ASSERT_TRUE(matcher.match(request));
  9732. std::unordered_map<std::string, std::string> expected_params = {
  9733. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9734. EXPECT_EQ(request.path_params, expected_params);
  9735. }
  9736. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9737. const auto pattern = "/prefix:suffix";
  9738. detail::PathParamsMatcher matcher(pattern);
  9739. Request request;
  9740. request.path = "/prefix:suffix";
  9741. ASSERT_TRUE(matcher.match(request));
  9742. const std::unordered_map<std::string, std::string> expected_params = {};
  9743. EXPECT_EQ(request.path_params, expected_params);
  9744. }
  9745. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9746. // If ipv6 regex working, regex match codepath is taken.
  9747. // else port will default to 80 in Client impl
  9748. int clientImplMagicPort = 80;
  9749. int port = 4321;
  9750. // above ports must be different to avoid false negative
  9751. EXPECT_NE(clientImplMagicPort, port);
  9752. std::string ipV6TestURL = "http://[ff06::c3]";
  9753. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9754. CLIENT_PRIVATE_KEY_FILE);
  9755. EXPECT_EQ(cli.port(), port);
  9756. }
  9757. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9758. auto file_path = "./www/dir/index.html";
  9759. auto dir_path = "./www/dir";
  9760. detail::FileStat stat_file(file_path);
  9761. EXPECT_TRUE(stat_file.is_file());
  9762. EXPECT_FALSE(stat_file.is_dir());
  9763. detail::FileStat stat_dir(dir_path);
  9764. EXPECT_FALSE(stat_dir.is_file());
  9765. EXPECT_TRUE(stat_dir.is_dir());
  9766. }
  9767. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9768. // IPv4 with default HTTP port (80)
  9769. EXPECT_EQ("example.com",
  9770. detail::make_host_and_port_string("example.com", 80, false));
  9771. // IPv4 with default HTTPS port (443)
  9772. EXPECT_EQ("example.com",
  9773. detail::make_host_and_port_string("example.com", 443, true));
  9774. // IPv4 with non-default HTTP port
  9775. EXPECT_EQ("example.com:8080",
  9776. detail::make_host_and_port_string("example.com", 8080, false));
  9777. // IPv4 with non-default HTTPS port
  9778. EXPECT_EQ("example.com:8443",
  9779. detail::make_host_and_port_string("example.com", 8443, true));
  9780. // IPv6 with default HTTP port (80)
  9781. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9782. // IPv6 with default HTTPS port (443)
  9783. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9784. // IPv6 with non-default HTTP port
  9785. EXPECT_EQ("[::1]:8080",
  9786. detail::make_host_and_port_string("::1", 8080, false));
  9787. // IPv6 with non-default HTTPS port
  9788. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9789. // IPv6 full address with default port
  9790. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9791. detail::make_host_and_port_string(
  9792. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9793. // IPv6 full address with non-default port
  9794. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9795. detail::make_host_and_port_string(
  9796. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9797. // IPv6 localhost with non-default port
  9798. EXPECT_EQ("[::1]:3000",
  9799. detail::make_host_and_port_string("::1", 3000, false));
  9800. // IPv6 with zone ID (link-local address) with default port
  9801. EXPECT_EQ("[fe80::1%eth0]",
  9802. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9803. // IPv6 with zone ID (link-local address) with non-default port
  9804. EXPECT_EQ("[fe80::1%eth0]:8080",
  9805. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9806. // Edge case: Port 443 with is_ssl=false (should add port)
  9807. EXPECT_EQ("example.com:443",
  9808. detail::make_host_and_port_string("example.com", 443, false));
  9809. // Edge case: Port 80 with is_ssl=true (should add port)
  9810. EXPECT_EQ("example.com:80",
  9811. detail::make_host_and_port_string("example.com", 80, true));
  9812. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9813. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9814. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9815. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9816. // Security fix: Already bracketed IPv6 should not get double brackets
  9817. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9818. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9819. EXPECT_EQ("[::1]:8080",
  9820. detail::make_host_and_port_string("[::1]", 8080, false));
  9821. EXPECT_EQ("[2001:db8::1]:8080",
  9822. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9823. EXPECT_EQ("[fe80::1%eth0]",
  9824. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9825. EXPECT_EQ("[fe80::1%eth0]:8080",
  9826. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9827. // Edge case: Empty host (should return as-is)
  9828. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9829. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9830. // This is a known limitation but shouldn't crash
  9831. EXPECT_EQ("[host:name]",
  9832. detail::make_host_and_port_string("host:name", 80, false));
  9833. // Port number edge cases (no validation, but should not crash)
  9834. EXPECT_EQ("example.com:0",
  9835. detail::make_host_and_port_string("example.com", 0, false));
  9836. EXPECT_EQ("example.com:-1",
  9837. detail::make_host_and_port_string("example.com", -1, false));
  9838. EXPECT_EQ("example.com:65535",
  9839. detail::make_host_and_port_string("example.com", 65535, false));
  9840. EXPECT_EQ("example.com:65536",
  9841. detail::make_host_and_port_string("example.com", 65536, false));
  9842. }
  9843. #ifdef CPPHTTPLIB_SSL_ENABLED
  9844. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9845. httplib::SSLClient cli("roblox.com", 443);
  9846. cli.set_follow_location(true);
  9847. auto res = cli.Get("/");
  9848. ASSERT_TRUE(res);
  9849. EXPECT_EQ(StatusCode::OK_200, res->status);
  9850. }
  9851. #endif
  9852. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9853. Server svr;
  9854. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9855. EXPECT_EQ(res.status, 400);
  9856. });
  9857. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. thread.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.wait_until_ready();
  9864. Client cli(HOST, PORT);
  9865. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9866. }
  9867. TEST(InvalidHeaderCharsTest, is_field_name) {
  9868. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9869. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9870. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9871. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9872. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9873. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9874. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9875. EXPECT_FALSE(detail::fields::is_field_name(""));
  9876. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9877. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9878. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9879. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9880. }
  9881. TEST(InvalidHeaderCharsTest, is_field_value) {
  9882. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9883. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9884. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9885. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9886. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9887. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9888. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9889. EXPECT_TRUE(detail::fields::is_field_value(""));
  9890. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9891. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9892. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9893. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9894. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9895. }
  9896. TEST(InvalidHeaderCharsTest, OnServer) {
  9897. Server svr;
  9898. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9899. std::string header = "Not Set";
  9900. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9901. res.set_header(header, "value");
  9902. res.set_content("Page Content Page Content", "text/plain");
  9903. });
  9904. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9905. std::string header = "Not Set";
  9906. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9907. res.set_header("X-Test", header);
  9908. res.set_content("Page Content Page Content", "text/plain");
  9909. });
  9910. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9911. auto se = detail::scope_exit([&] {
  9912. svr.stop();
  9913. thread.join();
  9914. ASSERT_FALSE(svr.is_running());
  9915. });
  9916. svr.wait_until_ready();
  9917. Client cli(HOST, PORT);
  9918. {
  9919. auto res = cli.Get(
  9920. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9921. ASSERT_TRUE(res);
  9922. EXPECT_EQ("Page Content Page Content", res->body);
  9923. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9924. }
  9925. {
  9926. auto res = cli.Get(
  9927. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9928. ASSERT_TRUE(res);
  9929. EXPECT_EQ("Page Content Page Content", res->body);
  9930. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9931. }
  9932. }
  9933. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9934. auto handled = false;
  9935. Server svr;
  9936. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9937. thread t = thread([&] { svr.listen(HOST, PORT); });
  9938. auto se = detail::scope_exit([&] {
  9939. svr.stop();
  9940. t.join();
  9941. ASSERT_FALSE(svr.is_running());
  9942. ASSERT_FALSE(handled);
  9943. });
  9944. svr.wait_until_ready();
  9945. auto req = "POST /test HTTP/1.1\r\n"
  9946. "Content-Length: x\r\n"
  9947. "\r\n";
  9948. std::string response;
  9949. ASSERT_TRUE(send_request(1, req, &response));
  9950. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9951. response.substr(0, response.find("\r\n")));
  9952. }
  9953. #ifndef _WIN32
  9954. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9955. static constexpr char reject[] = "Unauthorized";
  9956. static constexpr char accept[] = "Upload accepted";
  9957. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9958. Server svr;
  9959. svr.set_expect_100_continue_handler(
  9960. [](const Request & /*req*/, Response &res) {
  9961. res.status = StatusCode::Unauthorized_401;
  9962. res.set_content(reject, "text/plain");
  9963. return res.status;
  9964. });
  9965. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9966. res.set_content(accept, "text/plain");
  9967. });
  9968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9969. auto se = detail::scope_exit([&] {
  9970. svr.stop();
  9971. thread.join();
  9972. ASSERT_FALSE(svr.is_running());
  9973. });
  9974. svr.wait_until_ready();
  9975. {
  9976. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9977. curl_easy_init(), &curl_easy_cleanup};
  9978. ASSERT_NE(curl, nullptr);
  9979. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9980. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9981. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9982. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9983. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9984. &curl_slist_free_all};
  9985. ASSERT_NE(list, nullptr);
  9986. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9987. struct read_data {
  9988. size_t read_size;
  9989. size_t total_size;
  9990. } data = {0, total_size};
  9991. using read_callback_t =
  9992. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9993. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9994. void *userdata) -> size_t {
  9995. read_data *data = (read_data *)userdata;
  9996. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9997. std::fill_n(ptr, size * nmemb, 'A');
  9998. data->read_size += size * nmemb;
  9999. return size * nmemb;
  10000. };
  10001. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10002. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10003. std::vector<char> buffer;
  10004. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10005. using write_callback_t =
  10006. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10007. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10008. void *userdata) -> size_t {
  10009. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10010. buffer->reserve(buffer->size() + size * nmemb + 1);
  10011. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10012. return size * nmemb;
  10013. };
  10014. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10015. {
  10016. const auto res = curl_easy_perform(curl.get());
  10017. ASSERT_EQ(res, CURLE_OK);
  10018. }
  10019. {
  10020. auto response_code = long{};
  10021. const auto res =
  10022. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10023. ASSERT_EQ(res, CURLE_OK);
  10024. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10025. }
  10026. {
  10027. auto dl = curl_off_t{};
  10028. const auto res =
  10029. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10030. ASSERT_EQ(res, CURLE_OK);
  10031. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10032. }
  10033. {
  10034. buffer.push_back('\0');
  10035. ASSERT_STRCASEEQ(buffer.data(), reject);
  10036. }
  10037. }
  10038. }
  10039. #endif
  10040. template <typename S, typename C>
  10041. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10042. svr.Get("/stream", [&](const Request &, Response &res) {
  10043. auto data = new std::string("01234567890123456789");
  10044. res.set_content_provider(
  10045. data->size(), "text/plain",
  10046. [&, data](size_t offset, size_t length, DataSink &sink) {
  10047. const size_t DATA_CHUNK_SIZE = 4;
  10048. const auto &d = *data;
  10049. std::this_thread::sleep_for(std::chrono::seconds(1));
  10050. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10051. return true;
  10052. },
  10053. [data](bool success) {
  10054. EXPECT_FALSE(success);
  10055. delete data;
  10056. });
  10057. });
  10058. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10059. auto i = new size_t(0);
  10060. res.set_content_provider(
  10061. "text/plain",
  10062. [i](size_t, DataSink &sink) {
  10063. if (*i < 5) {
  10064. std::this_thread::sleep_for(std::chrono::seconds(1));
  10065. sink.write("abcd", 4);
  10066. (*i)++;
  10067. } else {
  10068. sink.done();
  10069. }
  10070. return true;
  10071. },
  10072. [i](bool success) {
  10073. EXPECT_FALSE(success);
  10074. delete i;
  10075. });
  10076. });
  10077. svr.Get("/chunked", [&](const Request &, Response &res) {
  10078. auto i = new size_t(0);
  10079. res.set_chunked_content_provider(
  10080. "text/plain",
  10081. [i](size_t, DataSink &sink) {
  10082. if (*i < 5) {
  10083. std::this_thread::sleep_for(std::chrono::seconds(1));
  10084. sink.os << "abcd";
  10085. (*i)++;
  10086. } else {
  10087. sink.done();
  10088. }
  10089. return true;
  10090. },
  10091. [i](bool success) {
  10092. EXPECT_FALSE(success);
  10093. delete i;
  10094. });
  10095. });
  10096. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10097. auto se = detail::scope_exit([&] {
  10098. svr.stop();
  10099. listen_thread.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. });
  10102. svr.wait_until_ready();
  10103. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10104. {
  10105. auto start = std::chrono::steady_clock::now();
  10106. auto res = cli.Get("/stream");
  10107. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10108. std::chrono::steady_clock::now() - start)
  10109. .count();
  10110. ASSERT_FALSE(res);
  10111. EXPECT_EQ(Error::Read, res.error());
  10112. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10113. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10114. }
  10115. {
  10116. auto start = std::chrono::steady_clock::now();
  10117. auto res = cli.Get("/stream_without_length");
  10118. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10119. std::chrono::steady_clock::now() - start)
  10120. .count();
  10121. ASSERT_FALSE(res);
  10122. EXPECT_EQ(Error::Read, res.error());
  10123. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10124. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10125. }
  10126. {
  10127. auto start = std::chrono::steady_clock::now();
  10128. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10129. EXPECT_EQ("abcd", string(data, data_length));
  10130. return true;
  10131. });
  10132. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10133. std::chrono::steady_clock::now() - start)
  10134. .count();
  10135. ASSERT_FALSE(res);
  10136. EXPECT_EQ(Error::Read, res.error());
  10137. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10138. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10139. }
  10140. }
  10141. TEST(MaxTimeoutTest, ContentStream) {
  10142. time_t timeout = 2000;
  10143. time_t threshold = 200;
  10144. Server svr;
  10145. Client cli("localhost", PORT);
  10146. max_timeout_test(svr, cli, timeout, threshold);
  10147. }
  10148. #ifdef CPPHTTPLIB_SSL_ENABLED
  10149. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10150. time_t timeout = 2000;
  10151. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10153. SSLClient cli("localhost", PORT);
  10154. cli.enable_server_certificate_verification(false);
  10155. max_timeout_test(svr, cli, timeout, threshold);
  10156. }
  10157. #endif
  10158. class EventDispatcher {
  10159. public:
  10160. EventDispatcher() {}
  10161. bool wait_event(DataSink *sink) {
  10162. unique_lock<mutex> lk(m_);
  10163. int id = id_;
  10164. // Wait with timeout to prevent hanging if client disconnects
  10165. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10166. [&] { return cid_ == id; })) {
  10167. return false; // Timeout occurred
  10168. }
  10169. sink->write(message_.data(), message_.size());
  10170. return true;
  10171. }
  10172. void send_event(const string &message) {
  10173. lock_guard<mutex> lk(m_);
  10174. cid_ = id_++;
  10175. message_ = message;
  10176. cv_.notify_all();
  10177. }
  10178. private:
  10179. mutex m_;
  10180. condition_variable cv_;
  10181. atomic_int id_{0};
  10182. atomic_int cid_{-1};
  10183. string message_;
  10184. };
  10185. TEST(ClientInThreadTest, Issue2068) {
  10186. EventDispatcher ed;
  10187. Server svr;
  10188. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10189. res.set_chunked_content_provider("text/event-stream",
  10190. [&](size_t /*offset*/, DataSink &sink) {
  10191. return ed.wait_event(&sink);
  10192. });
  10193. });
  10194. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10195. svr.wait_until_ready();
  10196. thread event_thread([&] {
  10197. int id = 0;
  10198. while (svr.is_running()) {
  10199. this_thread::sleep_for(chrono::milliseconds(500));
  10200. std::stringstream ss;
  10201. ss << "data: " << id << "\n\n";
  10202. ed.send_event(ss.str());
  10203. id++;
  10204. }
  10205. });
  10206. auto se = detail::scope_exit([&] {
  10207. svr.stop();
  10208. listen_thread.join();
  10209. event_thread.join();
  10210. ASSERT_FALSE(svr.is_running());
  10211. });
  10212. {
  10213. auto client = detail::make_unique<Client>(HOST, PORT);
  10214. client->set_read_timeout(std::chrono::minutes(10));
  10215. std::atomic<bool> stop{false};
  10216. std::thread t([&] {
  10217. client->Get("/event1",
  10218. [&](const char *, size_t) -> bool { return !stop; });
  10219. });
  10220. std::this_thread::sleep_for(std::chrono::seconds(2));
  10221. stop = true;
  10222. client->stop();
  10223. t.join();
  10224. // Reset client after thread has finished
  10225. client.reset();
  10226. }
  10227. }
  10228. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10229. Server svr;
  10230. svr.Get("/", [](const Request &req, Response &res) {
  10231. EXPECT_EQ(2U, req.trailers.size());
  10232. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10233. // Denied
  10234. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10235. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10236. // Accepted
  10237. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10238. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10239. EXPECT_TRUE(req.has_trailer("X-World"));
  10240. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10241. res.set_content("ok", "text/plain");
  10242. });
  10243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. t.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. });
  10249. svr.wait_until_ready();
  10250. const std::string req = "GET / HTTP/1.1\r\n"
  10251. "Transfer-Encoding: chunked\r\n"
  10252. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10253. "\r\n"
  10254. "0\r\n"
  10255. "Content-Length: 10\r\n"
  10256. "Host: internal.local\r\n"
  10257. "Content-Type: malicious/content\r\n"
  10258. "Cookie: any\r\n"
  10259. "Set-Cookie: any\r\n"
  10260. "X-Forwarded-For: attacker.com\r\n"
  10261. "X-Real-Ip: 1.1.1.1\r\n"
  10262. "X-Hello: hello\r\n"
  10263. "X-World: world\r\n"
  10264. "\r\n";
  10265. std::string res;
  10266. ASSERT_TRUE(send_request(1, req, &res));
  10267. }
  10268. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10269. Server svr;
  10270. std::string observed_remote_addr;
  10271. std::string observed_xff;
  10272. svr.Get("/ip", [&](const Request &req, Response &res) {
  10273. observed_remote_addr = req.remote_addr;
  10274. observed_xff = req.get_header_value("X-Forwarded-For");
  10275. res.set_content("ok", "text/plain");
  10276. });
  10277. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10278. auto se = detail::scope_exit([&] {
  10279. svr.stop();
  10280. t.join();
  10281. ASSERT_FALSE(svr.is_running());
  10282. });
  10283. svr.wait_until_ready();
  10284. Client cli(HOST, PORT);
  10285. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10286. ASSERT_TRUE(res);
  10287. EXPECT_EQ(StatusCode::OK_200, res->status);
  10288. EXPECT_EQ(observed_xff, "203.0.113.66");
  10289. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10290. observed_remote_addr == "127.0.0.1");
  10291. }
  10292. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10293. Server svr;
  10294. svr.set_trusted_proxies({"203.0.113.66"});
  10295. std::string observed_remote_addr;
  10296. std::string observed_xff;
  10297. svr.Get("/ip", [&](const Request &req, Response &res) {
  10298. observed_remote_addr = req.remote_addr;
  10299. observed_xff = req.get_header_value("X-Forwarded-For");
  10300. res.set_content("ok", "text/plain");
  10301. });
  10302. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. t.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. Client cli(HOST, PORT);
  10310. auto res = cli.Get("/ip");
  10311. ASSERT_TRUE(res);
  10312. EXPECT_EQ(StatusCode::OK_200, res->status);
  10313. EXPECT_EQ(observed_xff, "");
  10314. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10315. observed_remote_addr == "127.0.0.1");
  10316. }
  10317. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10318. Server svr;
  10319. svr.set_trusted_proxies({"203.0.113.66"});
  10320. std::string observed_remote_addr;
  10321. std::string observed_xff;
  10322. svr.Get("/ip", [&](const Request &req, Response &res) {
  10323. observed_remote_addr = req.remote_addr;
  10324. observed_xff = req.get_header_value("X-Forwarded-For");
  10325. res.set_content("ok", "text/plain");
  10326. });
  10327. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10328. auto se = detail::scope_exit([&] {
  10329. svr.stop();
  10330. t.join();
  10331. ASSERT_FALSE(svr.is_running());
  10332. });
  10333. svr.wait_until_ready();
  10334. Client cli(HOST, PORT);
  10335. auto res =
  10336. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10337. ASSERT_TRUE(res);
  10338. EXPECT_EQ(StatusCode::OK_200, res->status);
  10339. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10340. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10341. }
  10342. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10343. Server svr;
  10344. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10345. std::string observed_remote_addr;
  10346. std::string observed_xff;
  10347. svr.Get("/ip", [&](const Request &req, Response &res) {
  10348. observed_remote_addr = req.remote_addr;
  10349. observed_xff = req.get_header_value("X-Forwarded-For");
  10350. res.set_content("ok", "text/plain");
  10351. });
  10352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10353. auto se = detail::scope_exit([&] {
  10354. svr.stop();
  10355. t.join();
  10356. ASSERT_FALSE(svr.is_running());
  10357. });
  10358. svr.wait_until_ready();
  10359. Client cli(HOST, PORT);
  10360. auto res = cli.Get(
  10361. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10362. ASSERT_TRUE(res);
  10363. EXPECT_EQ(StatusCode::OK_200, res->status);
  10364. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10365. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10366. }
  10367. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10368. Server svr;
  10369. svr.set_trusted_proxies({"192.0.2.45"});
  10370. std::string observed_remote_addr;
  10371. std::string observed_xff;
  10372. svr.Get("/ip", [&](const Request &req, Response &res) {
  10373. observed_remote_addr = req.remote_addr;
  10374. observed_xff = req.get_header_value("X-Forwarded-For");
  10375. res.set_content("ok", "text/plain");
  10376. });
  10377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. ASSERT_FALSE(svr.is_running());
  10382. });
  10383. svr.wait_until_ready();
  10384. Client cli(HOST, PORT);
  10385. auto res =
  10386. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10387. ASSERT_TRUE(res);
  10388. EXPECT_EQ(StatusCode::OK_200, res->status);
  10389. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10390. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10391. }
  10392. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10393. Server svr;
  10394. svr.set_trusted_proxies({"192.0.2.45"});
  10395. std::string observed_remote_addr;
  10396. std::string observed_xff;
  10397. svr.Get("/ip", [&](const Request &req, Response &res) {
  10398. observed_remote_addr = req.remote_addr;
  10399. observed_xff = req.get_header_value("X-Forwarded-For");
  10400. res.set_content("ok", "text/plain");
  10401. });
  10402. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10403. auto se = detail::scope_exit([&] {
  10404. svr.stop();
  10405. t.join();
  10406. ASSERT_FALSE(svr.is_running());
  10407. });
  10408. svr.wait_until_ready();
  10409. Client cli(HOST, PORT);
  10410. auto res = cli.Get(
  10411. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10412. ASSERT_TRUE(res);
  10413. EXPECT_EQ(StatusCode::OK_200, res->status);
  10414. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10415. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10416. }
  10417. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10418. Server svr;
  10419. svr.set_trusted_proxies({"192.0.2.45"});
  10420. std::string observed_remote_addr;
  10421. std::string observed_xff;
  10422. svr.Get("/ip", [&](const Request &req, Response &res) {
  10423. observed_remote_addr = req.remote_addr;
  10424. observed_xff = req.get_header_value("X-Forwarded-For");
  10425. res.set_content("ok", "text/plain");
  10426. });
  10427. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10428. auto se = detail::scope_exit([&] {
  10429. svr.stop();
  10430. t.join();
  10431. ASSERT_FALSE(svr.is_running());
  10432. });
  10433. svr.wait_until_ready();
  10434. std::string raw_req =
  10435. "GET /ip HTTP/1.1\r\n"
  10436. "Host: localhost\r\n"
  10437. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10438. "Connection: close\r\n"
  10439. "\r\n";
  10440. std::string out;
  10441. ASSERT_TRUE(send_request(5, raw_req, &out));
  10442. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10443. // Header parser trims surrounding whitespace of the header value
  10444. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10445. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10446. }
  10447. #ifndef _WIN32
  10448. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10449. Server svr;
  10450. svr.Post("/post", [&](const Request &req, Response &res) {
  10451. res.set_content(req.body, "text/plain");
  10452. });
  10453. svr.Put("/put", [&](const Request &req, Response &res) {
  10454. res.set_content(req.body, "text/plain");
  10455. });
  10456. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10457. res.set_content(req.body, "text/plain");
  10458. });
  10459. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10460. res.set_content(req.body, "text/plain");
  10461. });
  10462. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. t.join();
  10466. ASSERT_FALSE(svr.is_running());
  10467. });
  10468. svr.wait_until_ready();
  10469. std::string resp;
  10470. // POST without Content-Length
  10471. ASSERT_TRUE(send_request(5,
  10472. "POST /post HTTP/1.1\r\n"
  10473. "Host: localhost\r\n"
  10474. "Connection: close\r\n"
  10475. "\r\n",
  10476. &resp));
  10477. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10478. // PUT without Content-Length
  10479. resp.clear();
  10480. ASSERT_TRUE(send_request(5,
  10481. "PUT /put HTTP/1.1\r\n"
  10482. "Host: localhost\r\n"
  10483. "Connection: close\r\n"
  10484. "\r\n",
  10485. &resp));
  10486. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10487. // PATCH without Content-Length
  10488. resp.clear();
  10489. ASSERT_TRUE(send_request(5,
  10490. "PATCH /patch HTTP/1.1\r\n"
  10491. "Host: localhost\r\n"
  10492. "Connection: close\r\n"
  10493. "\r\n",
  10494. &resp));
  10495. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10496. // DELETE without Content-Length
  10497. resp.clear();
  10498. ASSERT_TRUE(send_request(5,
  10499. "DELETE /delete HTTP/1.1\r\n"
  10500. "Host: localhost\r\n"
  10501. "Connection: close\r\n"
  10502. "\r\n",
  10503. &resp));
  10504. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10505. }
  10506. #endif
  10507. //==============================================================================
  10508. // open_stream() Tests
  10509. //==============================================================================
  10510. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10511. std::string result;
  10512. char buf[8192];
  10513. ssize_t n;
  10514. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10515. result.append(buf, static_cast<size_t>(n));
  10516. }
  10517. return result;
  10518. }
  10519. // Mock stream for unit tests
  10520. class MockStream : public Stream {
  10521. public:
  10522. std::string data;
  10523. size_t pos = 0;
  10524. ssize_t error_after = -1; // -1 = no error
  10525. explicit MockStream(const std::string &d, ssize_t err = -1)
  10526. : data(d), error_after(err) {}
  10527. bool is_readable() const override { return true; }
  10528. bool wait_readable() const override { return true; }
  10529. bool wait_writable() const override { return true; }
  10530. ssize_t read(char *ptr, size_t size) override {
  10531. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10532. if (pos >= data.size()) return 0;
  10533. size_t limit =
  10534. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10535. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10536. std::memcpy(ptr, data.data() + pos, to_read);
  10537. pos += to_read;
  10538. return static_cast<ssize_t>(to_read);
  10539. }
  10540. ssize_t write(const char *, size_t) override { return -1; }
  10541. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10542. ip = "127.0.0.1";
  10543. port = 0;
  10544. }
  10545. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10546. ip = "127.0.0.1";
  10547. port = 0;
  10548. }
  10549. socket_t socket() const override { return INVALID_SOCKET; }
  10550. time_t duration() const override { return 0; }
  10551. };
  10552. TEST(StreamHandleTest, Basic) {
  10553. ClientImpl::StreamHandle handle;
  10554. EXPECT_FALSE(handle.is_valid());
  10555. handle.response = detail::make_unique<Response>();
  10556. handle.error = Error::Connection;
  10557. EXPECT_FALSE(handle.is_valid());
  10558. handle.error = Error::Success;
  10559. EXPECT_TRUE(handle.is_valid());
  10560. }
  10561. TEST(BodyReaderTest, Basic) {
  10562. MockStream stream("Hello, World!");
  10563. detail::BodyReader reader;
  10564. reader.stream = &stream;
  10565. reader.content_length = 13;
  10566. char buf[32];
  10567. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10568. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10569. EXPECT_TRUE(reader.eof);
  10570. }
  10571. TEST(BodyReaderTest, NoStream) {
  10572. detail::BodyReader reader;
  10573. char buf[32];
  10574. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10575. EXPECT_EQ(Error::Connection, reader.last_error);
  10576. }
  10577. TEST(BodyReaderTest, Error) {
  10578. MockStream stream("Hello, World!", 5);
  10579. detail::BodyReader reader;
  10580. reader.stream = &stream;
  10581. reader.content_length = 13;
  10582. char buf[32];
  10583. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10584. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10585. EXPECT_EQ(Error::Read, reader.last_error);
  10586. }
  10587. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10588. // Mock-based StreamHandle tests relying on private internals are removed.
  10589. class OpenStreamTest : public ::testing::Test {
  10590. protected:
  10591. void SetUp() override {
  10592. svr_.Get("/hello", [](const Request &, Response &res) {
  10593. res.set_content("Hello World!", "text/plain");
  10594. });
  10595. svr_.Get("/large", [](const Request &, Response &res) {
  10596. res.set_content(std::string(10000, 'X'), "text/plain");
  10597. });
  10598. svr_.Get("/chunked", [](const Request &, Response &res) {
  10599. res.set_chunked_content_provider("text/plain",
  10600. [](size_t offset, DataSink &sink) {
  10601. if (offset < 15) {
  10602. sink.write("chunk", 5);
  10603. return true;
  10604. }
  10605. sink.done();
  10606. return true;
  10607. });
  10608. });
  10609. svr_.Get("/compressible", [](const Request &, Response &res) {
  10610. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10611. DataSink &sink) {
  10612. if (offset < 100 * 1024) {
  10613. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10614. sink.write(chunk.data(), chunk.size());
  10615. return true;
  10616. }
  10617. sink.done();
  10618. return true;
  10619. });
  10620. });
  10621. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10622. [](const Request & /*req*/, Response &res) {
  10623. auto i = new int(0);
  10624. res.set_header("Trailer", "Content-Length, X-Allowed");
  10625. res.set_chunked_content_provider(
  10626. "text/plain",
  10627. [i](size_t /*offset*/, DataSink &sink) {
  10628. switch (*i) {
  10629. case 0: sink.os << "123"; break;
  10630. case 1: sink.os << "456"; break;
  10631. case 2: sink.os << "789"; break;
  10632. case 3: {
  10633. sink.done_with_trailer(
  10634. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10635. } break;
  10636. }
  10637. (*i)++;
  10638. return true;
  10639. },
  10640. [i](bool success) {
  10641. EXPECT_TRUE(success);
  10642. delete i;
  10643. });
  10644. });
  10645. // Echo headers endpoint for header-related tests
  10646. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10647. std::string body;
  10648. for (const auto &h : req.headers) {
  10649. body.append(h.first);
  10650. body.push_back(':');
  10651. body.append(h.second);
  10652. body.push_back('\n');
  10653. }
  10654. res.set_content(body, "text/plain");
  10655. });
  10656. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10657. std::string body;
  10658. for (const auto &h : req.headers) {
  10659. body.append(h.first);
  10660. body.push_back(':');
  10661. body.append(h.second);
  10662. body.push_back('\n');
  10663. }
  10664. res.set_content(body, "text/plain");
  10665. });
  10666. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10667. svr_.wait_until_ready();
  10668. }
  10669. void TearDown() override {
  10670. svr_.stop();
  10671. if (thread_.joinable()) thread_.join();
  10672. }
  10673. Server svr_;
  10674. std::thread thread_;
  10675. };
  10676. TEST_F(OpenStreamTest, Basic) {
  10677. Client cli("127.0.0.1", 8787);
  10678. auto handle = cli.open_stream("GET", "/hello");
  10679. EXPECT_TRUE(handle.is_valid());
  10680. EXPECT_EQ("Hello World!", read_all(handle));
  10681. }
  10682. TEST_F(OpenStreamTest, SmallBuffer) {
  10683. Client cli("127.0.0.1", 8787);
  10684. auto handle = cli.open_stream("GET", "/hello");
  10685. std::string result;
  10686. char buf[4];
  10687. ssize_t n;
  10688. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10689. result.append(buf, static_cast<size_t>(n));
  10690. EXPECT_EQ("Hello World!", result);
  10691. }
  10692. TEST_F(OpenStreamTest, DefaultHeaders) {
  10693. Client cli("127.0.0.1", 8787);
  10694. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10695. {
  10696. auto handle = cli.open_stream("GET", "/echo-headers");
  10697. ASSERT_TRUE(handle.is_valid());
  10698. auto body = read_all(handle);
  10699. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10700. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10701. std::string::npos);
  10702. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10703. }
  10704. // open_stream POST with body and no explicit content_type should NOT add
  10705. // text/plain Content-Type (behavior differs from non-streaming path), but
  10706. // should include Content-Length
  10707. {
  10708. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10709. ASSERT_TRUE(handle.is_valid());
  10710. auto body = read_all(handle);
  10711. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10712. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10713. }
  10714. // open_stream POST with explicit Content-Type should preserve it
  10715. {
  10716. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10717. {{"Content-Type", "application/custom"}},
  10718. "{}", "application/custom");
  10719. ASSERT_TRUE(handle.is_valid());
  10720. auto body = read_all(handle);
  10721. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10722. }
  10723. // User-specified User-Agent must not be overwritten for stream API
  10724. {
  10725. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10726. {{"User-Agent", "MyAgent/1.2"}});
  10727. ASSERT_TRUE(handle.is_valid());
  10728. auto body = read_all(handle);
  10729. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10730. }
  10731. }
  10732. TEST_F(OpenStreamTest, Large) {
  10733. Client cli("127.0.0.1", 8787);
  10734. auto handle = cli.open_stream("GET", "/large");
  10735. EXPECT_EQ(10000u, read_all(handle).size());
  10736. }
  10737. TEST_F(OpenStreamTest, ConnectionError) {
  10738. Client cli("127.0.0.1", 9999);
  10739. auto handle = cli.open_stream("GET", "/hello");
  10740. EXPECT_FALSE(handle.is_valid());
  10741. }
  10742. TEST_F(OpenStreamTest, Chunked) {
  10743. Client cli("127.0.0.1", 8787);
  10744. auto handle = cli.open_stream("GET", "/chunked");
  10745. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10746. "Transfer-Encoding") == "chunked");
  10747. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10748. }
  10749. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10750. Client cli("127.0.0.1", 8787);
  10751. auto handle =
  10752. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10753. ASSERT_TRUE(handle.is_valid());
  10754. // Consume body to allow trailers to be received/parsed
  10755. auto body = read_all(handle);
  10756. // Explicitly parse trailers (ensure trailers are available for assertion)
  10757. handle.parse_trailers_if_needed();
  10758. EXPECT_EQ(std::string("123456789"), body);
  10759. // The response should include a Trailer header declaring both names
  10760. ASSERT_TRUE(handle.response);
  10761. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10762. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10763. handle.response->get_header_value("Trailer"));
  10764. // Prohibited trailer must not be present
  10765. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10766. // Allowed trailer should be present
  10767. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10768. EXPECT_EQ(std::string("yes"),
  10769. handle.response->get_trailer_value("X-Allowed"));
  10770. // Verify trailers are NOT present as regular headers
  10771. EXPECT_EQ(std::string(""),
  10772. handle.response->get_header_value("Content-Length"));
  10773. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10774. }
  10775. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10776. TEST_F(OpenStreamTest, Gzip) {
  10777. Client cli("127.0.0.1", 8787);
  10778. auto handle = cli.open_stream("GET", "/compressible", {},
  10779. {{"Accept-Encoding", "gzip"}});
  10780. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10781. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10782. }
  10783. #endif
  10784. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10785. TEST_F(OpenStreamTest, Brotli) {
  10786. Client cli("127.0.0.1", 8787);
  10787. auto handle =
  10788. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10789. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10790. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10791. }
  10792. #endif
  10793. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10794. TEST_F(OpenStreamTest, Zstd) {
  10795. Client cli("127.0.0.1", 8787);
  10796. auto handle = cli.open_stream("GET", "/compressible", {},
  10797. {{"Accept-Encoding", "zstd"}});
  10798. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10799. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10800. }
  10801. #endif
  10802. #ifdef CPPHTTPLIB_SSL_ENABLED
  10803. class SSLOpenStreamTest : public ::testing::Test {
  10804. protected:
  10805. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10806. void SetUp() override {
  10807. svr_.Get("/hello", [](const Request &, Response &res) {
  10808. res.set_content("Hello SSL World!", "text/plain");
  10809. });
  10810. svr_.Get("/chunked", [](const Request &, Response &res) {
  10811. res.set_chunked_content_provider("text/plain",
  10812. [](size_t offset, DataSink &sink) {
  10813. if (offset < 15) {
  10814. sink.write("chunk", 5);
  10815. return true;
  10816. }
  10817. sink.done();
  10818. return true;
  10819. });
  10820. });
  10821. svr_.Post("/echo", [](const Request &req, Response &res) {
  10822. res.set_content(req.body, req.get_header_value("Content-Type"));
  10823. });
  10824. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10825. std::string body = req.body;
  10826. res.set_chunked_content_provider(
  10827. "text/plain", [body](size_t offset, DataSink &sink) {
  10828. if (offset < body.size()) {
  10829. sink.write(body.data() + offset, body.size() - offset);
  10830. }
  10831. sink.done();
  10832. return true;
  10833. });
  10834. });
  10835. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10836. svr_.wait_until_ready();
  10837. }
  10838. void TearDown() override {
  10839. svr_.stop();
  10840. if (thread_.joinable()) thread_.join();
  10841. }
  10842. SSLServer svr_;
  10843. std::thread thread_;
  10844. };
  10845. TEST_F(SSLOpenStreamTest, Basic) {
  10846. SSLClient cli("127.0.0.1", 8788);
  10847. cli.enable_server_certificate_verification(false);
  10848. auto handle = cli.open_stream("GET", "/hello");
  10849. ASSERT_TRUE(handle.is_valid());
  10850. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10851. }
  10852. TEST_F(SSLOpenStreamTest, Chunked) {
  10853. SSLClient cli("127.0.0.1", 8788);
  10854. cli.enable_server_certificate_verification(false);
  10855. auto handle = cli.open_stream("GET", "/chunked");
  10856. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10857. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10858. "Transfer-Encoding") == "chunked");
  10859. auto body = read_all(handle);
  10860. EXPECT_EQ("chunkchunkchunk", body);
  10861. }
  10862. TEST_F(SSLOpenStreamTest, Post) {
  10863. SSLClient cli("127.0.0.1", 8788);
  10864. cli.enable_server_certificate_verification(false);
  10865. auto handle =
  10866. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10867. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10868. EXPECT_EQ(200, handle.response->status);
  10869. auto body = read_all(handle);
  10870. EXPECT_EQ("Hello SSL POST", body);
  10871. }
  10872. TEST_F(SSLOpenStreamTest, PostChunked) {
  10873. SSLClient cli("127.0.0.1", 8788);
  10874. cli.enable_server_certificate_verification(false);
  10875. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10876. "Chunked SSL Data", "text/plain");
  10877. ASSERT_TRUE(handle.is_valid());
  10878. EXPECT_EQ(200, handle.response->status);
  10879. auto body = read_all(handle);
  10880. EXPECT_EQ("Chunked SSL Data", body);
  10881. }
  10882. #endif // CPPHTTPLIB_SSL_ENABLED
  10883. //==============================================================================
  10884. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10885. // results for various scenarios.
  10886. //==============================================================================
  10887. TEST(ParityTest, GetVsOpenStream) {
  10888. Server svr;
  10889. const std::string path = "/parity";
  10890. const std::string content = "Parity test content: hello world";
  10891. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10892. res.set_content(content, "text/plain");
  10893. });
  10894. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10895. auto se = detail::scope_exit([&] {
  10896. svr.stop();
  10897. t.join();
  10898. ASSERT_FALSE(svr.is_running());
  10899. });
  10900. svr.wait_until_ready();
  10901. Client cli(HOST, PORT);
  10902. // Non-stream path
  10903. auto r1 = cli.Get(path);
  10904. ASSERT_TRUE(r1);
  10905. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10906. // Stream path
  10907. auto h = cli.open_stream("GET", path);
  10908. ASSERT_TRUE(h.is_valid());
  10909. EXPECT_EQ(r1->body, read_all(h));
  10910. }
  10911. // Helper to compress data with provided compressor type T
  10912. template <typename Compressor>
  10913. static std::string compress_payload_for_parity(const std::string &in) {
  10914. std::string out;
  10915. Compressor compressor;
  10916. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10917. [&](const char *data, size_t n) {
  10918. out.append(data, n);
  10919. return true;
  10920. });
  10921. EXPECT_TRUE(ok);
  10922. return out;
  10923. }
  10924. // Helper function for compression parity tests
  10925. template <typename Compressor>
  10926. static void test_compression_parity(const std::string &original,
  10927. const std::string &path,
  10928. const std::string &encoding) {
  10929. const std::string compressed =
  10930. compress_payload_for_parity<Compressor>(original);
  10931. Server svr;
  10932. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10933. res.set_content(compressed, "application/octet-stream");
  10934. res.set_header("Content-Encoding", encoding);
  10935. });
  10936. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10937. auto se = detail::scope_exit([&] {
  10938. svr.stop();
  10939. t.join();
  10940. ASSERT_FALSE(svr.is_running());
  10941. });
  10942. svr.wait_until_ready();
  10943. Client cli(HOST, PORT);
  10944. // Non-streaming
  10945. {
  10946. auto res = cli.Get(path);
  10947. ASSERT_TRUE(res);
  10948. EXPECT_EQ(StatusCode::OK_200, res->status);
  10949. EXPECT_EQ(original, res->body);
  10950. }
  10951. // Streaming
  10952. {
  10953. auto h = cli.open_stream("GET", path);
  10954. ASSERT_TRUE(h.is_valid());
  10955. EXPECT_EQ(original, read_all(h));
  10956. }
  10957. }
  10958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10959. TEST(ParityTest, Gzip) {
  10960. test_compression_parity<detail::gzip_compressor>(
  10961. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10962. }
  10963. #endif
  10964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10965. TEST(ParityTest, Brotli) {
  10966. test_compression_parity<detail::brotli_compressor>(
  10967. "Hello, brotli parity test payload", "/parity-br", "br");
  10968. }
  10969. #endif
  10970. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10971. TEST(ParityTest, Zstd) {
  10972. test_compression_parity<detail::zstd_compressor>(
  10973. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10974. }
  10975. #endif
  10976. //==============================================================================
  10977. // New Stream API Tests
  10978. //==============================================================================
  10979. inline std::string read_body(httplib::stream::Result &result) {
  10980. std::string body;
  10981. while (result.next()) {
  10982. body.append(result.data(), result.size());
  10983. }
  10984. return body;
  10985. }
  10986. TEST(ClientConnectionTest, Basic) {
  10987. httplib::ClientConnection conn;
  10988. EXPECT_FALSE(conn.is_open());
  10989. conn.sock = 1;
  10990. EXPECT_TRUE(conn.is_open());
  10991. httplib::ClientConnection conn2(std::move(conn));
  10992. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10993. conn2.sock = INVALID_SOCKET;
  10994. }
  10995. // Unified test server for all stream::* tests
  10996. class StreamApiTest : public ::testing::Test {
  10997. protected:
  10998. void SetUp() override {
  10999. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11000. res.set_content("Hello World!", "text/plain");
  11001. });
  11002. svr_.Get("/echo-params",
  11003. [](const httplib::Request &req, httplib::Response &res) {
  11004. std::string r;
  11005. for (const auto &p : req.params) {
  11006. if (!r.empty()) r += "&";
  11007. r += p.first + "=" + p.second;
  11008. }
  11009. res.set_content(r, "text/plain");
  11010. });
  11011. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11012. res.set_content(req.body, req.get_header_value("Content-Type"));
  11013. });
  11014. svr_.Post("/echo-headers",
  11015. [](const httplib::Request &req, httplib::Response &res) {
  11016. std::string r;
  11017. for (const auto &h : req.headers)
  11018. r += h.first + ": " + h.second + "\n";
  11019. res.set_content(r, "text/plain");
  11020. });
  11021. svr_.Post("/echo-params",
  11022. [](const httplib::Request &req, httplib::Response &res) {
  11023. std::string r = "params:";
  11024. for (const auto &p : req.params)
  11025. r += p.first + "=" + p.second + ";";
  11026. res.set_content(r + " body:" + req.body, "text/plain");
  11027. });
  11028. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11029. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11030. });
  11031. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11032. res.set_content("PUT:" + req.body, "text/plain");
  11033. });
  11034. svr_.Patch("/echo",
  11035. [](const httplib::Request &req, httplib::Response &res) {
  11036. res.set_content("PATCH:" + req.body, "text/plain");
  11037. });
  11038. svr_.Delete(
  11039. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11040. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11041. "text/plain");
  11042. });
  11043. svr_.Get("/head-test",
  11044. [](const httplib::Request &, httplib::Response &res) {
  11045. res.set_content("body for HEAD", "text/plain");
  11046. });
  11047. svr_.Options("/options",
  11048. [](const httplib::Request &, httplib::Response &res) {
  11049. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11050. });
  11051. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11052. svr_.wait_until_ready();
  11053. }
  11054. void TearDown() override {
  11055. svr_.stop();
  11056. if (thread_.joinable()) thread_.join();
  11057. }
  11058. httplib::Server svr_;
  11059. std::thread thread_;
  11060. };
  11061. // stream::Get tests
  11062. TEST_F(StreamApiTest, GetBasic) {
  11063. httplib::Client cli(HOST, PORT);
  11064. auto result = httplib::stream::Get(cli, "/hello");
  11065. ASSERT_TRUE(result.is_valid());
  11066. EXPECT_EQ(200, result.status());
  11067. EXPECT_EQ("Hello World!", read_body(result));
  11068. }
  11069. TEST_F(StreamApiTest, GetWithParams) {
  11070. httplib::Client cli(HOST, PORT);
  11071. httplib::Params params{{"foo", "bar"}};
  11072. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11073. ASSERT_TRUE(result.is_valid());
  11074. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11075. }
  11076. TEST_F(StreamApiTest, GetConnectionError) {
  11077. httplib::Client cli(HOST, 9999);
  11078. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11079. }
  11080. TEST_F(StreamApiTest, Get404) {
  11081. httplib::Client cli(HOST, PORT);
  11082. auto result = httplib::stream::Get(cli, "/nonexistent");
  11083. EXPECT_TRUE(result.is_valid());
  11084. EXPECT_EQ(404, result.status());
  11085. }
  11086. // stream::Post tests
  11087. TEST_F(StreamApiTest, PostBasic) {
  11088. httplib::Client cli(HOST, PORT);
  11089. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11090. "application/json");
  11091. ASSERT_TRUE(result.is_valid());
  11092. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11093. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11094. }
  11095. TEST_F(StreamApiTest, PostWithHeaders) {
  11096. httplib::Client cli(HOST, PORT);
  11097. httplib::Headers headers{{"X-Custom", "value"}};
  11098. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11099. "text/plain");
  11100. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11101. }
  11102. TEST_F(StreamApiTest, PostWithParams) {
  11103. httplib::Client cli(HOST, PORT);
  11104. httplib::Params params{{"k", "v"}};
  11105. auto result =
  11106. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11107. auto body = read_body(result);
  11108. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11109. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11110. }
  11111. TEST_F(StreamApiTest, PostLarge) {
  11112. httplib::Client cli(HOST, PORT);
  11113. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11114. size_t total = 0;
  11115. while (result.next()) {
  11116. total += result.size();
  11117. }
  11118. EXPECT_EQ(100u * 1024u, total);
  11119. }
  11120. // stream::Put/Patch tests
  11121. TEST_F(StreamApiTest, PutAndPatch) {
  11122. httplib::Client cli(HOST, PORT);
  11123. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11124. EXPECT_EQ("PUT:test", read_body(put));
  11125. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11126. EXPECT_EQ("PATCH:test", read_body(patch));
  11127. }
  11128. // stream::Delete tests
  11129. TEST_F(StreamApiTest, Delete) {
  11130. httplib::Client cli(HOST, PORT);
  11131. auto del1 = httplib::stream::Delete(cli, "/resource");
  11132. EXPECT_EQ("Deleted", read_body(del1));
  11133. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11134. EXPECT_EQ("Deleted:data", read_body(del2));
  11135. }
  11136. // stream::Head/Options tests
  11137. TEST_F(StreamApiTest, HeadAndOptions) {
  11138. httplib::Client cli(HOST, PORT);
  11139. auto head = httplib::stream::Head(cli, "/head-test");
  11140. EXPECT_TRUE(head.is_valid());
  11141. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11142. auto opts = httplib::stream::Options(cli, "/options");
  11143. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11144. }
  11145. // SSL stream::* tests
  11146. #ifdef CPPHTTPLIB_SSL_ENABLED
  11147. class SSLStreamApiTest : public ::testing::Test {
  11148. protected:
  11149. void SetUp() override {
  11150. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11151. res.set_content("Hello SSL!", "text/plain");
  11152. });
  11153. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11154. res.set_content(req.body, "text/plain");
  11155. });
  11156. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  11157. svr_.wait_until_ready();
  11158. }
  11159. void TearDown() override {
  11160. svr_.stop();
  11161. if (thread_.joinable()) thread_.join();
  11162. }
  11163. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11164. std::thread thread_;
  11165. };
  11166. TEST_F(SSLStreamApiTest, GetAndPost) {
  11167. httplib::SSLClient cli("127.0.0.1", 8803);
  11168. cli.enable_server_certificate_verification(false);
  11169. auto get = httplib::stream::Get(cli, "/hello");
  11170. EXPECT_EQ("Hello SSL!", read_body(get));
  11171. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11172. EXPECT_EQ("test", read_body(post));
  11173. }
  11174. #endif
  11175. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11176. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11177. // BodyReader
  11178. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11179. // Test that read timeout during streaming is detected
  11180. // Use a large content-length response where server delays mid-stream
  11181. Server svr;
  11182. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11183. // Send a large response with delay in the middle
  11184. res.set_content_provider(
  11185. 1000, // content_length
  11186. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11187. if (offset < 100) {
  11188. // Send first 100 bytes immediately
  11189. std::string data(100, 'A');
  11190. sink.write(data.c_str(), data.size());
  11191. return true;
  11192. }
  11193. // Then delay longer than client timeout
  11194. std::this_thread::sleep_for(std::chrono::seconds(3));
  11195. std::string data(900, 'B');
  11196. sink.write(data.c_str(), data.size());
  11197. return true;
  11198. });
  11199. });
  11200. auto port = 8091;
  11201. std::thread t([&]() { svr.listen("localhost", port); });
  11202. svr.wait_until_ready();
  11203. Client cli("localhost", port);
  11204. cli.set_read_timeout(1, 0); // 1 second timeout
  11205. auto handle = cli.open_stream("GET", "/slow-stream");
  11206. ASSERT_TRUE(handle.is_valid());
  11207. char buf[256];
  11208. ssize_t total = 0;
  11209. ssize_t n;
  11210. bool got_error = false;
  11211. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11212. total += n;
  11213. }
  11214. if (n < 0) {
  11215. got_error = true;
  11216. // Should be timeout or read error
  11217. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11218. handle.get_read_error() == Error::Read)
  11219. << "Actual error: " << to_string(handle.get_read_error());
  11220. }
  11221. // Either we got an error, or we got less data than expected
  11222. EXPECT_TRUE(got_error || total < 1000)
  11223. << "Expected timeout but got all " << total << " bytes";
  11224. svr.stop();
  11225. t.join();
  11226. }
  11227. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11228. // Test connection closed detection via BodyReader
  11229. Server svr;
  11230. std::atomic<bool> close_now{false};
  11231. svr.Get("/will-close", [&](const Request &, Response &res) {
  11232. res.set_content_provider(
  11233. 10000, // Large content_length that we won't fully send
  11234. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11235. if (offset < 100) {
  11236. std::string data(100, 'X');
  11237. sink.write(data.c_str(), data.size());
  11238. return true;
  11239. }
  11240. // Wait for signal then abort
  11241. while (!close_now) {
  11242. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11243. }
  11244. return false; // Abort - server will close connection
  11245. });
  11246. });
  11247. auto port = 8092;
  11248. std::thread t([&]() { svr.listen("localhost", port); });
  11249. svr.wait_until_ready();
  11250. Client cli("localhost", port);
  11251. auto handle = cli.open_stream("GET", "/will-close");
  11252. ASSERT_TRUE(handle.is_valid());
  11253. char buf[256];
  11254. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11255. EXPECT_GT(n, 0) << "First read should succeed";
  11256. // Signal server to close
  11257. close_now = true;
  11258. // Keep reading until error or EOF
  11259. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11260. // Keep reading
  11261. }
  11262. // Should get an error since content_length wasn't satisfied
  11263. if (n < 0) {
  11264. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11265. handle.get_read_error() == Error::Read)
  11266. << "Actual error: " << to_string(handle.get_read_error());
  11267. }
  11268. svr.stop();
  11269. t.join();
  11270. }
  11271. #ifdef CPPHTTPLIB_SSL_ENABLED
  11272. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11273. // Test that read timeout during SSL streaming is detected
  11274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11275. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11276. res.set_content_provider(
  11277. 1000, "text/plain",
  11278. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11279. if (offset < 100) {
  11280. std::string data(100, 'A');
  11281. sink.write(data.c_str(), data.size());
  11282. return true;
  11283. }
  11284. std::this_thread::sleep_for(std::chrono::seconds(3));
  11285. std::string data(900, 'B');
  11286. sink.write(data.c_str(), data.size());
  11287. return true;
  11288. });
  11289. });
  11290. auto port = 8093;
  11291. std::thread t([&]() { svr.listen("localhost", port); });
  11292. svr.wait_until_ready();
  11293. SSLClient cli("localhost", port);
  11294. cli.enable_server_certificate_verification(false);
  11295. cli.set_read_timeout(1, 0); // 1 second timeout
  11296. auto handle = cli.open_stream("GET", "/slow-stream");
  11297. ASSERT_TRUE(handle.is_valid());
  11298. char buf[256];
  11299. ssize_t total = 0;
  11300. ssize_t n;
  11301. bool got_error = false;
  11302. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11303. total += n;
  11304. }
  11305. if (n < 0) {
  11306. got_error = true;
  11307. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11308. handle.get_read_error() == Error::Read)
  11309. << "Actual error: " << to_string(handle.get_read_error());
  11310. }
  11311. EXPECT_TRUE(got_error || total < 1000)
  11312. << "Expected timeout but got all " << total << " bytes";
  11313. svr.stop();
  11314. t.join();
  11315. }
  11316. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11317. // Test SSL connection closed detection
  11318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11319. std::atomic<bool> close_now{false};
  11320. svr.Get("/will-close", [&](const Request &, Response &res) {
  11321. res.set_content_provider(
  11322. 10000, "text/plain",
  11323. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11324. if (offset < 100) {
  11325. std::string data(100, 'X');
  11326. sink.write(data.c_str(), data.size());
  11327. return true;
  11328. }
  11329. while (!close_now) {
  11330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11331. }
  11332. return false;
  11333. });
  11334. });
  11335. auto port = 8094;
  11336. std::thread t([&]() { svr.listen("localhost", port); });
  11337. svr.wait_until_ready();
  11338. SSLClient cli("localhost", port);
  11339. cli.enable_server_certificate_verification(false);
  11340. auto handle = cli.open_stream("GET", "/will-close");
  11341. ASSERT_TRUE(handle.is_valid());
  11342. char buf[256];
  11343. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11344. EXPECT_GT(n, 0);
  11345. // Signal server to close
  11346. close_now = true;
  11347. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11348. // Keep reading
  11349. }
  11350. if (n < 0) {
  11351. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11352. handle.get_read_error() == Error::Read)
  11353. << "Actual error: " << to_string(handle.get_read_error());
  11354. }
  11355. svr.stop();
  11356. t.join();
  11357. }
  11358. #endif
  11359. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11360. using namespace httplib;
  11361. // Create a test file
  11362. const char *fname = "etag_testfile.txt";
  11363. const char *content = "etag-content";
  11364. {
  11365. std::ofstream ofs(fname);
  11366. ofs << content;
  11367. ASSERT_TRUE(ofs.good());
  11368. }
  11369. Server svr;
  11370. svr.set_mount_point("/static", ".");
  11371. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11372. svr.wait_until_ready();
  11373. Client cli(HOST, PORT);
  11374. // First request: should get 200 with ETag header
  11375. auto res1 = cli.Get("/static/etag_testfile.txt");
  11376. ASSERT_TRUE(res1);
  11377. ASSERT_EQ(200, res1->status);
  11378. ASSERT_TRUE(res1->has_header("ETag"));
  11379. std::string etag = res1->get_header_value("ETag");
  11380. EXPECT_FALSE(etag.empty());
  11381. // Verify ETag format: W/"hex-hex"
  11382. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11383. EXPECT_EQ('W', etag[0]);
  11384. EXPECT_EQ('/', etag[1]);
  11385. EXPECT_EQ('"', etag[2]);
  11386. EXPECT_EQ('"', etag.back());
  11387. // Exact match: expect 304 Not Modified
  11388. Headers h2 = {{"If-None-Match", etag}};
  11389. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11390. ASSERT_TRUE(res2);
  11391. EXPECT_EQ(304, res2->status);
  11392. // Wildcard match: expect 304 Not Modified
  11393. Headers h3 = {{"If-None-Match", "*"}};
  11394. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11395. ASSERT_TRUE(res3);
  11396. EXPECT_EQ(304, res3->status);
  11397. // Non-matching ETag: expect 200
  11398. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11399. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11400. ASSERT_TRUE(res4);
  11401. EXPECT_EQ(200, res4->status);
  11402. // Multiple ETags with one matching: expect 304
  11403. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11404. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11405. ASSERT_TRUE(res5);
  11406. EXPECT_EQ(304, res5->status);
  11407. svr.stop();
  11408. t.join();
  11409. std::remove(fname);
  11410. }
  11411. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11412. using namespace httplib;
  11413. Server svr;
  11414. svr.set_mount_point("/static", ".");
  11415. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11416. svr.wait_until_ready();
  11417. Client cli(HOST, PORT);
  11418. // Send If-None-Match: * to a non-existent file
  11419. Headers h = {{"If-None-Match", "*"}};
  11420. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11421. ASSERT_TRUE(res);
  11422. EXPECT_EQ(404, res->status);
  11423. svr.stop();
  11424. t.join();
  11425. }
  11426. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11427. using namespace httplib;
  11428. // Create a test file
  11429. const char *fname = "ims_testfile.txt";
  11430. const char *content = "if-modified-since-test";
  11431. {
  11432. std::ofstream ofs(fname);
  11433. ofs << content;
  11434. ASSERT_TRUE(ofs.good());
  11435. }
  11436. Server svr;
  11437. svr.set_mount_point("/static", ".");
  11438. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11439. svr.wait_until_ready();
  11440. Client cli(HOST, PORT);
  11441. // First request: should get 200 with Last-Modified header
  11442. auto res1 = cli.Get("/static/ims_testfile.txt");
  11443. ASSERT_TRUE(res1);
  11444. ASSERT_EQ(200, res1->status);
  11445. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11446. std::string last_modified = res1->get_header_value("Last-Modified");
  11447. EXPECT_FALSE(last_modified.empty());
  11448. // If-Modified-Since with same time: expect 304
  11449. Headers h2 = {{"If-Modified-Since", last_modified}};
  11450. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11451. ASSERT_TRUE(res2);
  11452. EXPECT_EQ(304, res2->status);
  11453. // If-Modified-Since with future time: expect 304
  11454. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11455. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11456. ASSERT_TRUE(res3);
  11457. EXPECT_EQ(304, res3->status);
  11458. // If-Modified-Since with past time: expect 200
  11459. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11460. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11461. ASSERT_TRUE(res4);
  11462. EXPECT_EQ(200, res4->status);
  11463. // If-None-Match takes precedence over If-Modified-Since
  11464. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11465. ASSERT_TRUE(res1->has_header("ETag"));
  11466. std::string etag = res1->get_header_value("ETag");
  11467. Headers h5 = {{"If-None-Match", etag},
  11468. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11469. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11470. ASSERT_TRUE(res5);
  11471. EXPECT_EQ(304, res5->status);
  11472. svr.stop();
  11473. t.join();
  11474. std::remove(fname);
  11475. }
  11476. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11477. using namespace httplib;
  11478. Server svr;
  11479. // Endpoint that returns compressible content
  11480. svr.Get("/compressible", [](const Request &, Response &res) {
  11481. // Return a large enough body to trigger compression
  11482. std::string body(1000, 'a');
  11483. res.set_content(body, "text/plain");
  11484. });
  11485. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11486. svr.wait_until_ready();
  11487. Client cli(HOST, PORT);
  11488. // Request with gzip support: should get Vary header when compressed
  11489. cli.set_compress(true);
  11490. auto res1 = cli.Get("/compressible");
  11491. ASSERT_TRUE(res1);
  11492. EXPECT_EQ(200, res1->status);
  11493. // If Content-Encoding is set, Vary should also be set
  11494. if (res1->has_header("Content-Encoding")) {
  11495. EXPECT_TRUE(res1->has_header("Vary"));
  11496. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11497. }
  11498. // Request without Accept-Encoding header: should not have compression
  11499. Headers h_no_compress;
  11500. auto res2 = cli.Get("/compressible", h_no_compress);
  11501. ASSERT_TRUE(res2);
  11502. EXPECT_EQ(200, res2->status);
  11503. // Verify Vary header is present when compression is applied
  11504. // (the exact behavior depends on server configuration)
  11505. svr.stop();
  11506. t.join();
  11507. }
  11508. TEST(ETagTest, IfRangeWithETag) {
  11509. using namespace httplib;
  11510. // Create a test file with known content
  11511. const char *fname = "if_range_testfile.txt";
  11512. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11513. {
  11514. std::ofstream ofs(fname);
  11515. ofs << content;
  11516. ASSERT_TRUE(ofs.good());
  11517. }
  11518. Server svr;
  11519. svr.set_mount_point("/static", ".");
  11520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11521. svr.wait_until_ready();
  11522. Client cli(HOST, PORT);
  11523. // First request: get ETag
  11524. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11525. ASSERT_TRUE(res1);
  11526. ASSERT_EQ(200, res1->status);
  11527. ASSERT_TRUE(res1->has_header("ETag"));
  11528. std::string etag = res1->get_header_value("ETag");
  11529. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11530. // Since our server generates weak ETags (W/"..."), If-Range with our
  11531. // ETag should NOT result in partial content - it should return full content.
  11532. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11533. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11534. ASSERT_TRUE(res2);
  11535. // Weak ETag in If-Range -> full content (200), not partial (206)
  11536. EXPECT_EQ(200, res2->status);
  11537. EXPECT_EQ(content, res2->body);
  11538. EXPECT_FALSE(res2->has_header("Content-Range"));
  11539. // Range request with non-matching If-Range (ETag): should get 200 (full
  11540. // content)
  11541. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11542. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11543. ASSERT_TRUE(res3);
  11544. EXPECT_EQ(200, res3->status);
  11545. EXPECT_EQ(content, res3->body);
  11546. EXPECT_FALSE(res3->has_header("Content-Range"));
  11547. // Range request with strong ETag (hypothetical - our server doesn't generate
  11548. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11549. // should return full content)
  11550. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11551. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11552. ASSERT_TRUE(res4);
  11553. EXPECT_EQ(200, res4->status);
  11554. EXPECT_EQ(content, res4->body);
  11555. EXPECT_FALSE(res4->has_header("Content-Range"));
  11556. svr.stop();
  11557. t.join();
  11558. std::remove(fname);
  11559. }
  11560. TEST(ETagTest, IfRangeWithDate) {
  11561. using namespace httplib;
  11562. // Create a test file
  11563. const char *fname = "if_range_date_testfile.txt";
  11564. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11565. {
  11566. std::ofstream ofs(fname);
  11567. ofs << content;
  11568. ASSERT_TRUE(ofs.good());
  11569. }
  11570. Server svr;
  11571. svr.set_mount_point("/static", ".");
  11572. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11573. svr.wait_until_ready();
  11574. Client cli(HOST, PORT);
  11575. // First request: get Last-Modified
  11576. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11577. ASSERT_TRUE(res1);
  11578. ASSERT_EQ(200, res1->status);
  11579. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11580. std::string last_modified = res1->get_header_value("Last-Modified");
  11581. // Range request with matching If-Range (date): should get 206
  11582. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11583. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11584. ASSERT_TRUE(res2);
  11585. EXPECT_EQ(206, res2->status);
  11586. EXPECT_EQ("FGHIJ", res2->body);
  11587. // Range request with old If-Range date: should get 200 (full content)
  11588. Headers h3 = {{"Range", "bytes=5-9"},
  11589. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11590. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11591. ASSERT_TRUE(res3);
  11592. EXPECT_EQ(200, res3->status);
  11593. EXPECT_EQ(content, res3->body);
  11594. // Range request with future If-Range date: should get 206
  11595. Headers h4 = {{"Range", "bytes=0-4"},
  11596. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11597. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11598. ASSERT_TRUE(res4);
  11599. EXPECT_EQ(206, res4->status);
  11600. EXPECT_EQ("ABCDE", res4->body);
  11601. svr.stop();
  11602. t.join();
  11603. std::remove(fname);
  11604. }
  11605. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11606. using namespace httplib;
  11607. const char *fname = "etag_malformed.txt";
  11608. const char *content = "malformed-etag";
  11609. {
  11610. std::ofstream ofs(fname);
  11611. ofs << content;
  11612. ASSERT_TRUE(ofs.good());
  11613. }
  11614. Server svr;
  11615. svr.set_mount_point("/static", ".");
  11616. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11617. svr.wait_until_ready();
  11618. Client cli(HOST, PORT);
  11619. // baseline: should get 200 and an ETag
  11620. auto res1 = cli.Get("/static/etag_malformed.txt");
  11621. ASSERT_TRUE(res1);
  11622. ASSERT_EQ(200, res1->status);
  11623. ASSERT_TRUE(res1->has_header("ETag"));
  11624. // Malformed ETag value (missing quotes) should be treated as non-matching
  11625. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11626. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11627. ASSERT_TRUE(res_bad);
  11628. EXPECT_EQ(200, res_bad->status);
  11629. // Whitespace-only header value should be considered invalid / non-matching
  11630. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11631. "Host: localhost\r\n"
  11632. "If-None-Match: \r\n"
  11633. "Connection: close\r\n"
  11634. "\r\n";
  11635. std::string out;
  11636. ASSERT_TRUE(send_request(5, raw_req, &out));
  11637. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11638. svr.stop();
  11639. t.join();
  11640. std::remove(fname);
  11641. }
  11642. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11643. using namespace httplib;
  11644. const char *fname = "ims_invalid_format.txt";
  11645. const char *content = "ims-bad-format";
  11646. {
  11647. std::ofstream ofs(fname);
  11648. ofs << content;
  11649. ASSERT_TRUE(ofs.good());
  11650. }
  11651. Server svr;
  11652. svr.set_mount_point("/static", ".");
  11653. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11654. svr.wait_until_ready();
  11655. Client cli(HOST, PORT);
  11656. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11657. ASSERT_TRUE(res1);
  11658. ASSERT_EQ(200, res1->status);
  11659. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11660. // If-Modified-Since with invalid format should not result in 304
  11661. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11662. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11663. ASSERT_TRUE(res_bad);
  11664. EXPECT_EQ(200, res_bad->status);
  11665. // If-Range with invalid date format should be treated as mismatch -> full
  11666. // content (200)
  11667. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11668. {"If-Range", "invalid-date"}};
  11669. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11670. ASSERT_TRUE(res_ifrange);
  11671. EXPECT_EQ(200, res_ifrange->status);
  11672. svr.stop();
  11673. t.join();
  11674. std::remove(fname);
  11675. }
  11676. TEST(ETagTest, IfRangeWithMalformedETag) {
  11677. using namespace httplib;
  11678. const char *fname = "ifrange_malformed.txt";
  11679. const std::string content = "0123456789";
  11680. {
  11681. std::ofstream ofs(fname);
  11682. ofs << content;
  11683. ASSERT_TRUE(ofs.good());
  11684. }
  11685. Server svr;
  11686. svr.set_mount_point("/static", ".");
  11687. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11688. svr.wait_until_ready();
  11689. Client cli(HOST, PORT);
  11690. // First request: get ETag
  11691. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11692. ASSERT_TRUE(res1);
  11693. ASSERT_EQ(200, res1->status);
  11694. ASSERT_TRUE(res1->has_header("ETag"));
  11695. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11696. // full content (200)
  11697. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11698. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11699. ASSERT_TRUE(res2);
  11700. EXPECT_EQ(200, res2->status);
  11701. EXPECT_EQ(content, res2->body);
  11702. svr.stop();
  11703. t.join();
  11704. std::remove(fname);
  11705. }
  11706. TEST(ETagTest, ExtremeLargeDateValues) {
  11707. using namespace httplib;
  11708. const char *fname = "ims_extreme_date.txt";
  11709. const char *content = "ims-extreme-date";
  11710. {
  11711. std::ofstream ofs(fname);
  11712. ofs << content;
  11713. ASSERT_TRUE(ofs.good());
  11714. }
  11715. Server svr;
  11716. svr.set_mount_point("/static", ".");
  11717. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11718. svr.wait_until_ready();
  11719. Client cli(HOST, PORT);
  11720. auto res1 = cli.Get(std::string("/static/") + fname);
  11721. ASSERT_TRUE(res1);
  11722. ASSERT_EQ(200, res1->status);
  11723. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11724. // Extremely large year that may overflow date parsing routines.
  11725. Headers h_large_date = {
  11726. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11727. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11728. ASSERT_TRUE(res_bad);
  11729. // Expect server to treat this as invalid/mismatch and return full content
  11730. EXPECT_EQ(200, res_bad->status);
  11731. // If-Range with extremely large date should be treated as mismatch -> full
  11732. // content (200)
  11733. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11734. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11735. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11736. ASSERT_TRUE(res_ifrange);
  11737. EXPECT_EQ(200, res_ifrange->status);
  11738. svr.stop();
  11739. t.join();
  11740. std::remove(fname);
  11741. }
  11742. TEST(ETagTest, NegativeFileModificationTime) {
  11743. using namespace httplib;
  11744. const char *fname = "ims_negative_mtime.txt";
  11745. const std::string content = "negative-mtime";
  11746. {
  11747. std::ofstream ofs(fname);
  11748. ofs << content;
  11749. ASSERT_TRUE(ofs.good());
  11750. }
  11751. // Try to set file mtime to a negative value. This may fail on some
  11752. // platforms/filesystems; if it fails, the test will still verify server
  11753. // behaves safely by performing a regular conditional request.
  11754. #if defined(__APPLE__) || defined(__linux__)
  11755. bool set_negative = false;
  11756. do {
  11757. struct timeval times[2];
  11758. // access time: now
  11759. times[0].tv_sec = time(nullptr);
  11760. times[0].tv_usec = 0;
  11761. // modification time: negative (e.g., -1)
  11762. times[1].tv_sec = -1;
  11763. times[1].tv_usec = 0;
  11764. if (utimes(fname, times) == 0) { set_negative = true; }
  11765. } while (0);
  11766. #else
  11767. bool set_negative = false;
  11768. #endif
  11769. Server svr;
  11770. svr.set_mount_point("/static", ".");
  11771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11772. svr.wait_until_ready();
  11773. Client cli(HOST, PORT);
  11774. auto res1 = cli.Get(std::string("/static/") + fname);
  11775. ASSERT_TRUE(res1);
  11776. ASSERT_EQ(200, res1->status);
  11777. bool has_last_modified = res1->has_header("Last-Modified");
  11778. std::string last_modified;
  11779. if (has_last_modified) {
  11780. last_modified = res1->get_header_value("Last-Modified");
  11781. }
  11782. if (set_negative) {
  11783. // If we successfully set a negative mtime, ensure server returns a
  11784. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11785. // with an old date and ensure server handles it without crash.
  11786. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11787. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11788. ASSERT_TRUE(res2);
  11789. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11790. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11791. } else {
  11792. // Could not set negative mtime on this platform; fall back to verifying
  11793. // that normal invalid/malformed dates are treated safely (non-304).
  11794. Headers h_bad_date = {
  11795. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11796. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11797. ASSERT_TRUE(res_bad);
  11798. EXPECT_EQ(200, res_bad->status);
  11799. }
  11800. svr.stop();
  11801. t.join();
  11802. std::remove(fname);
  11803. }
  11804. //==============================================================================
  11805. // SSE Parsing Tests
  11806. //==============================================================================
  11807. class SSEParsingTest : public ::testing::Test {
  11808. protected:
  11809. // Test helper that mimics SSE parsing behavior
  11810. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11811. int &retry_ms) {
  11812. // Blank line signals end of event
  11813. if (line.empty() || line == "\r") { return true; }
  11814. // Lines starting with ':' are comments (ignored)
  11815. if (!line.empty() && line[0] == ':') { return false; }
  11816. // Find the colon separator
  11817. auto colon_pos = line.find(':');
  11818. if (colon_pos == std::string::npos) {
  11819. // Line with no colon is treated as field name with empty value
  11820. return false;
  11821. }
  11822. std::string field = line.substr(0, colon_pos);
  11823. std::string value;
  11824. // Value starts after colon, skip optional single space
  11825. if (colon_pos + 1 < line.size()) {
  11826. size_t value_start = colon_pos + 1;
  11827. if (line[value_start] == ' ') { value_start++; }
  11828. value = line.substr(value_start);
  11829. // Remove trailing \r if present
  11830. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11831. }
  11832. // Handle known fields
  11833. if (field == "event") {
  11834. msg.event = value;
  11835. } else if (field == "data") {
  11836. // Multiple data lines are concatenated with newlines
  11837. if (!msg.data.empty()) { msg.data += "\n"; }
  11838. msg.data += value;
  11839. } else if (field == "id") {
  11840. // Empty id is valid (clears the last event ID)
  11841. msg.id = value;
  11842. } else if (field == "retry") {
  11843. // Parse retry interval in milliseconds
  11844. {
  11845. int v = 0;
  11846. auto res =
  11847. detail::from_chars(value.data(), value.data() + value.size(), v);
  11848. if (res.ec == std::errc{}) { retry_ms = v; }
  11849. }
  11850. }
  11851. // Unknown fields are ignored per SSE spec
  11852. return false;
  11853. }
  11854. };
  11855. // Test: Single-line data
  11856. TEST_F(SSEParsingTest, SingleLineData) {
  11857. sse::SSEMessage msg;
  11858. int retry_ms = 3000;
  11859. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11860. EXPECT_EQ(msg.data, "hello");
  11861. EXPECT_EQ(msg.event, "message");
  11862. // Blank line ends event
  11863. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11864. }
  11865. // Test: Multi-line data
  11866. TEST_F(SSEParsingTest, MultiLineData) {
  11867. sse::SSEMessage msg;
  11868. int retry_ms = 3000;
  11869. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11870. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11871. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11872. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11873. }
  11874. // Test: Custom event types
  11875. TEST_F(SSEParsingTest, CustomEventType) {
  11876. sse::SSEMessage msg;
  11877. int retry_ms = 3000;
  11878. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11879. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11880. EXPECT_EQ(msg.event, "update");
  11881. EXPECT_EQ(msg.data, "payload");
  11882. }
  11883. // Test: Event ID handling
  11884. TEST_F(SSEParsingTest, EventIdHandling) {
  11885. sse::SSEMessage msg;
  11886. int retry_ms = 3000;
  11887. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11888. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11889. EXPECT_EQ(msg.id, "12345");
  11890. }
  11891. // Test: Empty event ID (clears last event ID)
  11892. TEST_F(SSEParsingTest, EmptyEventId) {
  11893. sse::SSEMessage msg;
  11894. msg.id = "previous";
  11895. int retry_ms = 3000;
  11896. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11897. EXPECT_EQ(msg.id, "");
  11898. }
  11899. // Test: Retry field parsing
  11900. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11901. sse::SSEMessage msg;
  11902. int retry_ms = 3000;
  11903. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11904. EXPECT_EQ(retry_ms, 5000);
  11905. }
  11906. // Test: Invalid retry value
  11907. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11908. sse::SSEMessage msg;
  11909. int retry_ms = 3000;
  11910. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11911. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11912. }
  11913. // Test: Comments (lines starting with :)
  11914. TEST_F(SSEParsingTest, CommentsIgnored) {
  11915. sse::SSEMessage msg;
  11916. int retry_ms = 3000;
  11917. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11918. EXPECT_EQ(msg.data, "");
  11919. EXPECT_EQ(msg.event, "message");
  11920. }
  11921. // Test: Colon in value
  11922. TEST_F(SSEParsingTest, ColonInValue) {
  11923. sse::SSEMessage msg;
  11924. int retry_ms = 3000;
  11925. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11926. EXPECT_EQ(msg.data, "hello:world:test");
  11927. }
  11928. // Test: Line with no colon (field name only)
  11929. TEST_F(SSEParsingTest, FieldNameOnly) {
  11930. sse::SSEMessage msg;
  11931. int retry_ms = 3000;
  11932. // According to SSE spec, this is treated as field name with empty value
  11933. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11934. // Since we don't recognize "data" without colon, data should be empty
  11935. EXPECT_EQ(msg.data, "");
  11936. }
  11937. // Test: Trailing \r handling
  11938. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11939. sse::SSEMessage msg;
  11940. int retry_ms = 3000;
  11941. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11942. EXPECT_EQ(msg.data, "hello");
  11943. }
  11944. // Test: Unknown fields ignored
  11945. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11946. sse::SSEMessage msg;
  11947. int retry_ms = 3000;
  11948. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11949. EXPECT_EQ(msg.data, "");
  11950. EXPECT_EQ(msg.event, "message");
  11951. }
  11952. // Test: Space after colon is optional
  11953. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11954. sse::SSEMessage msg1, msg2;
  11955. int retry_ms = 3000;
  11956. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11957. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11958. EXPECT_EQ(msg1.data, "hello");
  11959. EXPECT_EQ(msg2.data, "hello");
  11960. }
  11961. // Test: SSEMessage clear
  11962. TEST_F(SSEParsingTest, MessageClear) {
  11963. sse::SSEMessage msg;
  11964. msg.event = "custom";
  11965. msg.data = "some data";
  11966. msg.id = "123";
  11967. msg.clear();
  11968. EXPECT_EQ(msg.event, "message");
  11969. EXPECT_EQ(msg.data, "");
  11970. EXPECT_EQ(msg.id, "");
  11971. }
  11972. // Test: Complete event parsing
  11973. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11974. sse::SSEMessage msg;
  11975. int retry_ms = 3000;
  11976. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11977. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11978. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11979. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11980. // Blank line ends event
  11981. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11982. EXPECT_EQ(msg.event, "notification");
  11983. EXPECT_EQ(msg.id, "evt-42");
  11984. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11985. EXPECT_EQ(retry_ms, 1000);
  11986. }
  11987. //==============================================================================
  11988. // Integration Tests with Server
  11989. //==============================================================================
  11990. class SSEIntegrationTest : public ::testing::Test {
  11991. protected:
  11992. void SetUp() override {
  11993. stop_server_.store(false);
  11994. events_.clear();
  11995. server_ = httplib::detail::make_unique<Server>();
  11996. setup_server();
  11997. start_server();
  11998. }
  11999. void TearDown() override {
  12000. stop_server_.store(true);
  12001. event_cv_.notify_all();
  12002. server_->stop();
  12003. if (server_thread_.joinable()) { server_thread_.join(); }
  12004. }
  12005. void setup_server() {
  12006. // Simple SSE endpoint
  12007. server_->Get("/events", [this](const Request &req, Response &res) {
  12008. auto last_id = req.get_header_value("Last-Event-ID");
  12009. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12010. res.set_chunked_content_provider(
  12011. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12012. std::unique_lock<std::mutex> lock(event_mutex_);
  12013. if (event_cv_.wait_for(
  12014. lock, std::chrono::milliseconds(200), [this] {
  12015. return !events_.empty() || stop_server_.load();
  12016. })) {
  12017. if (stop_server_.load()) { return false; }
  12018. if (!events_.empty()) {
  12019. std::string event = events_.front();
  12020. events_.erase(events_.begin());
  12021. sink.write(event.data(), event.size());
  12022. return true;
  12023. }
  12024. }
  12025. return !stop_server_.load();
  12026. });
  12027. });
  12028. // Endpoint that returns error
  12029. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12030. res.status = 500;
  12031. res.set_content("Internal Server Error", "text/plain");
  12032. });
  12033. // Endpoint for custom event types
  12034. server_->Get("/custom-events", [](const Request &, Response &res) {
  12035. res.set_chunked_content_provider(
  12036. "text/event-stream", [](size_t offset, DataSink &sink) {
  12037. if (offset == 0) {
  12038. std::string event = "event: update\ndata: updated\n\n"
  12039. "event: delete\ndata: deleted\n\n";
  12040. sink.write(event.data(), event.size());
  12041. }
  12042. return false; // End stream after sending
  12043. });
  12044. });
  12045. }
  12046. void start_server() {
  12047. port_ = server_->bind_to_any_port(HOST);
  12048. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12049. // Wait for server to start
  12050. while (!server_->is_running()) {
  12051. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12052. }
  12053. }
  12054. int get_port() const { return port_; }
  12055. void send_event(const std::string &event) {
  12056. std::lock_guard<std::mutex> lock(event_mutex_);
  12057. events_.push_back(event);
  12058. event_cv_.notify_all();
  12059. }
  12060. std::unique_ptr<Server> server_;
  12061. std::thread server_thread_;
  12062. std::mutex event_mutex_;
  12063. std::condition_variable event_cv_;
  12064. std::vector<std::string> events_;
  12065. std::atomic<bool> stop_server_{false};
  12066. std::string last_received_event_id_;
  12067. int port_ = 0;
  12068. };
  12069. // Test: Successful connection and on_open callback
  12070. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12071. // Add a simple endpoint that sends one event and closes
  12072. server_->Get("/simple-event", [](const Request &, Response &res) {
  12073. res.set_chunked_content_provider(
  12074. "text/event-stream", [](size_t offset, DataSink &sink) {
  12075. if (offset == 0) {
  12076. std::string event = "data: hello\n\n";
  12077. sink.write(event.data(), event.size());
  12078. }
  12079. return false; // Close stream after sending
  12080. });
  12081. });
  12082. Client client("localhost", get_port());
  12083. sse::SSEClient sse(client, "/simple-event");
  12084. std::atomic<bool> open_called{false};
  12085. std::atomic<bool> message_received{false};
  12086. sse.on_open([&open_called]() { open_called.store(true); });
  12087. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12088. if (msg.data == "hello") { message_received.store(true); }
  12089. });
  12090. sse.set_reconnect_interval(100);
  12091. sse.set_max_reconnect_attempts(1);
  12092. // Start async
  12093. sse.start_async();
  12094. // Wait for message to be processed
  12095. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12096. sse.stop();
  12097. EXPECT_TRUE(open_called.load());
  12098. EXPECT_TRUE(message_received.load());
  12099. }
  12100. // Test: on_message callback
  12101. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12102. // Endpoint that sends multiple events then closes
  12103. server_->Get("/multi-event", [](const Request &, Response &res) {
  12104. res.set_chunked_content_provider(
  12105. "text/event-stream", [](size_t offset, DataSink &sink) {
  12106. if (offset == 0) {
  12107. std::string events = "data: message1\n\ndata: message2\n\n";
  12108. sink.write(events.data(), events.size());
  12109. }
  12110. return false;
  12111. });
  12112. });
  12113. Client client("localhost", get_port());
  12114. sse::SSEClient sse(client, "/multi-event");
  12115. std::vector<std::string> received_messages;
  12116. std::mutex messages_mutex;
  12117. sse.on_message([&](const sse::SSEMessage &msg) {
  12118. std::lock_guard<std::mutex> lock(messages_mutex);
  12119. received_messages.push_back(msg.data);
  12120. });
  12121. sse.set_reconnect_interval(100);
  12122. sse.set_max_reconnect_attempts(1);
  12123. sse.start_async();
  12124. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12125. sse.stop();
  12126. std::lock_guard<std::mutex> lock(messages_mutex);
  12127. EXPECT_GE(received_messages.size(), 2u);
  12128. if (received_messages.size() >= 2) {
  12129. EXPECT_EQ(received_messages[0], "message1");
  12130. EXPECT_EQ(received_messages[1], "message2");
  12131. }
  12132. }
  12133. // Test: on_event for specific types
  12134. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12135. Client client("localhost", get_port());
  12136. sse::SSEClient sse(client, "/custom-events");
  12137. std::atomic<bool> update_received{false};
  12138. std::atomic<bool> delete_received{false};
  12139. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12140. if (msg.data == "updated") { update_received.store(true); }
  12141. });
  12142. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12143. if (msg.data == "deleted") { delete_received.store(true); }
  12144. });
  12145. sse.set_max_reconnect_attempts(1);
  12146. sse.start_async();
  12147. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12148. sse.stop();
  12149. EXPECT_TRUE(update_received.load());
  12150. EXPECT_TRUE(delete_received.load());
  12151. }
  12152. // Test: on_error callback on connection failure
  12153. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12154. // Connect to a non-existent port
  12155. Client client("localhost", 59999);
  12156. sse::SSEClient sse(client, "/events");
  12157. std::atomic<bool> error_called{false};
  12158. Error received_error = Error::Success;
  12159. sse.on_error([&](Error err) {
  12160. error_called.store(true);
  12161. received_error = err;
  12162. });
  12163. sse.set_reconnect_interval(50);
  12164. sse.set_max_reconnect_attempts(1);
  12165. sse.start_async();
  12166. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12167. sse.stop();
  12168. EXPECT_TRUE(error_called.load());
  12169. EXPECT_NE(received_error, Error::Success);
  12170. }
  12171. // Test: Last-Event-ID header sent on reconnect
  12172. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12173. // Endpoint that sends event with ID
  12174. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12175. res.set_chunked_content_provider(
  12176. "text/event-stream", [](size_t offset, DataSink &sink) {
  12177. if (offset == 0) {
  12178. std::string event = "id: evt-123\ndata: test\n\n";
  12179. sink.write(event.data(), event.size());
  12180. }
  12181. return false;
  12182. });
  12183. });
  12184. Client client("localhost", get_port());
  12185. sse::SSEClient sse(client, "/event-with-id");
  12186. std::atomic<bool> id_received{false};
  12187. sse.on_message([&](const sse::SSEMessage &msg) {
  12188. if (!msg.id.empty()) { id_received.store(true); }
  12189. });
  12190. sse.set_reconnect_interval(100);
  12191. sse.set_max_reconnect_attempts(1);
  12192. sse.start_async();
  12193. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12194. sse.stop();
  12195. EXPECT_TRUE(id_received.load());
  12196. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12197. }
  12198. // Test: Manual stop
  12199. TEST_F(SSEIntegrationTest, ManualStop) {
  12200. // Endpoint that sends one event and stays open briefly
  12201. std::atomic<bool> handler_running{true};
  12202. server_->Get("/stay-open", [&handler_running](const Request &,
  12203. Response &res) {
  12204. res.set_chunked_content_provider(
  12205. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12206. if (offset == 0) {
  12207. std::string event = "data: connected\n\n";
  12208. sink.write(event.data(), event.size());
  12209. }
  12210. // Keep connection open while handler_running is true
  12211. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12212. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12213. }
  12214. return false;
  12215. });
  12216. });
  12217. Client client("localhost", get_port());
  12218. sse::SSEClient sse(client, "/stay-open");
  12219. std::atomic<bool> connected{false};
  12220. sse.on_open([&connected]() { connected.store(true); });
  12221. sse.set_reconnect_interval(100);
  12222. sse.set_max_reconnect_attempts(1);
  12223. sse.start_async();
  12224. // Wait for connection to establish
  12225. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12226. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12227. }
  12228. EXPECT_TRUE(connected.load());
  12229. EXPECT_TRUE(sse.is_connected());
  12230. // Signal handler to stop
  12231. handler_running.store(false);
  12232. // Stop SSE client
  12233. sse.stop();
  12234. EXPECT_FALSE(sse.is_connected());
  12235. }
  12236. // Test: SSEClient with custom headers
  12237. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12238. // Setup a server endpoint that checks for custom header
  12239. std::atomic<bool> header_received{false};
  12240. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12241. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12242. header_received.store(true);
  12243. }
  12244. res.set_chunked_content_provider("text/event-stream",
  12245. [](size_t, DataSink &) { return false; });
  12246. });
  12247. Client client("localhost", get_port());
  12248. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12249. sse::SSEClient sse(client, "/header-check", headers);
  12250. sse.set_max_reconnect_attempts(1);
  12251. sse.start_async();
  12252. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12253. sse.stop();
  12254. EXPECT_TRUE(header_received.load());
  12255. }
  12256. // Test: Reconnect interval configuration
  12257. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12258. Client client("localhost", get_port());
  12259. sse::SSEClient sse(client, "/events");
  12260. auto &result = sse.set_reconnect_interval(500);
  12261. // Builder pattern should return reference to self
  12262. EXPECT_EQ(&result, &sse);
  12263. }
  12264. // Test: Max reconnect attempts
  12265. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12266. // Connect to non-existent port to force reconnects
  12267. Client client("localhost", 59998);
  12268. sse::SSEClient sse(client, "/events");
  12269. std::atomic<int> error_count{0};
  12270. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12271. sse.set_reconnect_interval(50);
  12272. sse.set_max_reconnect_attempts(2);
  12273. auto start = std::chrono::steady_clock::now();
  12274. sse.start(); // Blocking call
  12275. auto end = std::chrono::steady_clock::now();
  12276. // Should have stopped after 2 failed attempts
  12277. EXPECT_GE(error_count.load(), 2);
  12278. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12279. auto duration =
  12280. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12281. #ifdef _WIN32
  12282. // Windows is much slower for socket connection failures
  12283. EXPECT_LT(duration.count(), 7000);
  12284. #else
  12285. EXPECT_LT(duration.count(), 1000);
  12286. #endif
  12287. }
  12288. // Test: Multi-line data in integration
  12289. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12290. // Endpoint with multi-line data
  12291. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12292. res.set_chunked_content_provider(
  12293. "text/event-stream", [](size_t offset, DataSink &sink) {
  12294. if (offset == 0) {
  12295. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12296. sink.write(event.data(), event.size());
  12297. }
  12298. return false;
  12299. });
  12300. });
  12301. Client client("localhost", get_port());
  12302. sse::SSEClient sse(client, "/multiline-data");
  12303. std::string received_data;
  12304. std::mutex data_mutex;
  12305. sse.on_message([&](const sse::SSEMessage &msg) {
  12306. std::lock_guard<std::mutex> lock(data_mutex);
  12307. received_data = msg.data;
  12308. });
  12309. sse.set_reconnect_interval(100);
  12310. sse.set_max_reconnect_attempts(1);
  12311. sse.start_async();
  12312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12313. sse.stop();
  12314. std::lock_guard<std::mutex> lock(data_mutex);
  12315. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12316. }
  12317. // Test: Auto-reconnect after server disconnection
  12318. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12319. std::atomic<int> connection_count{0};
  12320. std::atomic<int> message_count{0};
  12321. // Endpoint that sends one event and closes, forcing reconnect
  12322. server_->Get("/reconnect-test",
  12323. [&connection_count](const Request &, Response &res) {
  12324. connection_count.fetch_add(1);
  12325. res.set_chunked_content_provider(
  12326. "text/event-stream", [](size_t offset, DataSink &sink) {
  12327. if (offset == 0) {
  12328. std::string event = "data: hello\n\n";
  12329. sink.write(event.data(), event.size());
  12330. }
  12331. return false; // Close connection after sending
  12332. });
  12333. });
  12334. Client client("localhost", get_port());
  12335. sse::SSEClient sse(client, "/reconnect-test");
  12336. sse.on_message([&message_count](const sse::SSEMessage &) {
  12337. message_count.fetch_add(1);
  12338. });
  12339. sse.set_reconnect_interval(100);
  12340. sse.set_max_reconnect_attempts(3);
  12341. sse.start_async();
  12342. // Wait long enough for multiple reconnects
  12343. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12344. sse.stop();
  12345. // Should have connected multiple times (initial + reconnects)
  12346. EXPECT_GE(connection_count.load(), 2);
  12347. // Should have received messages from multiple connections
  12348. EXPECT_GE(message_count.load(), 2);
  12349. }
  12350. // Test: Last-Event-ID sent on reconnect
  12351. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12352. std::atomic<int> connection_count{0};
  12353. std::vector<std::string> received_last_event_ids;
  12354. std::mutex id_mutex;
  12355. // Endpoint that checks Last-Event-ID header and sends event with ID
  12356. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12357. int conn = connection_count.fetch_add(1);
  12358. // Capture the Last-Event-ID header from each connection
  12359. {
  12360. std::lock_guard<std::mutex> lock(id_mutex);
  12361. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12362. }
  12363. res.set_chunked_content_provider(
  12364. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12365. if (offset == 0) {
  12366. std::string event =
  12367. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12368. sink.write(event.data(), event.size());
  12369. }
  12370. return false;
  12371. });
  12372. });
  12373. Client client("localhost", get_port());
  12374. sse::SSEClient sse(client, "/reconnect-with-id");
  12375. sse.set_reconnect_interval(100);
  12376. sse.set_max_reconnect_attempts(3);
  12377. sse.start_async();
  12378. // Wait for at least 2 connections
  12379. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12380. sse.stop();
  12381. // Verify behavior
  12382. std::lock_guard<std::mutex> lock(id_mutex);
  12383. EXPECT_GE(received_last_event_ids.size(), 2u);
  12384. // First connection should have no Last-Event-ID
  12385. if (!received_last_event_ids.empty()) {
  12386. EXPECT_EQ(received_last_event_ids[0], "");
  12387. }
  12388. // Second connection should have Last-Event-ID from first connection
  12389. if (received_last_event_ids.size() >= 2) {
  12390. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12391. }
  12392. }
  12393. TEST(Issue2318Test, EmptyHostString) {
  12394. {
  12395. httplib::Client cli_empty("", PORT);
  12396. auto res = cli_empty.Get("/");
  12397. ASSERT_FALSE(res);
  12398. EXPECT_EQ(httplib::Error::Connection, res.error());
  12399. }
  12400. {
  12401. httplib::Client cli(" ", PORT);
  12402. auto res = cli.Get("/");
  12403. ASSERT_FALSE(res);
  12404. EXPECT_EQ(httplib::Error::Connection, res.error());
  12405. }
  12406. }
  12407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12408. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12409. Server svr;
  12410. // Set a small payload limit (1KB)
  12411. svr.set_payload_max_length(1024);
  12412. svr.Post("/test", [&](const Request &req, Response &res) {
  12413. res.set_content("Body size: " + std::to_string(req.body.size()),
  12414. "text/plain");
  12415. });
  12416. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12417. auto se = detail::scope_exit([&] {
  12418. svr.stop();
  12419. listen_thread.join();
  12420. });
  12421. svr.wait_until_ready();
  12422. // Create data that compresses well but exceeds limit when decompressed
  12423. // 8KB of repeated null bytes compresses to a very small size
  12424. std::string original_data(8 * 1024, '\0');
  12425. // Compress the data using gzip
  12426. std::string compressed_data;
  12427. detail::gzip_compressor compressor;
  12428. compressor.compress(original_data.data(), original_data.size(), true,
  12429. [&](const char *data, size_t size) {
  12430. compressed_data.append(data, size);
  12431. return true;
  12432. });
  12433. // Verify compression worked (compressed should be much smaller)
  12434. ASSERT_LT(compressed_data.size(), original_data.size());
  12435. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12436. // Send compressed data with Content-Encoding: gzip
  12437. Client cli(HOST, PORT);
  12438. Headers headers = {{"Content-Encoding", "gzip"}};
  12439. auto res =
  12440. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12441. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12442. ASSERT_TRUE(res);
  12443. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12444. }
  12445. #endif
  12446. // ============================================================================
  12447. // OpenSSL-Specific Tests
  12448. // ============================================================================
  12449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12450. X509 *readCertificate(const std::string &strFileName) {
  12451. std::ifstream inStream(strFileName);
  12452. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12453. std::istreambuf_iterator<char>());
  12454. if (strCertPEM.empty()) return (nullptr);
  12455. BIO *pbCert = BIO_new(BIO_s_mem());
  12456. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12457. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12458. BIO_free(pbCert);
  12459. return (pCert);
  12460. }
  12461. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12462. std::ifstream inStream(strFileName);
  12463. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12464. std::istreambuf_iterator<char>());
  12465. if (strPrivateKeyPEM.empty()) return (nullptr);
  12466. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12467. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12468. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12469. BIO_free(pbPrivKey);
  12470. return (pPrivateKey);
  12471. }
  12472. TEST(BindServerTest, UpdateCerts) {
  12473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12474. int port = svr.bind_to_any_port("0.0.0.0");
  12475. ASSERT_TRUE(svr.is_valid());
  12476. ASSERT_TRUE(port > 0);
  12477. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12478. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12479. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12480. ASSERT_TRUE(cert != nullptr);
  12481. ASSERT_TRUE(ca_cert != nullptr);
  12482. ASSERT_TRUE(key != nullptr);
  12483. X509_STORE *cert_store = X509_STORE_new();
  12484. X509_STORE_add_cert(cert_store, ca_cert);
  12485. // svr.update_certs(cert, key, cert_store); // deprecated
  12486. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12487. CLIENT_CA_CERT_FILE);
  12488. ASSERT_TRUE(svr.is_valid());
  12489. svr.stop();
  12490. X509_free(cert);
  12491. X509_free(ca_cert);
  12492. EVP_PKEY_free(key);
  12493. }
  12494. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12495. // client CA list correctly for TLS handshake
  12496. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12497. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12498. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12499. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12500. ASSERT_TRUE(cert != nullptr);
  12501. ASSERT_TRUE(ca_cert != nullptr);
  12502. ASSERT_TRUE(key != nullptr);
  12503. X509_STORE *cert_store = X509_STORE_new();
  12504. X509_STORE_add_cert(cert_store, ca_cert);
  12505. // Use X509-based constructor (deprecated but should still work correctly)
  12506. #pragma GCC diagnostic push
  12507. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12508. SSLServer svr(cert, key, cert_store);
  12509. #pragma GCC diagnostic pop
  12510. ASSERT_TRUE(svr.is_valid());
  12511. // Verify that client CA list is set in SSL_CTX
  12512. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12513. ASSERT_TRUE(ssl_ctx != nullptr);
  12514. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12515. ASSERT_TRUE(ca_list != nullptr);
  12516. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12517. X509_free(cert);
  12518. X509_free(ca_cert);
  12519. EVP_PKEY_free(key);
  12520. }
  12521. // Test that update_certs() updates client CA list correctly
  12522. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12523. // Start with file-based constructor
  12524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12525. ASSERT_TRUE(svr.is_valid());
  12526. // Initially no client CA list should be set
  12527. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12528. ASSERT_TRUE(ssl_ctx != nullptr);
  12529. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12530. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12531. EXPECT_EQ(0, count_before);
  12532. // Now update with client CA (PEM string)
  12533. std::string cert_pem, key_pem, ca_pem;
  12534. read_file(SERVER_CERT_FILE, cert_pem);
  12535. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12536. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12537. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12538. ASSERT_TRUE(svr.is_valid());
  12539. // Now client CA list should be set
  12540. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12541. ASSERT_TRUE(ca_list_after != nullptr);
  12542. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12543. }
  12544. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12545. // Test that the file-path SSLServer constructor properly sets the client CA
  12546. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12548. ASSERT_TRUE(svr.is_valid());
  12549. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12550. ASSERT_TRUE(ssl_ctx != nullptr);
  12551. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12552. ASSERT_TRUE(ca_list != nullptr);
  12553. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12554. }
  12555. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12556. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12557. // prepare large data
  12558. std::random_device seed_gen;
  12559. std::mt19937 random(seed_gen());
  12560. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12561. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12562. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12563. // server
  12564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12565. ASSERT_TRUE(svr.is_valid());
  12566. svr.Post("/binary", [&](const Request &req, Response &res) {
  12567. EXPECT_EQ(large_size_byte, req.body.size());
  12568. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12569. res.set_content(req.body, "application/octet-stream");
  12570. });
  12571. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12572. auto se = detail::scope_exit([&] {
  12573. svr.stop();
  12574. listen_thread.join();
  12575. ASSERT_FALSE(svr.is_running());
  12576. });
  12577. svr.wait_until_ready();
  12578. // client POST
  12579. SSLClient cli("localhost", PORT);
  12580. cli.enable_server_certificate_verification(false);
  12581. cli.set_read_timeout(std::chrono::seconds(100));
  12582. cli.set_write_timeout(std::chrono::seconds(100));
  12583. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12584. large_size_byte, "application/octet-stream");
  12585. // compare
  12586. EXPECT_EQ(StatusCode::OK_200, res->status);
  12587. EXPECT_EQ(large_size_byte, res->body.size());
  12588. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12589. }
  12590. #endif
  12591. // ============================================================================
  12592. // MbedTLS-Specific Tests
  12593. // ============================================================================
  12594. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12595. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12596. using namespace httplib::tls;
  12597. // Track if callback was invoked
  12598. bool callback_invoked = false;
  12599. // The callback receives void* ctx which is actually MbedTlsContext*
  12600. // We can access the mbedtls_ssl_config via the context
  12601. auto setup_callback = [&callback_invoked](void *ctx) {
  12602. callback_invoked = true;
  12603. // Cast to MbedTlsContext* to access the ssl config
  12604. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12605. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12606. // Use static variables to hold certificate data (simplified for test)
  12607. static mbedtls_x509_crt own_cert;
  12608. static mbedtls_pk_context own_key;
  12609. static mbedtls_x509_crt ca_chain;
  12610. static bool initialized = false;
  12611. if (!initialized) {
  12612. mbedtls_x509_crt_init(&own_cert);
  12613. mbedtls_pk_init(&own_key);
  12614. mbedtls_x509_crt_init(&ca_chain);
  12615. // Load server certificate
  12616. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  12617. return false;
  12618. }
  12619. // Load server private key
  12620. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  12621. #if MBEDTLS_VERSION_MAJOR >= 3
  12622. ,
  12623. mbedtls_ctr_drbg_random, nullptr
  12624. #endif
  12625. ) != 0) {
  12626. return false;
  12627. }
  12628. // Load CA chain for client verification
  12629. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  12630. return false;
  12631. }
  12632. initialized = true;
  12633. }
  12634. // Configure the SSL config
  12635. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  12636. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  12637. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12638. // Set minimum TLS version using mbedTLS native API
  12639. #if MBEDTLS_VERSION_MAJOR >= 3
  12640. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12641. #else
  12642. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12643. MBEDTLS_SSL_MINOR_VERSION_3);
  12644. #endif
  12645. return true;
  12646. };
  12647. SSLServer svr(setup_callback);
  12648. ASSERT_TRUE(svr.is_valid());
  12649. ASSERT_TRUE(callback_invoked);
  12650. svr.Get("/test", [&](const Request &req, Response &res) {
  12651. res.set_content("test", "text/plain");
  12652. auto cert = req.peer_cert();
  12653. ASSERT_TRUE(static_cast<bool>(cert));
  12654. auto common_name = cert.subject_cn();
  12655. EXPECT_EQ("Common Name", common_name);
  12656. });
  12657. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12658. auto se = detail::scope_exit([&] {
  12659. svr.stop();
  12660. t.join();
  12661. ASSERT_FALSE(svr.is_running());
  12662. });
  12663. svr.wait_until_ready();
  12664. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12665. cli.enable_server_certificate_verification(false);
  12666. cli.set_connection_timeout(30);
  12667. auto res = cli.Get("/test");
  12668. ASSERT_TRUE(res);
  12669. ASSERT_EQ(StatusCode::OK_200, res->status);
  12670. }
  12671. #endif