test.cc 481 KB

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