test.cc 482 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_EQ(0, close(fds[1]));
  269. EXPECT_FALSE(s0.wait_writable());
  270. return true;
  271. });
  272. EXPECT_EQ(0, close(fds[0]));
  273. }
  274. TEST(SocketStream, wait_writable_INET) {
  275. sockaddr_in addr;
  276. memset(&addr, 0, sizeof(addr));
  277. addr.sin_family = AF_INET;
  278. addr.sin_port = htons(PORT + 1);
  279. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  280. int disconnected_svr_sock = -1;
  281. std::thread svr{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, listen(s, 1));
  286. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  287. ASSERT_EQ(0, close(s));
  288. }};
  289. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  290. std::thread cli{[&] {
  291. const int s = socket(AF_INET, SOCK_STREAM, 0);
  292. ASSERT_LE(0, s);
  293. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  294. ASSERT_EQ(0, close(s));
  295. }};
  296. cli.join();
  297. svr.join();
  298. ASSERT_NE(disconnected_svr_sock, -1);
  299. const auto asSocketStream = [&](socket_t fd,
  300. std::function<bool(Stream &)> func) {
  301. return detail::process_client_socket(
  302. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  303. };
  304. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  305. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  306. EXPECT_FALSE(ss.wait_writable());
  307. return true;
  308. });
  309. ASSERT_EQ(0, close(disconnected_svr_sock));
  310. }
  311. #endif // #ifndef _WIN32
  312. TEST(ClientTest, MoveConstructible) {
  313. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  314. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  315. }
  316. TEST(ClientTest, MoveAssignable) {
  317. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  318. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  319. }
  320. #ifdef _WIN32
  321. TEST(StartupTest, WSAStartup) {
  322. WSADATA wsaData;
  323. int ret = WSAStartup(0x0002, &wsaData);
  324. ASSERT_EQ(0, ret);
  325. }
  326. #endif
  327. TEST(DecodePathTest, PercentCharacter) {
  328. EXPECT_EQ(
  329. decode_path_component(
  330. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  331. U8("descrip=Gastos áéíóúñÑ 6"));
  332. }
  333. TEST(DecodePathTest, PercentCharacterNUL) {
  334. string expected;
  335. expected.push_back('x');
  336. expected.push_back('\0');
  337. expected.push_back('x');
  338. EXPECT_EQ(decode_path_component("x%00x"), expected);
  339. }
  340. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  341. string unescapedCharacters = "-_.!~*'()";
  342. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  343. }
  344. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  345. string reservedCharacters = ";,/?:@&=+$";
  346. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  347. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  348. }
  349. TEST(ClientQueryOrder, PreserveOrder) {
  350. // This test reproduces Issue #2259: client may reorder query parameters
  351. // when sending a GET request. The expected behavior is that the client
  352. // preserves the original query string order when the caller supplied it
  353. // as part of the path.
  354. Server svr;
  355. svr.Get("/", [&](const Request &req, Response &res) {
  356. // Echo back the raw target so the test can assert ordering
  357. res.set_content(req.target, "text/plain");
  358. });
  359. std::thread t{[&] { svr.listen(HOST, PORT); }};
  360. auto se = detail::scope_exit([&] {
  361. svr.stop();
  362. t.join();
  363. ASSERT_FALSE(svr.is_running());
  364. });
  365. svr.wait_until_ready();
  366. Client cli(HOST, PORT);
  367. ASSERT_TRUE(cli.is_valid());
  368. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  369. auto res = cli.Get(original);
  370. ASSERT_TRUE(res);
  371. // Expect the echoed target to exactly match the original path (order
  372. // preserved)
  373. EXPECT_EQ(res->body, original);
  374. }
  375. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  376. string chineseCharacters = U8("中国語");
  377. string russianCharacters = U8("дом");
  378. string brazilianCharacters = U8("óculos");
  379. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  380. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  381. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  382. "%D0%B4%D0%BE%D0%BC");
  383. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  384. }
  385. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  386. string unescapedCharacters = "-_.!~*'()";
  387. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  388. }
  389. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  390. string reservedCharacters = ";,/?:@&=+$";
  391. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  392. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  393. }
  394. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  395. string chineseCharacters = U8("中国語");
  396. string russianCharacters = U8("дом");
  397. string brazilianCharacters = U8("óculos");
  398. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  399. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  400. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  401. "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  405. // Issue #2082 use case: encoding path component with ampersand
  406. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  407. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  408. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  409. }
  410. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  411. string unescapedCharacters = "-_.!~*'()";
  412. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  413. }
  414. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  415. string reservedCharacters = ";,/?:@&=+$#";
  416. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  417. }
  418. TEST(EncodeUriTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  425. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  426. }
  427. TEST(EncodeUriTest, TestCompleteUri) {
  428. string uri =
  429. "https://example.com/path/to/resource?query=value&param=test#fragment";
  430. EXPECT_EQ(
  431. httplib::encode_uri(uri),
  432. "https://example.com/path/to/resource?query=value&param=test#fragment");
  433. }
  434. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  435. string uri =
  436. "https://example.com/path with spaces/file name.html?q=hello world";
  437. EXPECT_EQ(httplib::encode_uri(uri),
  438. "https://example.com/path%20with%20spaces/"
  439. "file%20name.html?q=hello%20world");
  440. }
  441. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  442. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  443. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  444. }
  445. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  446. string unescapedCharacters = "-_.!~*'()";
  447. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  448. }
  449. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  450. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  451. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  452. string encodedBrazilian = "%C3%B3culos";
  453. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  454. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  455. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  456. }
  457. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  458. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  459. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  460. "Piri Tommy Villiers - on & on");
  461. }
  462. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  463. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  464. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  465. }
  466. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  467. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  468. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  469. }
  470. TEST(DecodeUriTest, TestUTF8Characters) {
  471. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  472. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  473. string encodedBrazilian = "%C3%B3culos";
  474. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  475. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  476. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  477. }
  478. TEST(DecodeUriTest, TestCompleteUri) {
  479. string encodedUri = "https://example.com/path%20with%20spaces/"
  480. "file%20name.html?q=hello%20world";
  481. EXPECT_EQ(
  482. httplib::decode_uri(encodedUri),
  483. "https://example.com/path with spaces/file name.html?q=hello world");
  484. }
  485. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  486. string original =
  487. "https://example.com/path with spaces/file name.html?q=hello world";
  488. string encoded = httplib::encode_uri(original);
  489. string decoded = httplib::decode_uri(encoded);
  490. EXPECT_EQ(decoded, original);
  491. }
  492. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  493. string original = "Piri Tommy Villiers - on & on";
  494. string encoded = httplib::encode_uri_component(original);
  495. string decoded = httplib::decode_uri_component(encoded);
  496. EXPECT_EQ(decoded, original);
  497. }
  498. TEST(TrimTests, TrimStringTests) {
  499. EXPECT_EQ("abc", detail::trim_copy("abc"));
  500. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  501. EXPECT_TRUE(detail::trim_copy("").empty());
  502. }
  503. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  504. // Simple case without quality values
  505. std::vector<std::string> result1;
  506. EXPECT_TRUE(detail::parse_accept_header(
  507. "text/html,application/json,text/plain", result1));
  508. EXPECT_EQ(result1.size(), 3U);
  509. EXPECT_EQ(result1[0], "text/html");
  510. EXPECT_EQ(result1[1], "application/json");
  511. EXPECT_EQ(result1[2], "text/plain");
  512. // With quality values
  513. std::vector<std::string> result2;
  514. EXPECT_TRUE(detail::parse_accept_header(
  515. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  516. EXPECT_EQ(result2.size(), 3U);
  517. EXPECT_EQ(result2[0], "application/json"); // highest q value
  518. EXPECT_EQ(result2[1], "text/html");
  519. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  520. }
  521. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  522. // Mixed with and without quality values
  523. std::vector<std::string> result;
  524. EXPECT_TRUE(detail::parse_accept_header(
  525. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  526. EXPECT_EQ(result.size(), 3U);
  527. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  528. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  529. EXPECT_EQ(result[2], "application/json"); // q=0.5
  530. }
  531. TEST(ParseAcceptHeaderTest, EdgeCases) {
  532. // Empty header
  533. std::vector<std::string> empty_result;
  534. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  535. EXPECT_TRUE(empty_result.empty());
  536. // Single type
  537. std::vector<std::string> single_result;
  538. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  539. EXPECT_EQ(single_result.size(), 1U);
  540. EXPECT_EQ(single_result[0], "application/json");
  541. // Wildcard types
  542. std::vector<std::string> wildcard_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  545. EXPECT_EQ(wildcard_result.size(), 3U);
  546. EXPECT_EQ(wildcard_result[0], "application/json");
  547. EXPECT_EQ(wildcard_result[1], "text/*");
  548. EXPECT_EQ(wildcard_result[2], "*/*");
  549. }
  550. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  551. // Common browser Accept header
  552. std::vector<std::string> browser_result;
  553. EXPECT_TRUE(
  554. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  555. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  556. browser_result));
  557. EXPECT_EQ(browser_result.size(), 6U);
  558. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  560. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  561. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  563. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  564. // API client header
  565. std::vector<std::string> api_result;
  566. EXPECT_TRUE(detail::parse_accept_header(
  567. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  568. api_result));
  569. EXPECT_EQ(api_result.size(), 3U);
  570. EXPECT_EQ(api_result[0], "application/json");
  571. EXPECT_EQ(api_result[1], "application/xml");
  572. EXPECT_EQ(api_result[2], "text/plain");
  573. }
  574. TEST(ParseAcceptHeaderTest, SpecialCases) {
  575. // Quality value with 3 decimal places
  576. std::vector<std::string> decimal_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  579. EXPECT_EQ(decimal_result.size(), 2U);
  580. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  581. EXPECT_EQ(decimal_result[1], "text/html");
  582. // Zero quality (should still be included but with lowest priority)
  583. std::vector<std::string> zero_q_result;
  584. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  585. zero_q_result));
  586. EXPECT_EQ(zero_q_result.size(), 2U);
  587. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  588. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  589. // No spaces around commas
  590. std::vector<std::string> no_space_result;
  591. EXPECT_TRUE(detail::parse_accept_header(
  592. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  593. no_space_result));
  594. EXPECT_EQ(no_space_result.size(), 3U);
  595. EXPECT_EQ(no_space_result[0], "text/html");
  596. EXPECT_EQ(no_space_result[1], "application/json");
  597. EXPECT_EQ(no_space_result[2], "text/plain");
  598. }
  599. TEST(ParseAcceptHeaderTest, InvalidCases) {
  600. std::vector<std::string> result;
  601. // Invalid quality value (> 1.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  604. // Invalid quality value (< 0.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  607. // Invalid quality value (not a number)
  608. EXPECT_FALSE(detail::parse_accept_header(
  609. "text/html;q=invalid,application/json", result));
  610. // Empty quality value
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("text/html;q=,application/json", result));
  613. // Invalid media type format (no slash and not wildcard)
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("invalidtype,application/json", result));
  616. // Empty media type
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  619. // Only commas
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  622. // Valid cases should still work
  623. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*/*");
  626. EXPECT_TRUE(detail::parse_accept_header("*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*");
  629. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "text/*");
  632. }
  633. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  634. Server svr;
  635. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  636. EXPECT_EQ(req.accept_content_types.size(), 3U);
  637. EXPECT_EQ(req.accept_content_types[0], "application/json");
  638. EXPECT_EQ(req.accept_content_types[1], "text/html");
  639. EXPECT_EQ(req.accept_content_types[2], "*/*");
  640. res.set_content("ok", "text/plain");
  641. });
  642. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  643. EXPECT_TRUE(false);
  644. res.set_content("bad request", "text/plain");
  645. });
  646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  647. auto se = detail::scope_exit([&] {
  648. svr.stop();
  649. listen_thread.join();
  650. ASSERT_FALSE(svr.is_running());
  651. });
  652. svr.wait_until_ready();
  653. Client cli("localhost", PORT);
  654. {
  655. auto res =
  656. cli.Get("/accept_ok",
  657. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ(StatusCode::OK_200, res->status);
  660. }
  661. {
  662. auto res = cli.Get("/accept_bad_request",
  663. {{"Accept", "text/html;q=abc,application/json"}});
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  666. }
  667. }
  668. TEST(DivideTest, DivideStringTests) {
  669. auto divide = [](const std::string &str, char d) {
  670. std::string lhs;
  671. std::string rhs;
  672. detail::divide(str, d,
  673. [&](const char *lhs_data, std::size_t lhs_size,
  674. const char *rhs_data, std::size_t rhs_size) {
  675. lhs.assign(lhs_data, lhs_size);
  676. rhs.assign(rhs_data, rhs_size);
  677. });
  678. return std::make_pair(std::move(lhs), std::move(rhs));
  679. };
  680. {
  681. const auto res = divide("", '=');
  682. EXPECT_EQ(res.first, "");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("=", '=');
  687. EXPECT_EQ(res.first, "");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide(" ", '=');
  692. EXPECT_EQ(res.first, " ");
  693. EXPECT_EQ(res.second, "");
  694. }
  695. {
  696. const auto res = divide("a", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "");
  699. }
  700. {
  701. const auto res = divide("a=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "");
  704. }
  705. {
  706. const auto res = divide("=b", '=');
  707. EXPECT_EQ(res.first, "");
  708. EXPECT_EQ(res.second, "b");
  709. }
  710. {
  711. const auto res = divide("a=b", '=');
  712. EXPECT_EQ(res.first, "a");
  713. EXPECT_EQ(res.second, "b");
  714. }
  715. {
  716. const auto res = divide("a=b=", '=');
  717. EXPECT_EQ(res.first, "a");
  718. EXPECT_EQ(res.second, "b=");
  719. }
  720. {
  721. const auto res = divide("a=b=c", '=');
  722. EXPECT_EQ(res.first, "a");
  723. EXPECT_EQ(res.second, "b=c");
  724. }
  725. }
  726. TEST(SplitTest, ParseQueryString) {
  727. string s = "key1=val1&key2=val2&key3=val3";
  728. Params dic;
  729. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  730. [&](const char *b, const char *e) {
  731. string key, val;
  732. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  733. if (key.empty()) {
  734. key.assign(b2, e2);
  735. } else {
  736. val.assign(b2, e2);
  737. }
  738. });
  739. dic.emplace(key, val);
  740. });
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. TEST(SplitTest, ParseInvalidQueryTests) {
  746. {
  747. string s = " ";
  748. Params dict;
  749. detail::parse_query_text(s, dict);
  750. EXPECT_TRUE(dict.empty());
  751. }
  752. {
  753. string s = " = =";
  754. Params dict;
  755. detail::parse_query_text(s, dict);
  756. EXPECT_TRUE(dict.empty());
  757. }
  758. }
  759. TEST(ParseQueryTest, ParseQueryString) {
  760. {
  761. std::string s = "key1=val1&key2=val2&key3=val3";
  762. Params dic;
  763. detail::parse_query_text(s, dic);
  764. EXPECT_EQ("val1", dic.find("key1")->second);
  765. EXPECT_EQ("val2", dic.find("key2")->second);
  766. EXPECT_EQ("val3", dic.find("key3")->second);
  767. }
  768. {
  769. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  770. Params dic;
  771. detail::parse_query_text(s, dic);
  772. EXPECT_EQ("", dic.find("key1")->second);
  773. EXPECT_EQ("val1", dic.find("key2")->second);
  774. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  775. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  776. }
  777. }
  778. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  779. Params dic;
  780. EXPECT_EQ(detail::params_to_query_str(dic), "");
  781. dic.emplace("key1", "val1");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  783. dic.emplace("key2", "val2");
  784. dic.emplace("key3", "val3");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  786. }
  787. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  788. string content_type = "multipart/form-data; boundary=something";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "something");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  795. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  796. string boundary;
  797. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  798. EXPECT_TRUE(ret);
  799. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  800. }
  801. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  802. string content_type =
  803. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  804. string boundary;
  805. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  806. EXPECT_TRUE(ret);
  807. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  808. }
  809. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  810. string content_type =
  811. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  812. string boundary;
  813. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  814. EXPECT_TRUE(ret);
  815. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  816. }
  817. TEST(GetHeaderValueTest, DefaultValue) {
  818. Headers headers = {{"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  820. EXPECT_STREQ("text/plain", val);
  821. }
  822. TEST(GetHeaderValueTest, DefaultValueInt) {
  823. Headers headers = {{"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularValue) {
  828. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  829. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  830. EXPECT_STREQ("text/html", val);
  831. }
  832. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  833. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  834. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  835. EXPECT_STREQ("text/html", val);
  836. }
  837. TEST(GetHeaderValueTest, SetContent) {
  838. Response res;
  839. res.set_content("html", "text/html");
  840. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  841. res.set_content("text", "text/plain");
  842. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  843. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  844. }
  845. TEST(GetHeaderValueTest, RegularValueInt) {
  846. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  847. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  848. EXPECT_EQ(100ull, val);
  849. }
  850. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  851. Headers headers = {{"Content-Length", "x"}};
  852. auto is_invalid_value = false;
  853. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  854. is_invalid_value);
  855. EXPECT_EQ(0ull, val);
  856. EXPECT_TRUE(is_invalid_value);
  857. }
  858. TEST(GetHeaderValueTest, Range) {
  859. {
  860. Headers headers = {make_range_header({{1, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{-1, 1}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=-1", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{1, 10}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=1-10", val);
  873. }
  874. {
  875. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  876. auto val = detail::get_header_value(headers, "Range", 0, 0);
  877. EXPECT_STREQ("bytes=1-10, 100-", val);
  878. }
  879. {
  880. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  881. auto val = detail::get_header_value(headers, "Range", 0, 0);
  882. EXPECT_STREQ("bytes=1-10, 100-200", val);
  883. }
  884. {
  885. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  886. auto val = detail::get_header_value(headers, "Range", 0, 0);
  887. EXPECT_STREQ("bytes=0-0, -1", val);
  888. }
  889. }
  890. TEST(ParseHeaderValueTest, Range) {
  891. {
  892. Ranges ranges;
  893. auto ret = detail::parse_range_header("bytes=1-", ranges);
  894. EXPECT_TRUE(ret);
  895. EXPECT_EQ(1u, ranges.size());
  896. EXPECT_EQ(1u, ranges[0].first);
  897. EXPECT_EQ(-1, ranges[0].second);
  898. }
  899. {
  900. Ranges ranges;
  901. auto ret = detail::parse_range_header("bytes=-1", ranges);
  902. EXPECT_TRUE(ret);
  903. EXPECT_EQ(1u, ranges.size());
  904. EXPECT_EQ(-1, ranges[0].first);
  905. EXPECT_EQ(1u, ranges[0].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  910. EXPECT_TRUE(ret);
  911. EXPECT_EQ(1u, ranges.size());
  912. EXPECT_EQ(1u, ranges[0].first);
  913. EXPECT_EQ(10u, ranges[0].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  918. EXPECT_FALSE(ret);
  919. }
  920. {
  921. Ranges ranges;
  922. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  923. EXPECT_TRUE(ret);
  924. EXPECT_EQ(2u, ranges.size());
  925. EXPECT_EQ(1u, ranges[0].first);
  926. EXPECT_EQ(10u, ranges[0].second);
  927. EXPECT_EQ(100u, ranges[1].first);
  928. EXPECT_EQ(-1, ranges[1].second);
  929. }
  930. {
  931. Ranges ranges;
  932. auto ret =
  933. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  934. EXPECT_TRUE(ret);
  935. EXPECT_EQ(3u, ranges.size());
  936. EXPECT_EQ(1u, ranges[0].first);
  937. EXPECT_EQ(10u, ranges[0].second);
  938. EXPECT_EQ(100u, ranges[1].first);
  939. EXPECT_EQ(200u, ranges[1].second);
  940. EXPECT_EQ(300u, ranges[2].first);
  941. EXPECT_EQ(400u, ranges[2].second);
  942. }
  943. {
  944. Ranges ranges;
  945. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  958. EXPECT_TRUE(ranges.empty());
  959. }
  960. }
  961. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  962. Request req;
  963. req.set_header("Accept-Encoding", "gzip");
  964. Response res;
  965. res.set_header("Content-Type", "text/plain");
  966. auto ret = detail::encoding_type(req, res);
  967. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #else
  970. EXPECT_TRUE(ret == detail::EncodingType::None);
  971. #endif
  972. }
  973. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  974. Request req;
  975. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  976. Response res;
  977. res.set_header("Content-Type", "text/plain");
  978. auto ret = detail::encoding_type(req, res);
  979. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  980. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  981. #elif CPPHTTPLIB_ZLIB_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  983. #elif CPPHTTPLIB_ZSTD_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  985. #else
  986. EXPECT_TRUE(ret == detail::EncodingType::None);
  987. #endif
  988. }
  989. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  990. Request req;
  991. req.set_header("Accept-Encoding",
  992. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  993. Response res;
  994. res.set_header("Content-Type", "text/plain");
  995. auto ret = detail::encoding_type(req, res);
  996. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  997. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  998. #elif CPPHTTPLIB_ZLIB_SUPPORT
  999. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1000. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(BufferStreamTest, read) {
  1007. detail::BufferStream strm1;
  1008. Stream &strm = strm1;
  1009. EXPECT_EQ(5, strm.write("hello"));
  1010. char buf[512];
  1011. EXPECT_EQ(2, strm.read(buf, 2));
  1012. EXPECT_EQ('h', buf[0]);
  1013. EXPECT_EQ('e', buf[1]);
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('l', buf[0]);
  1016. EXPECT_EQ('l', buf[1]);
  1017. EXPECT_EQ(1, strm.read(buf, 1));
  1018. EXPECT_EQ('o', buf[0]);
  1019. EXPECT_EQ(0, strm.read(buf, 1));
  1020. }
  1021. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1022. auto host = "www.httpwatch.com";
  1023. auto ip = hosted_at(host);
  1024. EXPECT_EQ("23.96.13.243", ip);
  1025. std::vector<std::string> addrs;
  1026. hosted_at(host, addrs);
  1027. EXPECT_EQ(1u, addrs.size());
  1028. }
  1029. #if 0 // It depends on each test environment...
  1030. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1031. auto host = "www.youtube.com";
  1032. std::vector<std::string> addrs;
  1033. hosted_at(host, addrs);
  1034. EXPECT_EQ(20u, addrs.size());
  1035. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1036. EXPECT_TRUE(it != addrs.end());
  1037. }
  1038. #endif
  1039. class ChunkedEncodingTest : public ::testing::Test {
  1040. protected:
  1041. ChunkedEncodingTest()
  1042. : cli_(HOST, PORT)
  1043. #ifdef CPPHTTPLIB_SSL_ENABLED
  1044. ,
  1045. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1046. #endif
  1047. {
  1048. cli_.set_connection_timeout(2);
  1049. #ifdef CPPHTTPLIB_SSL_ENABLED
  1050. cli_.enable_server_certificate_verification(false);
  1051. #endif
  1052. }
  1053. virtual void SetUp() {
  1054. read_file("./image.jpg", image_data_);
  1055. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1056. res.set_content("Hello World!", "text/plain");
  1057. });
  1058. svr_.Get(
  1059. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1060. res.set_chunked_content_provider(
  1061. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1062. size_t remaining = image_data_.size() - offset;
  1063. if (remaining == 0) {
  1064. sink.done();
  1065. } else {
  1066. constexpr size_t CHUNK_SIZE = 1024;
  1067. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1068. sink.write(&image_data_[offset], send_size);
  1069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1070. }
  1071. return true;
  1072. });
  1073. });
  1074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1075. svr_.wait_until_ready();
  1076. }
  1077. virtual void TearDown() {
  1078. svr_.stop();
  1079. if (!request_threads_.empty()) {
  1080. std::this_thread::sleep_for(std::chrono::seconds(1));
  1081. for (auto &t : request_threads_) {
  1082. t.join();
  1083. }
  1084. }
  1085. t_.join();
  1086. }
  1087. #ifdef CPPHTTPLIB_SSL_ENABLED
  1088. SSLClient cli_;
  1089. SSLServer svr_;
  1090. #else
  1091. Client cli_;
  1092. Server svr_;
  1093. #endif
  1094. thread t_;
  1095. std::vector<thread> request_threads_;
  1096. std::string image_data_;
  1097. };
  1098. TEST_F(ChunkedEncodingTest, NormalGet) {
  1099. auto res = cli_.Get("/chunked");
  1100. ASSERT_TRUE(res);
  1101. std::string out;
  1102. read_file("./image.jpg", out);
  1103. EXPECT_EQ(StatusCode::OK_200, res->status);
  1104. EXPECT_EQ(out, res->body);
  1105. }
  1106. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1107. std::string body;
  1108. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1109. body.append(data, data_length);
  1110. return true;
  1111. });
  1112. ASSERT_TRUE(res);
  1113. std::string out;
  1114. read_file("./image.jpg", out);
  1115. EXPECT_EQ(StatusCode::OK_200, res->status);
  1116. EXPECT_EQ(out, body);
  1117. }
  1118. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1119. std::string body;
  1120. auto res = cli_.Get(
  1121. "/chunked",
  1122. [&](const Response &response) {
  1123. EXPECT_EQ(StatusCode::OK_200, response.status);
  1124. return true;
  1125. },
  1126. [&](const char *data, size_t data_length) {
  1127. body.append(data, data_length);
  1128. return true;
  1129. });
  1130. ASSERT_TRUE(res);
  1131. std::string out;
  1132. read_file("./image.jpg", out);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. EXPECT_EQ(out, body);
  1135. }
  1136. TEST(RangeTest, FromHTTPBin_Online) {
  1137. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1138. auto host = "httpcan.org";
  1139. auto path = std::string{"/range/32"};
  1140. #else
  1141. auto host = "nghttp2.org";
  1142. auto path = std::string{"/httpbin/range/32"};
  1143. #endif
  1144. #ifdef CPPHTTPLIB_SSL_ENABLED
  1145. auto port = 443;
  1146. SSLClient cli(host, port);
  1147. #else
  1148. auto port = 80;
  1149. Client cli(host, port);
  1150. #endif
  1151. cli.set_connection_timeout(5);
  1152. {
  1153. auto res = cli.Get(path);
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1156. EXPECT_EQ(StatusCode::OK_200, res->status);
  1157. }
  1158. {
  1159. Headers headers = {make_range_header({{1, -1}})};
  1160. auto res = cli.Get(path, headers);
  1161. ASSERT_TRUE(res);
  1162. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1164. }
  1165. {
  1166. Headers headers = {make_range_header({{1, 10}})};
  1167. auto res = cli.Get(path, headers);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ("bcdefghijk", res->body);
  1170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1171. }
  1172. {
  1173. Headers headers = {make_range_header({{0, 31}})};
  1174. auto res = cli.Get(path, headers);
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1177. EXPECT_EQ(StatusCode::OK_200, res->status);
  1178. }
  1179. {
  1180. Headers headers = {make_range_header({{0, -1}})};
  1181. auto res = cli.Get(path, headers);
  1182. ASSERT_TRUE(res);
  1183. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1184. EXPECT_EQ(StatusCode::OK_200, res->status);
  1185. }
  1186. {
  1187. Headers headers = {make_range_header({{0, 32}})};
  1188. auto res = cli.Get(path, headers);
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1191. }
  1192. }
  1193. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1194. auto host = "unresolvableaddress.local";
  1195. auto path = std::string{"/"};
  1196. #ifdef CPPHTTPLIB_SSL_ENABLED
  1197. auto port = 443;
  1198. SSLClient cli(host, port);
  1199. #else
  1200. auto port = 80;
  1201. Client cli(host, port);
  1202. #endif
  1203. cli.set_connection_timeout(1);
  1204. {
  1205. auto res = cli.Get(path);
  1206. ASSERT_FALSE(res);
  1207. }
  1208. std::this_thread::sleep_for(std::chrono::seconds(8));
  1209. }
  1210. TEST(ConnectionErrorTest, InvalidHost) {
  1211. auto host = "-abcde.com";
  1212. #ifdef CPPHTTPLIB_SSL_ENABLED
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(2));
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(ConnectionErrorTest, InvalidHost2) {
  1225. auto host = "httpcan.org/";
  1226. #ifdef CPPHTTPLIB_SSL_ENABLED
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_connection_timeout(std::chrono::seconds(2));
  1232. auto res = cli.Get("/");
  1233. ASSERT_TRUE(!res);
  1234. EXPECT_EQ(Error::Connection, res.error());
  1235. }
  1236. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1237. auto host = "httpcan.org/";
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. stringstream s;
  1247. s << "error code: " << res.error();
  1248. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1249. }
  1250. TEST(ConnectionErrorTest, InvalidPort) {
  1251. auto host = "localhost";
  1252. auto port = 44380;
  1253. #ifdef CPPHTTPLIB_SSL_ENABLED
  1254. SSLClient cli(host, port);
  1255. #else
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. auto res = cli.Get("/");
  1260. ASSERT_TRUE(!res);
  1261. EXPECT_TRUE(Error::Connection == res.error() ||
  1262. Error::ConnectionTimeout == res.error());
  1263. }
  1264. TEST(ConnectionErrorTest, Timeout_Online) {
  1265. auto host = "google.com";
  1266. #ifdef CPPHTTPLIB_SSL_ENABLED
  1267. auto port = 44380;
  1268. SSLClient cli(host, port);
  1269. #else
  1270. auto port = 8080;
  1271. Client cli(host, port);
  1272. #endif
  1273. cli.set_connection_timeout(std::chrono::seconds(2));
  1274. // only probe one address type so that the error reason
  1275. // correlates to the timed-out IPv4, not the unsupported
  1276. // IPv6 connection attempt
  1277. cli.set_address_family(AF_INET);
  1278. auto res = cli.Get("/");
  1279. ASSERT_TRUE(!res);
  1280. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1281. }
  1282. TEST(CancelTest, NoCancel_Online) {
  1283. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1284. auto host = "httpcan.org";
  1285. auto path = std::string{"/range/32"};
  1286. #else
  1287. auto host = "nghttp2.org";
  1288. auto path = std::string{"/httpbin/range/32"};
  1289. #endif
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. auto port = 443;
  1292. SSLClient cli(host, port);
  1293. #else
  1294. auto port = 80;
  1295. Client cli(host, port);
  1296. #endif
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1301. EXPECT_EQ(StatusCode::OK_200, res->status);
  1302. }
  1303. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpcan.org";
  1306. auto path = std::string{"/range/32"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/range/32"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_SSL_ENABLED
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1319. cli.set_connection_timeout(std::chrono::seconds(5));
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, WithCancelLargePayload_Online) {
  1324. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1325. auto host = "httpcan.org";
  1326. auto path = std::string{"/range/65536"};
  1327. #else
  1328. auto host = "nghttp2.org";
  1329. auto path = std::string{"/httpbin/range/65536"};
  1330. #endif
  1331. #ifdef CPPHTTPLIB_SSL_ENABLED
  1332. auto port = 443;
  1333. SSLClient cli(host, port);
  1334. #else
  1335. auto port = 80;
  1336. Client cli(host, port);
  1337. #endif
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. uint32_t count = 0;
  1340. auto res =
  1341. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, NoCancelPost) {
  1346. Server svr;
  1347. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content("Hello World!", "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return true; });
  1362. ASSERT_TRUE(res);
  1363. EXPECT_EQ("Hello World!", res->body);
  1364. EXPECT_EQ(StatusCode::OK_200, res->status);
  1365. }
  1366. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1367. Server svr;
  1368. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1369. res.set_content("Hello World!", "text/plain");
  1370. });
  1371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1372. auto se = detail::scope_exit([&] {
  1373. svr.stop();
  1374. thread.join();
  1375. ASSERT_FALSE(svr.is_running());
  1376. });
  1377. svr.wait_until_ready();
  1378. Client cli(HOST, PORT);
  1379. cli.set_connection_timeout(std::chrono::seconds(5));
  1380. auto res =
  1381. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1382. "application/json", [](uint64_t, uint64_t) { return false; });
  1383. ASSERT_TRUE(!res);
  1384. EXPECT_EQ(Error::Canceled, res.error());
  1385. }
  1386. TEST(CancelTest, WithCancelLargePayloadPost) {
  1387. Server svr;
  1388. svr.set_payload_max_length(200 * 1024 * 1024);
  1389. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content(LARGE_DATA, "text/plain");
  1391. });
  1392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1393. auto se = detail::scope_exit([&] {
  1394. svr.stop();
  1395. thread.join();
  1396. ASSERT_FALSE(svr.is_running());
  1397. });
  1398. svr.wait_until_ready();
  1399. Client cli(HOST, PORT);
  1400. cli.set_payload_max_length(200 * 1024 * 1024);
  1401. cli.set_connection_timeout(std::chrono::seconds(5));
  1402. auto res =
  1403. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1404. "application/json", [](uint64_t, uint64_t) { return false; });
  1405. ASSERT_TRUE(!res);
  1406. EXPECT_EQ(Error::Canceled, res.error());
  1407. }
  1408. TEST(CancelTest, NoCancelPut) {
  1409. Server svr;
  1410. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1411. res.set_content("Hello World!", "text/plain");
  1412. });
  1413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. thread.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. Client cli(HOST, PORT);
  1421. cli.set_connection_timeout(std::chrono::seconds(5));
  1422. auto res =
  1423. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1424. "application/json", [](uint64_t, uint64_t) { return true; });
  1425. ASSERT_TRUE(res);
  1426. EXPECT_EQ("Hello World!", res->body);
  1427. EXPECT_EQ(StatusCode::OK_200, res->status);
  1428. }
  1429. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1430. Server svr;
  1431. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("Hello World!", "text/plain");
  1433. });
  1434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. thread.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. Client cli(HOST, PORT);
  1442. cli.set_connection_timeout(std::chrono::seconds(5));
  1443. auto res =
  1444. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1445. "application/json", [](uint64_t, uint64_t) { return false; });
  1446. ASSERT_TRUE(!res);
  1447. EXPECT_EQ(Error::Canceled, res.error());
  1448. }
  1449. TEST(CancelTest, WithCancelLargePayloadPut) {
  1450. Server svr;
  1451. svr.set_payload_max_length(200 * 1024 * 1024);
  1452. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_payload_max_length(200 * 1024 * 1024);
  1464. cli.set_connection_timeout(std::chrono::seconds(5));
  1465. auto res =
  1466. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1467. "application/json", [](uint64_t, uint64_t) { return false; });
  1468. ASSERT_TRUE(!res);
  1469. EXPECT_EQ(Error::Canceled, res.error());
  1470. }
  1471. TEST(CancelTest, NoCancelPatch) {
  1472. Server svr;
  1473. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1474. res.set_content("Hello World!", "text/plain");
  1475. });
  1476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. thread.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. Client cli(HOST, PORT);
  1484. cli.set_connection_timeout(std::chrono::seconds(5));
  1485. auto res =
  1486. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1487. "application/json", [](uint64_t, uint64_t) { return true; });
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("Hello World!", res->body);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. }
  1492. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1493. Server svr;
  1494. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1495. res.set_content("Hello World!", "text/plain");
  1496. });
  1497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1498. auto se = detail::scope_exit([&] {
  1499. svr.stop();
  1500. thread.join();
  1501. ASSERT_FALSE(svr.is_running());
  1502. });
  1503. svr.wait_until_ready();
  1504. Client cli(HOST, PORT);
  1505. cli.set_connection_timeout(std::chrono::seconds(5));
  1506. auto res =
  1507. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1508. "application/json", [](uint64_t, uint64_t) { return false; });
  1509. ASSERT_TRUE(!res);
  1510. EXPECT_EQ(Error::Canceled, res.error());
  1511. }
  1512. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1513. Server svr;
  1514. svr.set_payload_max_length(200 * 1024 * 1024);
  1515. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content(LARGE_DATA, "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_payload_max_length(200 * 1024 * 1024);
  1527. cli.set_connection_timeout(std::chrono::seconds(5));
  1528. auto res =
  1529. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1530. "application/json", [](uint64_t, uint64_t) { return false; });
  1531. ASSERT_TRUE(!res);
  1532. EXPECT_EQ(Error::Canceled, res.error());
  1533. }
  1534. TEST(CancelTest, NoCancelDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return true; });
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ("Hello World!", res->body);
  1553. EXPECT_EQ(StatusCode::OK_200, res->status);
  1554. }
  1555. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1556. Server svr;
  1557. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content("Hello World!", "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_connection_timeout(std::chrono::seconds(5));
  1569. auto res =
  1570. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1571. "application/json", [](uint64_t, uint64_t) { return false; });
  1572. ASSERT_TRUE(!res);
  1573. EXPECT_EQ(Error::Canceled, res.error());
  1574. }
  1575. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1576. Server svr;
  1577. svr.set_payload_max_length(200 * 1024 * 1024);
  1578. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content(LARGE_DATA, "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_payload_max_length(200 * 1024 * 1024);
  1590. cli.set_connection_timeout(std::chrono::seconds(5));
  1591. auto res =
  1592. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1593. "application/json", [](uint64_t, uint64_t) { return false; });
  1594. ASSERT_TRUE(!res);
  1595. EXPECT_EQ(Error::Canceled, res.error());
  1596. }
  1597. static std::string remove_whitespace(const std::string &input) {
  1598. std::string output;
  1599. output.reserve(input.size());
  1600. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1601. [](unsigned char c) { return !std::isspace(c); });
  1602. return output;
  1603. }
  1604. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1605. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1606. auto host = "httpcan.org";
  1607. auto path = std::string{"/basic-auth/hello/world"};
  1608. #else
  1609. auto host = "nghttp2.org";
  1610. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1611. #endif
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 443;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 80;
  1617. Client cli(host, port);
  1618. #endif
  1619. {
  1620. auto res = cli.Get(path);
  1621. ASSERT_TRUE(res);
  1622. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1623. }
  1624. {
  1625. auto res =
  1626. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. {
  1633. cli.set_basic_auth("hello", "world");
  1634. auto res = cli.Get(path);
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1637. remove_whitespace(res->body));
  1638. EXPECT_EQ(StatusCode::OK_200, res->status);
  1639. }
  1640. {
  1641. cli.set_basic_auth("hello", "bad");
  1642. auto res = cli.Get(path);
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1645. }
  1646. {
  1647. cli.set_basic_auth("bad", "world");
  1648. auto res = cli.Get(path);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1651. }
  1652. }
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. auto host = "httpcan.org";
  1657. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1658. auto paths = std::vector<std::string>{
  1659. "/digest-auth/auth/hello/world/MD5",
  1660. "/digest-auth/auth/hello/world/SHA-256",
  1661. "/digest-auth/auth/hello/world/SHA-512",
  1662. };
  1663. #else
  1664. auto host = "nghttp2.org";
  1665. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1666. auto paths = std::vector<std::string>{
  1667. "/httpbin/digest-auth/auth/hello/world/MD5",
  1668. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1669. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1670. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1671. };
  1672. #endif
  1673. auto port = 443;
  1674. SSLClient cli(host, port);
  1675. {
  1676. auto res = cli.Get(unauth_path);
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1679. }
  1680. {
  1681. cli.set_digest_auth("hello", "world");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1686. std::string algo(path.substr(path.rfind('/') + 1));
  1687. EXPECT_EQ(
  1688. remove_whitespace("{\"algorithm\":\"" + algo +
  1689. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1690. remove_whitespace(res->body));
  1691. #else
  1692. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1693. remove_whitespace(res->body));
  1694. #endif
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1698. cli.set_digest_auth("hello", "bad");
  1699. for (const auto &path : paths) {
  1700. auto res = cli.Get(path.c_str());
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. #endif
  1705. }
  1706. }
  1707. #endif
  1708. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1709. auto host = "google.com";
  1710. auto another_host = "example.com";
  1711. auto wrong_ip = "0.0.0.0";
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. SSLClient cli(host);
  1714. #else
  1715. Client cli(host);
  1716. #endif
  1717. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1718. auto res = cli.Get("/");
  1719. ASSERT_TRUE(res);
  1720. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1721. }
  1722. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1723. auto host = "google.com";
  1724. auto wrong_ip = "0.0.0.0";
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. SSLClient cli(host);
  1727. #else
  1728. Client cli(host);
  1729. #endif
  1730. cli.set_hostname_addr_map({{host, wrong_ip}});
  1731. auto res = cli.Get("/");
  1732. ASSERT_TRUE(!res);
  1733. EXPECT_EQ(Error::Connection, res.error());
  1734. }
  1735. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1736. auto host = "nghttp2.org";
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. SSLClient cli(host);
  1739. #else
  1740. Client cli(host);
  1741. #endif
  1742. cli.set_follow_location(true);
  1743. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(RedirectTest, Redirect_Online) {
  1748. auto host = "nghttp2.org";
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. SSLClient cli(host);
  1751. #else
  1752. Client cli(host);
  1753. #endif
  1754. cli.set_follow_location(true);
  1755. auto res = cli.Get("/httpbin/redirect/3");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::OK_200, res->status);
  1758. }
  1759. TEST(RelativeRedirectTest, Redirect_Online) {
  1760. auto host = "nghttp2.org";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_follow_location(true);
  1767. auto res = cli.Get("/httpbin/relative-redirect/3");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. }
  1771. TEST(TooManyRedirectTest, Redirect_Online) {
  1772. auto host = "nghttp2.org";
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. SSLClient cli(host);
  1775. #else
  1776. Client cli(host);
  1777. #endif
  1778. cli.set_follow_location(true);
  1779. auto res = cli.Get("/httpbin/redirect/21");
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1782. }
  1783. #ifdef CPPHTTPLIB_SSL_ENABLED
  1784. TEST(YahooRedirectTest, Redirect_Online) {
  1785. Client cli("yahoo.com");
  1786. auto res = cli.Get("/");
  1787. ASSERT_TRUE(res);
  1788. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1789. cli.set_follow_location(true);
  1790. res = cli.Get("/");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1794. }
  1795. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1796. #define REDIR_HOST "httpbingo.org"
  1797. #define REDIR_PATH "/redirect-to"
  1798. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1799. SSLClient cli(REDIR_HOST);
  1800. cli.set_follow_location(true);
  1801. auto res =
  1802. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. }
  1806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1807. SSLClient cli(REDIR_HOST);
  1808. cli.set_follow_location(true);
  1809. Params params;
  1810. params.emplace("url", "http://example.com");
  1811. params.emplace("status_code", "302");
  1812. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::OK_200, res->status);
  1815. }
  1816. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1817. SSLClient cli(REDIR_HOST);
  1818. cli.set_follow_location(true);
  1819. Params params;
  1820. params.emplace("url", "http://example.com");
  1821. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(UrlWithSpace, Redirect_Online) {
  1826. SSLClient cli("edge.forgecdn.net");
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1829. ASSERT_TRUE(res);
  1830. EXPECT_EQ(StatusCode::OK_200, res->status);
  1831. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1832. }
  1833. #endif
  1834. #if !defined(_WIN32) && !defined(_WIN64)
  1835. TEST(ReceiveSignals, Signal) {
  1836. auto setupSignalHandlers = []() {
  1837. struct sigaction act;
  1838. sigemptyset(&act.sa_mask);
  1839. act.sa_flags = SA_SIGINFO;
  1840. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1841. switch (sig) {
  1842. case SIGINT:
  1843. default: break;
  1844. }
  1845. };
  1846. ::sigaction(SIGINT, &act, nullptr);
  1847. };
  1848. Server svr;
  1849. int port = 0;
  1850. auto thread = std::thread([&]() {
  1851. setupSignalHandlers();
  1852. port = svr.bind_to_any_port(HOST);
  1853. svr.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr.stop();
  1857. thread.join();
  1858. ASSERT_FALSE(svr.is_running());
  1859. });
  1860. svr.wait_until_ready();
  1861. ASSERT_TRUE(svr.is_running());
  1862. pthread_kill(thread.native_handle(), SIGINT);
  1863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1864. ASSERT_TRUE(svr.is_running());
  1865. }
  1866. #endif
  1867. TEST(RedirectToDifferentPort, Redirect) {
  1868. Server svr1;
  1869. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content("Hello World!", "text/plain");
  1871. });
  1872. int svr1_port = 0;
  1873. auto thread1 = std::thread([&]() {
  1874. svr1_port = svr1.bind_to_any_port(HOST);
  1875. svr1.listen_after_bind();
  1876. });
  1877. Server svr2;
  1878. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1880. });
  1881. int svr2_port = 0;
  1882. auto thread2 = std::thread([&]() {
  1883. svr2_port = svr2.bind_to_any_port(HOST);
  1884. svr2.listen_after_bind();
  1885. });
  1886. auto se = detail::scope_exit([&] {
  1887. svr2.stop();
  1888. thread2.join();
  1889. svr1.stop();
  1890. thread1.join();
  1891. ASSERT_FALSE(svr2.is_running());
  1892. ASSERT_FALSE(svr1.is_running());
  1893. });
  1894. svr1.wait_until_ready();
  1895. svr2.wait_until_ready();
  1896. Client cli("localhost", svr2_port);
  1897. cli.set_follow_location(true);
  1898. auto res = cli.Get("/2");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. EXPECT_EQ("Hello World!", res->body);
  1902. }
  1903. TEST(RedirectFromPageWithContent, Redirect) {
  1904. Server svr;
  1905. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1906. res.set_content("___", "text/plain");
  1907. res.set_redirect("/2");
  1908. });
  1909. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. th.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. {
  1920. Client cli("localhost", PORT);
  1921. cli.set_follow_location(true);
  1922. std::string body;
  1923. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1924. body.append(data, data_length);
  1925. return true;
  1926. });
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::OK_200, res->status);
  1929. EXPECT_EQ("Hello World!", body);
  1930. }
  1931. {
  1932. Client cli("localhost", PORT);
  1933. std::string body;
  1934. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1935. body.append(data, data_length);
  1936. return true;
  1937. });
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(StatusCode::Found_302, res->status);
  1940. EXPECT_EQ("___", body);
  1941. }
  1942. }
  1943. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1944. Server svr;
  1945. auto port_str = std::to_string(PORT);
  1946. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1947. auto expected_host = "[::1]:" + port_str;
  1948. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1949. res.set_content("___", "text/plain");
  1950. // res.set_redirect("/2");
  1951. res.set_redirect(redirect_url);
  1952. });
  1953. svr.Get("/2", [&](const Request &req, Response &res) {
  1954. auto host_header = req.headers.find("Host");
  1955. ASSERT_TRUE(host_header != req.headers.end());
  1956. EXPECT_EQ(expected_host, host_header->second);
  1957. res.set_content("Hello World!", "text/plain");
  1958. });
  1959. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. th.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1966. // actually starts anything, so the condition !svr.is_running() will
  1967. // always remain true, and the loop never stops.
  1968. // This basically counts how many milliseconds have passed since the
  1969. // call to svr.listen(), and if after 5 seconds nothing started yet
  1970. // aborts the test.
  1971. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1972. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1973. ASSERT_LT(milliseconds, 5000U);
  1974. }
  1975. {
  1976. Client cli("::1", PORT);
  1977. cli.set_follow_location(true);
  1978. std::string body;
  1979. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1980. body.append(data, data_length);
  1981. return true;
  1982. });
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. EXPECT_EQ("Hello World!", body);
  1986. }
  1987. {
  1988. Client cli("::1", PORT);
  1989. std::string body;
  1990. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1991. body.append(data, data_length);
  1992. return true;
  1993. });
  1994. ASSERT_TRUE(res);
  1995. EXPECT_EQ(StatusCode::Found_302, res->status);
  1996. EXPECT_EQ("___", body);
  1997. }
  1998. }
  1999. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2000. Server svr;
  2001. svr.Get("/foo", [](const Request &req, Response &res) {
  2002. auto a = req.params.find("a");
  2003. if (a != req.params.end()) {
  2004. res.set_content((*a).second, "text/plain");
  2005. res.status = StatusCode::OK_200;
  2006. } else {
  2007. res.status = StatusCode::BadRequest_400;
  2008. }
  2009. });
  2010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2011. auto se = detail::scope_exit([&] {
  2012. svr.stop();
  2013. thread.join();
  2014. ASSERT_FALSE(svr.is_running());
  2015. });
  2016. svr.wait_until_ready();
  2017. {
  2018. Client cli(HOST, PORT);
  2019. cli.set_path_encode(false);
  2020. auto res = cli.Get("/foo?a=explicitly+encoded");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. // This expects it back with a space, as the `+` won't have been
  2024. // url-encoded, and server-side the params get decoded turning `+`
  2025. // into spaces.
  2026. EXPECT_EQ("explicitly encoded", res->body);
  2027. }
  2028. }
  2029. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2030. Server svr;
  2031. svr.Get("/", [](const Request &req, Response &) {
  2032. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli(HOST, PORT);
  2043. cli.set_path_encode(false);
  2044. auto res = cli.Get("/?something=%0A");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. }
  2048. }
  2049. TEST(BindServerTest, DISABLED_BindDualStack) {
  2050. Server svr;
  2051. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2052. res.set_content("Hello World!", "text/plain");
  2053. });
  2054. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. {
  2062. Client cli("127.0.0.1", PORT);
  2063. auto res = cli.Get("/1");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(StatusCode::OK_200, res->status);
  2066. EXPECT_EQ("Hello World!", res->body);
  2067. }
  2068. {
  2069. Client cli("::1", PORT);
  2070. auto res = cli.Get("/1");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::OK_200, res->status);
  2073. EXPECT_EQ("Hello World!", res->body);
  2074. }
  2075. }
  2076. TEST(BindServerTest, BindAndListenSeparately) {
  2077. Server svr;
  2078. int port = svr.bind_to_any_port("0.0.0.0");
  2079. ASSERT_TRUE(svr.is_valid());
  2080. ASSERT_TRUE(port > 0);
  2081. svr.stop();
  2082. }
  2083. #ifdef CPPHTTPLIB_SSL_ENABLED
  2084. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2086. CLIENT_CA_CERT_DIR);
  2087. int port = svr.bind_to_any_port("0.0.0.0");
  2088. ASSERT_TRUE(svr.is_valid());
  2089. ASSERT_TRUE(port > 0);
  2090. svr.stop();
  2091. }
  2092. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2093. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2094. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2095. int port = svr.bind_to_any_port("0.0.0.0");
  2096. ASSERT_TRUE(svr.is_valid());
  2097. ASSERT_TRUE(port > 0);
  2098. svr.stop();
  2099. }
  2100. TEST(BindServerTest, UpdateCertsPem) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. // Read PEM files
  2106. std::string cert_pem, key_pem, ca_pem;
  2107. read_file(SERVER_CERT_FILE, cert_pem);
  2108. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2109. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2110. // Update server certificates using PEM API
  2111. ASSERT_TRUE(
  2112. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2113. ASSERT_TRUE(svr.is_valid());
  2114. svr.stop();
  2115. }
  2116. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2117. // Start server with client CA (enables client auth)
  2118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2119. ASSERT_TRUE(svr.is_valid());
  2120. bool handler_called = false;
  2121. svr.Get("/test", [&](const Request &req, Response &res) {
  2122. handler_called = true;
  2123. // Verify client certificate is present
  2124. auto cert = req.peer_cert();
  2125. EXPECT_TRUE(static_cast<bool>(cert));
  2126. res.set_content("ok", "text/plain");
  2127. });
  2128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2129. auto se = detail::scope_exit([&] {
  2130. svr.stop();
  2131. t.join();
  2132. ASSERT_FALSE(svr.is_running());
  2133. });
  2134. svr.wait_until_ready();
  2135. // Read PEM files
  2136. std::string cert_pem, key_pem, ca_pem;
  2137. read_file(SERVER_CERT_FILE, cert_pem);
  2138. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2139. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2140. // Update server certificates and client CA using PEM API while server running
  2141. ASSERT_TRUE(
  2142. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2143. // Connect with client certificate
  2144. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2145. cli.enable_server_certificate_verification(false);
  2146. cli.set_connection_timeout(30);
  2147. auto res = cli.Get("/test");
  2148. ASSERT_TRUE(res);
  2149. ASSERT_EQ(StatusCode::OK_200, res->status);
  2150. ASSERT_TRUE(handler_called);
  2151. EXPECT_EQ("ok", res->body);
  2152. }
  2153. #endif
  2154. TEST(ErrorHandlerTest, ContentLength) {
  2155. Server svr;
  2156. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2157. res.status = StatusCode::OK_200;
  2158. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2159. "text/html"); // <= Content-Length still 13
  2160. });
  2161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2162. res.set_content("Hello World!\n", "text/plain");
  2163. res.status = 524;
  2164. });
  2165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2166. auto se = detail::scope_exit([&] {
  2167. svr.stop();
  2168. thread.join();
  2169. ASSERT_FALSE(svr.is_running());
  2170. });
  2171. svr.wait_until_ready();
  2172. {
  2173. Client cli(HOST, PORT);
  2174. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::OK_200, res->status);
  2177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2178. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2180. }
  2181. }
  2182. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2183. TEST(ExceptionTest, WithoutExceptionHandler) {
  2184. Server svr;
  2185. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2186. throw std::runtime_error("exception...");
  2187. });
  2188. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception\r\n...");
  2190. });
  2191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. listen_thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli("localhost", PORT);
  2199. {
  2200. auto res = cli.Get("/exception");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2203. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2204. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2205. }
  2206. {
  2207. auto res = cli.Get("/unknown");
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2210. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2211. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2212. }
  2213. }
  2214. TEST(ExceptionTest, WithExceptionHandler) {
  2215. Server svr;
  2216. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2217. std::exception_ptr ep) {
  2218. EXPECT_FALSE(ep == nullptr);
  2219. try {
  2220. std::rethrow_exception(ep);
  2221. } catch (std::exception &e) {
  2222. EXPECT_EQ("abc", std::string(e.what()));
  2223. } catch (...) {}
  2224. res.status = StatusCode::InternalServerError_500;
  2225. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2226. "text/html"); // <= Content-Length still 13 at this point
  2227. });
  2228. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!\n", "text/plain");
  2230. throw std::runtime_error("abc");
  2231. });
  2232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2233. auto se = detail::scope_exit([&] {
  2234. svr.stop();
  2235. thread.join();
  2236. ASSERT_FALSE(svr.is_running());
  2237. });
  2238. svr.wait_until_ready();
  2239. for (size_t i = 0; i < 10; i++) {
  2240. Client cli(HOST, PORT);
  2241. for (size_t j = 0; j < 100; j++) {
  2242. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2243. ASSERT_TRUE(res);
  2244. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2245. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2246. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2248. }
  2249. cli.set_keep_alive(true);
  2250. for (size_t j = 0; j < 100; j++) {
  2251. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2254. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2255. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2256. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2257. }
  2258. }
  2259. }
  2260. TEST(ExceptionTest, AndErrorHandler) {
  2261. Server svr;
  2262. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2263. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2264. });
  2265. svr.set_exception_handler(
  2266. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2267. EXPECT_FALSE(ep == nullptr);
  2268. try {
  2269. std::rethrow_exception(ep);
  2270. } catch (std::exception &e) {
  2271. res.set_content(e.what(), "text/html");
  2272. } catch (...) {}
  2273. res.status = StatusCode::InternalServerError_500;
  2274. });
  2275. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2276. throw std::runtime_error("EXCEPTION");
  2277. });
  2278. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2279. res.set_content("ERROR", "text/html");
  2280. res.status = StatusCode::InternalServerError_500;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. Client cli(HOST, PORT);
  2290. {
  2291. auto res = cli.Get("/exception");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("EXCEPTION", res->body);
  2295. }
  2296. {
  2297. auto res = cli.Get("/error");
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2300. EXPECT_EQ("ERROR", res->body);
  2301. }
  2302. {
  2303. auto res = cli.Get("/invalid");
  2304. ASSERT_TRUE(res);
  2305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2306. EXPECT_EQ("NOT_FOUND", res->body);
  2307. }
  2308. }
  2309. #endif
  2310. TEST(NoContentTest, ContentLength) {
  2311. Server svr;
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.status = StatusCode::NoContent_204;
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. Client cli(HOST, PORT);
  2324. auto res = cli.Get("/hi");
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2327. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2328. }
  2329. }
  2330. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2333. ASSERT_TRUE(svr.is_valid());
  2334. #else
  2335. Server svr;
  2336. #endif
  2337. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2338. if (req.path == "/routing_handler") {
  2339. res.set_header("PRE_ROUTING", "on");
  2340. res.set_content("Routing Handler", "text/plain");
  2341. return httplib::Server::HandlerResponse::Handled;
  2342. }
  2343. return httplib::Server::HandlerResponse::Unhandled;
  2344. });
  2345. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2346. res.set_content("Error", "text/html");
  2347. });
  2348. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2349. if (req.path == "/routing_handler") {
  2350. res.set_header("POST_ROUTING", "on");
  2351. }
  2352. });
  2353. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2354. res.set_content("Hello World!\n", "text/plain");
  2355. });
  2356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2357. auto se = detail::scope_exit([&] {
  2358. svr.stop();
  2359. thread.join();
  2360. ASSERT_FALSE(svr.is_running());
  2361. });
  2362. svr.wait_until_ready();
  2363. {
  2364. #ifdef CPPHTTPLIB_SSL_ENABLED
  2365. SSLClient cli(HOST, PORT);
  2366. cli.enable_server_certificate_verification(false);
  2367. #else
  2368. Client cli(HOST, PORT);
  2369. #endif
  2370. auto res = cli.Get("/routing_handler");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ("Routing Handler", res->body);
  2374. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2375. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2376. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2377. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2378. }
  2379. {
  2380. #ifdef CPPHTTPLIB_SSL_ENABLED
  2381. SSLClient cli(HOST, PORT);
  2382. cli.enable_server_certificate_verification(false);
  2383. #else
  2384. Client cli(HOST, PORT);
  2385. #endif
  2386. auto res = cli.Get("/hi");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(StatusCode::OK_200, res->status);
  2389. EXPECT_EQ("Hello World!\n", res->body);
  2390. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2391. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2392. }
  2393. {
  2394. #ifdef CPPHTTPLIB_SSL_ENABLED
  2395. SSLClient cli(HOST, PORT);
  2396. cli.enable_server_certificate_verification(false);
  2397. #else
  2398. Client cli(HOST, PORT);
  2399. #endif
  2400. auto res = cli.Get("/aaa");
  2401. ASSERT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2403. EXPECT_EQ("Error", res->body);
  2404. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2405. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2406. }
  2407. }
  2408. TEST(RequestHandlerTest, PreRequestHandler) {
  2409. auto route_path = "/user/:user";
  2410. Server svr;
  2411. svr.Get("/hi", [](const Request &, Response &res) {
  2412. res.set_content("hi", "text/plain");
  2413. });
  2414. svr.Get(route_path, [](const Request &req, Response &res) {
  2415. res.set_content(req.path_params.at("user"), "text/plain");
  2416. });
  2417. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2418. if (req.matched_route == route_path) {
  2419. auto user = req.path_params.at("user");
  2420. if (user != "john") {
  2421. res.status = StatusCode::Forbidden_403;
  2422. res.set_content("error", "text/html");
  2423. return Server::HandlerResponse::Handled;
  2424. }
  2425. }
  2426. return Server::HandlerResponse::Unhandled;
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, PORT);
  2436. {
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("hi", res->body);
  2441. }
  2442. {
  2443. auto res = cli.Get("/user/john");
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(StatusCode::OK_200, res->status);
  2446. EXPECT_EQ("john", res->body);
  2447. }
  2448. {
  2449. auto res = cli.Get("/user/invalid-user");
  2450. ASSERT_TRUE(res);
  2451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2452. EXPECT_EQ("error", res->body);
  2453. }
  2454. }
  2455. TEST(InvalidFormatTest, StatusCode) {
  2456. Server svr;
  2457. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2458. res.set_content("Hello World!\n", "text/plain");
  2459. res.status = 9999; // Status should be a three-digit code...
  2460. });
  2461. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2462. auto se = detail::scope_exit([&] {
  2463. svr.stop();
  2464. thread.join();
  2465. ASSERT_FALSE(svr.is_running());
  2466. });
  2467. svr.wait_until_ready();
  2468. {
  2469. Client cli(HOST, PORT);
  2470. auto res = cli.Get("/hi");
  2471. ASSERT_FALSE(res);
  2472. }
  2473. }
  2474. TEST(URLFragmentTest, WithFragment) {
  2475. Server svr;
  2476. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2477. EXPECT_TRUE(req.target == "/hi");
  2478. });
  2479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2480. auto se = detail::scope_exit([&] {
  2481. svr.stop();
  2482. thread.join();
  2483. ASSERT_FALSE(svr.is_running());
  2484. });
  2485. svr.wait_until_ready();
  2486. {
  2487. Client cli(HOST, PORT);
  2488. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2489. EXPECT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. res = cli.Get("/hi%23key1=val1=key2=val2");
  2492. EXPECT_TRUE(res);
  2493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2494. }
  2495. }
  2496. TEST(HeaderWriter, SetHeaderWriter) {
  2497. Server svr;
  2498. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2499. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2500. return detail::write_headers(strm, hdrs);
  2501. });
  2502. svr.Get("/hi", [](const Request &req, Response &res) {
  2503. auto it = req.headers.find("CustomClientHeader");
  2504. EXPECT_TRUE(it != req.headers.end());
  2505. EXPECT_EQ(it->second, "CustomClientValue");
  2506. res.set_content("Hello World!\n", "text/plain");
  2507. });
  2508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. {
  2516. Client cli(HOST, PORT);
  2517. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2518. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2519. return detail::write_headers(strm, hdrs);
  2520. });
  2521. auto res = cli.Get("/hi");
  2522. EXPECT_TRUE(res);
  2523. EXPECT_EQ(StatusCode::OK_200, res->status);
  2524. auto it = res->headers.find("CustomServerHeader");
  2525. EXPECT_TRUE(it != res->headers.end());
  2526. EXPECT_EQ(it->second, "CustomServerValue");
  2527. }
  2528. }
  2529. class ServerTest : public ::testing::Test {
  2530. protected:
  2531. ServerTest()
  2532. : cli_(HOST, PORT)
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. ,
  2535. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2536. #endif
  2537. {
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. cli_.enable_server_certificate_verification(false);
  2540. #endif
  2541. // Allow LARGE_DATA (100MB) responses
  2542. cli_.set_payload_max_length(200 * 1024 * 1024);
  2543. }
  2544. virtual void SetUp() {
  2545. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2546. svr_.set_payload_max_length(200 * 1024 * 1024);
  2547. svr_.set_mount_point("/", "./www");
  2548. svr_.set_mount_point("/mount", "./www2");
  2549. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2550. svr_.Get("/hi",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_content("Hello World!", "text/plain");
  2553. })
  2554. .Get("/file_content",
  2555. [&](const Request & /*req*/, Response &res) {
  2556. res.set_file_content("./www/dir/test.html");
  2557. })
  2558. .Get("/file_content_with_content_type",
  2559. [&](const Request & /*req*/, Response &res) {
  2560. res.set_file_content("./www/file", "text/plain");
  2561. })
  2562. .Get("/invalid_file_content",
  2563. [&](const Request & /*req*/, Response &res) {
  2564. res.set_file_content("./www/dir/invalid_file_path");
  2565. })
  2566. .Get("/http_response_splitting",
  2567. [&](const Request & /*req*/, Response &res) {
  2568. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2569. EXPECT_EQ(0U, res.headers.size());
  2570. EXPECT_FALSE(res.has_header("a"));
  2571. res.set_header("a", "1\nSet-Cookie: a=1");
  2572. EXPECT_EQ(0U, res.headers.size());
  2573. EXPECT_FALSE(res.has_header("a"));
  2574. res.set_header("a", "1\rSet-Cookie: a=1");
  2575. EXPECT_EQ(0U, res.headers.size());
  2576. EXPECT_FALSE(res.has_header("a"));
  2577. res.set_header("a\r\nb", "0");
  2578. EXPECT_EQ(0U, res.headers.size());
  2579. EXPECT_FALSE(res.has_header("a"));
  2580. res.set_header("a\rb", "0");
  2581. EXPECT_EQ(0U, res.headers.size());
  2582. EXPECT_FALSE(res.has_header("a"));
  2583. res.set_header("a\nb", "0");
  2584. EXPECT_EQ(0U, res.headers.size());
  2585. EXPECT_FALSE(res.has_header("a"));
  2586. res.set_redirect("1\r\nSet-Cookie: a=1");
  2587. EXPECT_EQ(0U, res.headers.size());
  2588. EXPECT_FALSE(res.has_header("Location"));
  2589. })
  2590. .Get("/slow",
  2591. [&](const Request & /*req*/, Response &res) {
  2592. std::this_thread::sleep_for(std::chrono::seconds(2));
  2593. res.set_content("slow", "text/plain");
  2594. })
  2595. #if 0
  2596. .Post("/slowpost",
  2597. [&](const Request & /*req*/, Response &res) {
  2598. std::this_thread::sleep_for(std::chrono::seconds(2));
  2599. res.set_content("slow", "text/plain");
  2600. })
  2601. #endif
  2602. .Get("/remote_addr",
  2603. [&](const Request &req, Response &res) {
  2604. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2605. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2606. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2607. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2608. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2609. #endif
  2610. res.set_content(req.remote_addr, "text/plain");
  2611. })
  2612. .Get("/local_addr",
  2613. [&](const Request &req, Response &res) {
  2614. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2615. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2616. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2617. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2618. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2619. #endif
  2620. auto local_addr = req.local_addr;
  2621. auto local_port = std::to_string(req.local_port);
  2622. res.set_content(local_addr.append(":").append(local_port),
  2623. "text/plain");
  2624. })
  2625. .Get("/endwith%",
  2626. [&](const Request & /*req*/, Response &res) {
  2627. res.set_content("Hello World!", "text/plain");
  2628. })
  2629. .Get("/a\\+\\+b",
  2630. [&](const Request &req, Response &res) {
  2631. ASSERT_TRUE(req.has_param("a +b"));
  2632. auto val = req.get_param_value("a +b");
  2633. res.set_content(val, "text/plain");
  2634. })
  2635. .Get("/", [&](const Request & /*req*/,
  2636. Response &res) { res.set_redirect("/hi"); })
  2637. .Post("/1",
  2638. [](const Request & /*req*/, Response &res) {
  2639. res.set_redirect("/2", StatusCode::SeeOther_303);
  2640. })
  2641. .Get("/2",
  2642. [](const Request & /*req*/, Response &res) {
  2643. res.set_content("redirected.", "text/plain");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Post("/person",
  2647. [&](const Request &req, Response &res) {
  2648. if (req.has_param("name") && req.has_param("note")) {
  2649. persons_[req.get_param_value("name")] =
  2650. req.get_param_value("note");
  2651. } else {
  2652. res.status = StatusCode::BadRequest_400;
  2653. }
  2654. })
  2655. .Put("/person",
  2656. [&](const Request &req, Response &res) {
  2657. if (req.has_param("name") && req.has_param("note")) {
  2658. persons_[req.get_param_value("name")] =
  2659. req.get_param_value("note");
  2660. } else {
  2661. res.status = StatusCode::BadRequest_400;
  2662. }
  2663. })
  2664. .Get("/person/(.*)",
  2665. [&](const Request &req, Response &res) {
  2666. string name = req.matches[1];
  2667. if (persons_.find(name) != persons_.end()) {
  2668. auto note = persons_[name];
  2669. res.set_content(note, "text/plain");
  2670. } else {
  2671. res.status = StatusCode::NotFound_404;
  2672. }
  2673. })
  2674. .Delete("/person",
  2675. [&](const Request &req, Response &res) {
  2676. if (req.has_param("name")) {
  2677. string name = req.get_param_value("name");
  2678. if (persons_.find(name) != persons_.end()) {
  2679. persons_.erase(name);
  2680. res.set_content("DELETED", "text/plain");
  2681. } else {
  2682. res.status = StatusCode::NotFound_404;
  2683. }
  2684. } else {
  2685. res.status = StatusCode::BadRequest_400;
  2686. }
  2687. })
  2688. .Post("/x-www-form-urlencoded-json",
  2689. [&](const Request &req, Response &res) {
  2690. auto json = req.get_param_value("json");
  2691. ASSERT_EQ(JSON_DATA, json);
  2692. res.set_content(json, "appliation/json");
  2693. res.status = StatusCode::OK_200;
  2694. })
  2695. .Get("/streamed-chunked",
  2696. [&](const Request & /*req*/, Response &res) {
  2697. res.set_chunked_content_provider(
  2698. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2699. sink.os << "123";
  2700. sink.os << "456";
  2701. sink.os << "789";
  2702. sink.done();
  2703. return true;
  2704. });
  2705. })
  2706. .Get("/streamed-chunked-with-prohibited-trailer",
  2707. [&](const Request & /*req*/, Response &res) {
  2708. auto i = new int(0);
  2709. // Declare both a prohibited trailer (Content-Length) and an
  2710. // allowed one
  2711. res.set_header("Trailer", "Content-Length, X-Allowed");
  2712. res.set_chunked_content_provider(
  2713. "text/plain",
  2714. [i](size_t /*offset*/, DataSink &sink) {
  2715. switch (*i) {
  2716. case 0: sink.os << "123"; break;
  2717. case 1: sink.os << "456"; break;
  2718. case 2: sink.os << "789"; break;
  2719. case 3: {
  2720. sink.done_with_trailer(
  2721. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2722. } break;
  2723. }
  2724. (*i)++;
  2725. return true;
  2726. },
  2727. [i](bool success) {
  2728. EXPECT_TRUE(success);
  2729. delete i;
  2730. });
  2731. })
  2732. .Get("/streamed-chunked2",
  2733. [&](const Request & /*req*/, Response &res) {
  2734. auto i = new int(0);
  2735. res.set_chunked_content_provider(
  2736. "text/plain",
  2737. [i](size_t /*offset*/, DataSink &sink) {
  2738. switch (*i) {
  2739. case 0: sink.os << "123"; break;
  2740. case 1: sink.os << "456"; break;
  2741. case 2: sink.os << "789"; break;
  2742. case 3: sink.done(); break;
  2743. }
  2744. (*i)++;
  2745. return true;
  2746. },
  2747. [i](bool success) {
  2748. EXPECT_TRUE(success);
  2749. delete i;
  2750. });
  2751. })
  2752. .Get("/streamed-chunked-with-trailer",
  2753. [&](const Request & /*req*/, Response &res) {
  2754. auto i = new int(0);
  2755. res.set_header("Trailer", "Dummy1, Dummy2");
  2756. res.set_chunked_content_provider(
  2757. "text/plain",
  2758. [i](size_t /*offset*/, DataSink &sink) {
  2759. switch (*i) {
  2760. case 0: sink.os << "123"; break;
  2761. case 1: sink.os << "456"; break;
  2762. case 2: sink.os << "789"; break;
  2763. case 3: {
  2764. sink.done_with_trailer(
  2765. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2766. } break;
  2767. }
  2768. (*i)++;
  2769. return true;
  2770. },
  2771. [i](bool success) {
  2772. EXPECT_TRUE(success);
  2773. delete i;
  2774. });
  2775. })
  2776. .Get("/streamed",
  2777. [&](const Request & /*req*/, Response &res) {
  2778. res.set_content_provider(
  2779. 6, "text/plain",
  2780. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2781. sink.os << (offset < 3 ? "a" : "b");
  2782. return true;
  2783. });
  2784. })
  2785. .Get("/streamed-with-range",
  2786. [&](const Request &req, Response &res) {
  2787. auto data = new std::string("abcdefg");
  2788. res.set_content_provider(
  2789. data->size(), "text/plain",
  2790. [data](size_t offset, size_t length, DataSink &sink) {
  2791. size_t DATA_CHUNK_SIZE = 4;
  2792. const auto &d = *data;
  2793. auto out_len =
  2794. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2795. auto ret =
  2796. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2797. EXPECT_TRUE(ret);
  2798. return true;
  2799. },
  2800. [data, &req](bool success) {
  2801. EXPECT_EQ(success, !req.has_param("error"));
  2802. delete data;
  2803. });
  2804. })
  2805. .Get("/streamed-cancel",
  2806. [&](const Request & /*req*/, Response &res) {
  2807. res.set_content_provider(
  2808. size_t(-1), "text/plain",
  2809. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2810. sink.os << "data_chunk";
  2811. return true;
  2812. });
  2813. })
  2814. .Get("/regex-with-delimiter",
  2815. [&](const Request &req, Response & /*res*/) {
  2816. ASSERT_TRUE(req.has_param("key"));
  2817. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2818. })
  2819. .Get("/with-range",
  2820. [&](const Request & /*req*/, Response &res) {
  2821. res.set_content("abcdefg", "text/plain");
  2822. })
  2823. .Get("/test-start-time",
  2824. [&](const Request &req, Response & /*res*/) {
  2825. EXPECT_NE(req.start_time_,
  2826. std::chrono::steady_clock::time_point::min());
  2827. })
  2828. .Get("/with-range-customized-response",
  2829. [&](const Request & /*req*/, Response &res) {
  2830. res.status = StatusCode::BadRequest_400;
  2831. res.set_content(JSON_DATA, "application/json");
  2832. })
  2833. .Post("/chunked",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(req.body, "dechunked post body");
  2836. })
  2837. .Post("/large-chunked",
  2838. [&](const Request &req, Response & /*res*/) {
  2839. std::string expected(6 * 30 * 1024u, 'a');
  2840. EXPECT_EQ(req.body, expected);
  2841. })
  2842. .Post("/multipart",
  2843. [&](const Request &req, Response & /*res*/) {
  2844. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2845. req.form.get_field_count("text2") +
  2846. req.form.get_field_count("file3") +
  2847. req.form.get_field_count("file4"));
  2848. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2849. req.form.get_file_count("file2"));
  2850. ASSERT_TRUE(!req.form.has_file("???"));
  2851. ASSERT_TRUE(!req.form.has_field("???"));
  2852. ASSERT_TRUE(req.body.empty());
  2853. {
  2854. const auto &text = req.form.get_field("text1");
  2855. EXPECT_EQ("text default", text);
  2856. }
  2857. {
  2858. const auto &text = req.form.get_field("text2");
  2859. EXPECT_EQ("aωb", text);
  2860. }
  2861. {
  2862. const auto &file = req.form.get_file("file1");
  2863. EXPECT_EQ("hello.txt", file.filename);
  2864. EXPECT_EQ("text/plain", file.content_type);
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2866. }
  2867. {
  2868. const auto &file = req.form.get_file("file2");
  2869. EXPECT_EQ("world.json", file.filename);
  2870. EXPECT_EQ("application/json", file.content_type);
  2871. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2872. }
  2873. {
  2874. const auto &text = req.form.get_field("file3");
  2875. EXPECT_EQ(0u, text.size());
  2876. }
  2877. {
  2878. const auto &text = req.form.get_field("file4");
  2879. EXPECT_EQ(0u, text.size());
  2880. }
  2881. })
  2882. .Post("/multipart/multi_file_values",
  2883. [&](const Request &req, Response & /*res*/) {
  2884. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2885. req.form.get_field_count("multi_text1"));
  2886. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2887. ASSERT_TRUE(!req.form.has_file("???"));
  2888. ASSERT_TRUE(!req.form.has_field("???"));
  2889. ASSERT_TRUE(req.body.empty());
  2890. {
  2891. const auto &text = req.form.get_field("text");
  2892. EXPECT_EQ("default text", text);
  2893. }
  2894. {
  2895. const auto &text1_values = req.form.get_fields("multi_text1");
  2896. EXPECT_EQ(2u, text1_values.size());
  2897. EXPECT_EQ("aaaaa", text1_values[0]);
  2898. EXPECT_EQ("bbbbb", text1_values[1]);
  2899. }
  2900. {
  2901. const auto &file1_values = req.form.get_files("multi_file1");
  2902. EXPECT_EQ(2u, file1_values.size());
  2903. auto file1 = file1_values[0];
  2904. EXPECT_EQ(file1.filename, "hello.txt");
  2905. EXPECT_EQ(file1.content_type, "text/plain");
  2906. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2907. auto file2 = file1_values[1];
  2908. EXPECT_EQ(file2.filename, "world.json");
  2909. EXPECT_EQ(file2.content_type, "application/json");
  2910. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2911. }
  2912. })
  2913. .Post("/empty",
  2914. [&](const Request &req, Response &res) {
  2915. EXPECT_EQ(req.body, "");
  2916. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2917. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2918. res.set_content("empty", "text/plain");
  2919. })
  2920. .Post("/empty-no-content-type",
  2921. [&](const Request &req, Response &res) {
  2922. EXPECT_EQ(req.body, "");
  2923. EXPECT_FALSE(req.has_header("Content-Type"));
  2924. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2925. res.set_content("empty-no-content-type", "text/plain");
  2926. })
  2927. .Post("/path-only",
  2928. [&](const Request &req, Response &res) {
  2929. EXPECT_EQ(req.body, "");
  2930. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2931. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2932. res.set_content("path-only", "text/plain");
  2933. })
  2934. .Post("/path-headers-only",
  2935. [&](const Request &req, Response &res) {
  2936. EXPECT_EQ(req.body, "");
  2937. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2938. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2939. EXPECT_EQ("world", req.get_header_value("hello"));
  2940. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2941. res.set_content("path-headers-only", "text/plain");
  2942. })
  2943. .Post("/post-large",
  2944. [&](const Request &req, Response &res) {
  2945. EXPECT_EQ(req.body, LARGE_DATA);
  2946. res.set_content(req.body, "text/plain");
  2947. })
  2948. .Post("/post-loopback",
  2949. [&](const Request &, Response &res,
  2950. ContentReader const &content_reader) {
  2951. std::string body;
  2952. content_reader([&](const char *data, size_t data_length) {
  2953. body.append(data, data_length);
  2954. return true;
  2955. });
  2956. res.set_content(body, "text/plain");
  2957. })
  2958. .Put("/put-loopback",
  2959. [&](const Request &, Response &res,
  2960. ContentReader const &content_reader) {
  2961. std::string body;
  2962. content_reader([&](const char *data, size_t data_length) {
  2963. body.append(data, data_length);
  2964. return true;
  2965. });
  2966. res.set_content(body, "text/plain");
  2967. })
  2968. .Patch("/patch-loopback",
  2969. [&](const Request &, Response &res,
  2970. ContentReader const &content_reader) {
  2971. std::string body;
  2972. content_reader([&](const char *data, size_t data_length) {
  2973. body.append(data, data_length);
  2974. return true;
  2975. });
  2976. res.set_content(body, "text/plain");
  2977. })
  2978. .Put("/empty-no-content-type",
  2979. [&](const Request &req, Response &res) {
  2980. EXPECT_EQ(req.body, "");
  2981. EXPECT_FALSE(req.has_header("Content-Type"));
  2982. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2983. res.set_content("empty-no-content-type", "text/plain");
  2984. })
  2985. .Put("/put",
  2986. [&](const Request &req, Response &res) {
  2987. EXPECT_EQ(req.body, "PUT");
  2988. res.set_content(req.body, "text/plain");
  2989. })
  2990. .Put("/put-large",
  2991. [&](const Request &req, Response &res) {
  2992. EXPECT_EQ(req.body, LARGE_DATA);
  2993. res.set_content(req.body, "text/plain");
  2994. })
  2995. .Patch("/patch",
  2996. [&](const Request &req, Response &res) {
  2997. EXPECT_EQ(req.body, "PATCH");
  2998. res.set_content(req.body, "text/plain");
  2999. })
  3000. .Delete("/delete",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content("DELETE", "text/plain");
  3003. })
  3004. .Delete("/delete-body",
  3005. [&](const Request &req, Response &res) {
  3006. EXPECT_EQ(req.body, "content");
  3007. res.set_content(req.body, "text/plain");
  3008. })
  3009. .Options(R"(\*)",
  3010. [&](const Request & /*req*/, Response &res) {
  3011. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3012. })
  3013. .Get("/request-target",
  3014. [&](const Request &req, Response & /*res*/) {
  3015. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3016. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3017. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3018. })
  3019. .Get("/long-query-value",
  3020. [&](const Request &req, Response & /*res*/) {
  3021. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3022. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3023. })
  3024. .Get("/too-long-query-value",
  3025. [&](const Request &req, Response & /*res*/) {
  3026. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3027. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3028. })
  3029. .Get("/array-param",
  3030. [&](const Request &req, Response & /*res*/) {
  3031. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3032. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3033. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3034. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3035. })
  3036. .Post("/validate-no-multiple-headers",
  3037. [&](const Request &req, Response & /*res*/) {
  3038. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3039. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3040. })
  3041. .Post("/content_receiver",
  3042. [&](const Request &req, Response &res,
  3043. const ContentReader &content_reader) {
  3044. if (req.is_multipart_form_data()) {
  3045. std::vector<FormData> items;
  3046. content_reader(
  3047. [&](const FormData &file) {
  3048. items.push_back(file);
  3049. return true;
  3050. },
  3051. [&](const char *data, size_t data_length) {
  3052. items.back().content.append(data, data_length);
  3053. return true;
  3054. });
  3055. EXPECT_EQ(5u, items.size());
  3056. {
  3057. const auto &file = get_file_value(items, "text1");
  3058. EXPECT_TRUE(file.filename.empty());
  3059. EXPECT_EQ("text default", file.content);
  3060. }
  3061. {
  3062. const auto &file = get_file_value(items, "text2");
  3063. EXPECT_TRUE(file.filename.empty());
  3064. EXPECT_EQ("aωb", file.content);
  3065. }
  3066. {
  3067. const auto &file = get_file_value(items, "file1");
  3068. EXPECT_EQ("hello.txt", file.filename);
  3069. EXPECT_EQ("text/plain", file.content_type);
  3070. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3071. }
  3072. {
  3073. const auto &file = get_file_value(items, "file2");
  3074. EXPECT_EQ("world.json", file.filename);
  3075. EXPECT_EQ("application/json", file.content_type);
  3076. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3077. }
  3078. {
  3079. const auto &file = get_file_value(items, "file3");
  3080. EXPECT_TRUE(file.filename.empty());
  3081. EXPECT_EQ("application/octet-stream", file.content_type);
  3082. EXPECT_EQ(0u, file.content.size());
  3083. }
  3084. } else {
  3085. std::string body;
  3086. content_reader([&](const char *data, size_t data_length) {
  3087. EXPECT_EQ(7U, 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. })
  3095. .Put("/content_receiver",
  3096. [&](const Request & /*req*/, Response &res,
  3097. const ContentReader &content_reader) {
  3098. std::string body;
  3099. content_reader([&](const char *data, size_t data_length) {
  3100. body.append(data, data_length);
  3101. return true;
  3102. });
  3103. EXPECT_EQ(body, "content");
  3104. res.set_content(body, "text/plain");
  3105. })
  3106. .Patch("/content_receiver",
  3107. [&](const Request & /*req*/, Response &res,
  3108. const ContentReader &content_reader) {
  3109. std::string body;
  3110. content_reader([&](const char *data, size_t data_length) {
  3111. body.append(data, data_length);
  3112. return true;
  3113. });
  3114. EXPECT_EQ(body, "content");
  3115. res.set_content(body, "text/plain");
  3116. })
  3117. .Post("/query-string-and-body",
  3118. [&](const Request &req, Response & /*res*/) {
  3119. ASSERT_TRUE(req.has_param("key"));
  3120. EXPECT_EQ(req.get_param_value("key"), "value");
  3121. EXPECT_EQ(req.body, "content");
  3122. })
  3123. .Get("/last-request",
  3124. [&](const Request &req, Response & /*res*/) {
  3125. EXPECT_EQ("close", req.get_header_value("Connection"));
  3126. })
  3127. .Get(R"(/redirect/(\d+))",
  3128. [&](const Request &req, Response &res) {
  3129. auto num = std::stoi(req.matches[1]) + 1;
  3130. std::string url = "/redirect/" + std::to_string(num);
  3131. res.set_redirect(url);
  3132. })
  3133. .Post("/binary",
  3134. [&](const Request &req, Response &res) {
  3135. EXPECT_EQ(4U, req.body.size());
  3136. EXPECT_EQ("application/octet-stream",
  3137. req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3139. res.set_content(req.body, "application/octet-stream");
  3140. })
  3141. .Put("/binary",
  3142. [&](const Request &req, Response &res) {
  3143. EXPECT_EQ(4U, req.body.size());
  3144. EXPECT_EQ("application/octet-stream",
  3145. req.get_header_value("Content-Type"));
  3146. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3147. res.set_content(req.body, "application/octet-stream");
  3148. })
  3149. .Patch("/binary",
  3150. [&](const Request &req, Response &res) {
  3151. EXPECT_EQ(4U, req.body.size());
  3152. EXPECT_EQ("application/octet-stream",
  3153. req.get_header_value("Content-Type"));
  3154. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3155. res.set_content(req.body, "application/octet-stream");
  3156. })
  3157. .Delete("/binary",
  3158. [&](const Request &req, Response &res) {
  3159. EXPECT_EQ(4U, req.body.size());
  3160. EXPECT_EQ("application/octet-stream",
  3161. req.get_header_value("Content-Type"));
  3162. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3163. res.set_content(req.body, "application/octet-stream");
  3164. })
  3165. .Get("/issue1772",
  3166. [&](const Request & /*req*/, Response &res) {
  3167. res.status = 401;
  3168. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3169. })
  3170. .Delete("/issue609",
  3171. [](const httplib::Request &, httplib::Response &res,
  3172. const httplib::ContentReader &) {
  3173. res.set_content("ok", "text/plain");
  3174. })
  3175. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3176. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3177. .Get("/compress",
  3178. [&](const Request & /*req*/, Response &res) {
  3179. res.set_content(
  3180. "12345678901234567890123456789012345678901234567890123456789"
  3181. "01234567890123456789012345678901234567890",
  3182. "text/plain");
  3183. })
  3184. .Get("/nocompress",
  3185. [&](const Request & /*req*/, Response &res) {
  3186. res.set_content(
  3187. "12345678901234567890123456789012345678901234567890123456789"
  3188. "01234567890123456789012345678901234567890",
  3189. "application/octet-stream");
  3190. })
  3191. .Post("/compress-multipart",
  3192. [&](const Request &req, Response & /*res*/) {
  3193. EXPECT_EQ(2u, req.form.fields.size());
  3194. ASSERT_TRUE(!req.form.has_field("???"));
  3195. {
  3196. const auto &text = req.form.get_field("key1");
  3197. EXPECT_EQ("test", text);
  3198. }
  3199. {
  3200. const auto &text = req.form.get_field("key2");
  3201. EXPECT_EQ("--abcdefg123", text);
  3202. }
  3203. })
  3204. #endif
  3205. ;
  3206. persons_["john"] = "programmer";
  3207. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3208. svr_.wait_until_ready();
  3209. }
  3210. virtual void TearDown() {
  3211. svr_.stop();
  3212. if (!request_threads_.empty()) {
  3213. std::this_thread::sleep_for(std::chrono::seconds(1));
  3214. for (auto &t : request_threads_) {
  3215. t.join();
  3216. }
  3217. }
  3218. t_.join();
  3219. }
  3220. map<string, string> persons_;
  3221. #ifdef CPPHTTPLIB_SSL_ENABLED
  3222. SSLClient cli_;
  3223. SSLServer svr_;
  3224. #else
  3225. Client cli_;
  3226. Server svr_;
  3227. #endif
  3228. thread t_;
  3229. std::vector<thread> request_threads_;
  3230. };
  3231. TEST_F(ServerTest, GetMethod200) {
  3232. auto res = cli_.Get("/hi");
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ("HTTP/1.1", res->version);
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. EXPECT_EQ("OK", res->reason);
  3237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3238. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3239. EXPECT_EQ("Hello World!", res->body);
  3240. }
  3241. TEST_F(ServerTest, GetEmptyFile) {
  3242. auto res = cli_.Get("/empty_file");
  3243. ASSERT_TRUE(res);
  3244. EXPECT_EQ(StatusCode::OK_200, res->status);
  3245. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3246. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3247. EXPECT_EQ("", res->body);
  3248. }
  3249. TEST_F(ServerTest, GetFileContent) {
  3250. auto res = cli_.Get("/file_content");
  3251. ASSERT_TRUE(res);
  3252. EXPECT_EQ(StatusCode::OK_200, res->status);
  3253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3254. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3255. EXPECT_EQ("test.html", res->body);
  3256. }
  3257. TEST_F(ServerTest, GetFileContentWithRange) {
  3258. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3261. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3262. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3263. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3264. EXPECT_EQ("est", res->body);
  3265. }
  3266. TEST_F(ServerTest, GetFileContentWithContentType) {
  3267. auto res = cli_.Get("/file_content_with_content_type");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3271. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3272. EXPECT_EQ("file\n", res->body);
  3273. }
  3274. TEST_F(ServerTest, GetInvalidFileContent) {
  3275. auto res = cli_.Get("/invalid_file_content");
  3276. ASSERT_TRUE(res);
  3277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3278. }
  3279. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3280. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ("HTTP/1.1", res->version);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3285. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3286. EXPECT_EQ("Hello World!", res->body);
  3287. }
  3288. TEST_F(ServerTest, GetMethod302) {
  3289. auto res = cli_.Get("/");
  3290. ASSERT_TRUE(res);
  3291. EXPECT_EQ(StatusCode::Found_302, res->status);
  3292. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3293. }
  3294. TEST_F(ServerTest, GetMethod302Redirect) {
  3295. cli_.set_follow_location(true);
  3296. auto res = cli_.Get("/");
  3297. ASSERT_TRUE(res);
  3298. EXPECT_EQ(StatusCode::OK_200, res->status);
  3299. EXPECT_EQ("Hello World!", res->body);
  3300. EXPECT_EQ("/hi", res->location);
  3301. }
  3302. TEST_F(ServerTest, GetMethod404) {
  3303. auto res = cli_.Get("/invalid");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3306. }
  3307. TEST_F(ServerTest, HeadMethod200) {
  3308. auto res = cli_.Head("/hi");
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3312. EXPECT_TRUE(res->body.empty());
  3313. }
  3314. TEST_F(ServerTest, HeadMethod200Static) {
  3315. auto res = cli_.Head("/mount/dir/index.html");
  3316. ASSERT_TRUE(res);
  3317. EXPECT_EQ(StatusCode::OK_200, res->status);
  3318. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3319. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3320. EXPECT_TRUE(res->body.empty());
  3321. }
  3322. TEST_F(ServerTest, HeadMethod404) {
  3323. auto res = cli_.Head("/invalid");
  3324. ASSERT_TRUE(res);
  3325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3326. EXPECT_TRUE(res->body.empty());
  3327. }
  3328. TEST_F(ServerTest, GetMethodPersonJohn) {
  3329. auto res = cli_.Get("/person/john");
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::OK_200, res->status);
  3332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3333. EXPECT_EQ("programmer", res->body);
  3334. }
  3335. TEST_F(ServerTest, PostMethod1) {
  3336. auto res = cli_.Get("/person/john1");
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3339. res = cli_.Post("/person", "name=john1&note=coder",
  3340. "application/x-www-form-urlencoded");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. res = cli_.Get("/person/john1");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3347. ASSERT_EQ("coder", res->body);
  3348. }
  3349. TEST_F(ServerTest, PostMethod2) {
  3350. auto res = cli_.Get("/person/john2");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3353. Params params;
  3354. params.emplace("name", "john2");
  3355. params.emplace("note", "coder");
  3356. res = cli_.Post("/person", params);
  3357. ASSERT_TRUE(res);
  3358. ASSERT_EQ(StatusCode::OK_200, res->status);
  3359. res = cli_.Get("/person/john2");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::OK_200, res->status);
  3362. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3363. ASSERT_EQ("coder", res->body);
  3364. }
  3365. TEST_F(ServerTest, PutMethod3) {
  3366. auto res = cli_.Get("/person/john3");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3369. Params params;
  3370. params.emplace("name", "john3");
  3371. params.emplace("note", "coder");
  3372. res = cli_.Put("/person", params);
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. res = cli_.Get("/person/john3");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. ASSERT_EQ("coder", res->body);
  3380. }
  3381. TEST_F(ServerTest, DeleteMethod1) {
  3382. auto res = cli_.Get("/person/john4");
  3383. ASSERT_TRUE(res);
  3384. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3385. Params params;
  3386. params.emplace("name", "john4");
  3387. params.emplace("note", "coder");
  3388. res = cli_.Post("/person", params);
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::OK_200, res->status);
  3391. res = cli_.Get("/person/john4");
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3395. ASSERT_EQ("coder", res->body);
  3396. Params delete_params;
  3397. delete_params.emplace("name", "john4");
  3398. res = cli_.Delete("/person", delete_params);
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("DELETED", res->body);
  3402. res = cli_.Get("/person/john4");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3405. }
  3406. TEST_F(ServerTest, DeleteMethod2) {
  3407. auto res = cli_.Get("/person/john5");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. Params params;
  3411. params.emplace("name", "john5");
  3412. params.emplace("note", "developer");
  3413. res = cli_.Post("/person", params);
  3414. ASSERT_TRUE(res);
  3415. ASSERT_EQ(StatusCode::OK_200, res->status);
  3416. res = cli_.Get("/person/john5");
  3417. ASSERT_TRUE(res);
  3418. ASSERT_EQ(StatusCode::OK_200, res->status);
  3419. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3420. ASSERT_EQ("developer", res->body);
  3421. Params delete_params;
  3422. delete_params.emplace("name", "john5");
  3423. Headers headers;
  3424. headers.emplace("Custom-Header", "test-value");
  3425. res = cli_.Delete("/person", headers, delete_params);
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::OK_200, res->status);
  3428. ASSERT_EQ("DELETED", res->body);
  3429. res = cli_.Get("/person/john5");
  3430. ASSERT_TRUE(res);
  3431. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3432. }
  3433. TEST_F(ServerTest, DeleteMethod3) {
  3434. auto res = cli_.Get("/person/john6");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3437. Params params;
  3438. params.emplace("name", "john6");
  3439. params.emplace("note", "tester");
  3440. res = cli_.Post("/person", params);
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. res = cli_.Get("/person/john6");
  3444. ASSERT_TRUE(res);
  3445. ASSERT_EQ(StatusCode::OK_200, res->status);
  3446. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3447. ASSERT_EQ("tester", res->body);
  3448. Params delete_params;
  3449. delete_params.emplace("name", "john6");
  3450. Headers headers;
  3451. headers.emplace("Custom-Header", "test-value");
  3452. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::OK_200, res->status);
  3455. ASSERT_EQ("DELETED", res->body);
  3456. res = cli_.Get("/person/john6");
  3457. ASSERT_TRUE(res);
  3458. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3459. }
  3460. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3461. Params params;
  3462. params.emplace("json", JSON_DATA);
  3463. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. ASSERT_EQ(JSON_DATA, res->body);
  3467. }
  3468. TEST_F(ServerTest, PostEmptyContent) {
  3469. auto res = cli_.Post("/empty", "", "text/plain");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("empty", res->body);
  3473. }
  3474. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3475. auto res = cli_.Post("/empty-no-content-type");
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("empty-no-content-type", res->body);
  3479. }
  3480. TEST_F(ServerTest, PostPathOnly) {
  3481. auto res = cli_.Post("/path-only");
  3482. ASSERT_TRUE(res);
  3483. ASSERT_EQ(StatusCode::OK_200, res->status);
  3484. ASSERT_EQ("path-only", res->body);
  3485. }
  3486. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3487. auto res = cli_.Post("/path-headers-only",
  3488. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. ASSERT_EQ("path-headers-only", res->body);
  3492. }
  3493. TEST_F(ServerTest, PostLarge) {
  3494. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ(LARGE_DATA, res->body);
  3498. }
  3499. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3500. auto res = cli_.Put("/empty-no-content-type");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ("empty-no-content-type", res->body);
  3504. }
  3505. TEST_F(ServerTest, GetMethodDir) {
  3506. auto res = cli_.Get("/dir/");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3510. auto body = R"(<html>
  3511. <head>
  3512. </head>
  3513. <body>
  3514. <a href="/dir/test.html">Test</a>
  3515. <a href="/hi">hi</a>
  3516. </body>
  3517. </html>
  3518. )";
  3519. EXPECT_EQ(body, res->body);
  3520. }
  3521. TEST_F(ServerTest, GetMethodDirTest) {
  3522. auto res = cli_.Get("/dir/test.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3526. EXPECT_EQ("test.html", res->body);
  3527. }
  3528. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3529. auto res = cli_.Get("/dir/../dir/test.html");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3533. EXPECT_EQ("test.html", res->body);
  3534. }
  3535. TEST_F(ServerTest, GetMethodInvalidPath) {
  3536. auto res = cli_.Get("/dir/../test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3541. auto res = cli_.Get("/../www/dir/test.html");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3544. }
  3545. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3546. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, GetMethodDirMountTest) {
  3551. auto res = cli_.Get("/mount/dir/test.html");
  3552. ASSERT_TRUE(res);
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3555. EXPECT_EQ("test.html", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3558. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ("test.html", res->body);
  3563. }
  3564. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3565. auto res = cli_.Get("/mount/dir/../test.html");
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3568. }
  3569. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3570. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3575. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3576. ASSERT_TRUE(res);
  3577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3578. }
  3579. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3580. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3583. }
  3584. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3585. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3588. }
  3589. TEST_F(ServerTest, PostMethod303) {
  3590. auto res = cli_.Post("/1", "body", "text/plain");
  3591. ASSERT_TRUE(res);
  3592. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3593. EXPECT_EQ("/2", res->get_header_value("Location"));
  3594. }
  3595. TEST_F(ServerTest, PostMethod303Redirect) {
  3596. cli_.set_follow_location(true);
  3597. auto res = cli_.Post("/1", "body", "text/plain");
  3598. ASSERT_TRUE(res);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("redirected.", res->body);
  3601. EXPECT_EQ("/2", res->location);
  3602. }
  3603. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3604. auto res = cli_.Get("/dir/test.abcde");
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::OK_200, res->status);
  3607. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("abcde", res->body);
  3609. }
  3610. TEST_F(ServerTest, StaticFileRange) {
  3611. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3614. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3615. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3616. EXPECT_EQ(true, res->has_header("Content-Range"));
  3617. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3618. EXPECT_EQ(std::string("cd"), res->body);
  3619. }
  3620. TEST_F(ServerTest, StaticFileRanges) {
  3621. auto res =
  3622. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3625. EXPECT_TRUE(
  3626. res->get_header_value("Content-Type")
  3627. .find(
  3628. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3629. 0);
  3630. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3631. }
  3632. TEST_F(ServerTest, StaticFileRangeHead) {
  3633. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3634. ASSERT_TRUE(res);
  3635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3636. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3637. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3638. EXPECT_EQ(true, res->has_header("Content-Range"));
  3639. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3640. }
  3641. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3642. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3646. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3647. EXPECT_EQ(true, res->has_header("Content-Range"));
  3648. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3649. res->get_header_value("Content-Range"));
  3650. EXPECT_EQ("LAST\n", res->body);
  3651. }
  3652. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3653. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3654. ASSERT_TRUE(res);
  3655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3657. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3658. EXPECT_EQ(true, res->has_header("Content-Range"));
  3659. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3660. }
  3661. TEST_F(ServerTest, StaticFileBigFile) {
  3662. auto res = cli_.Get("/dir/1MB.txt");
  3663. ASSERT_TRUE(res);
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3666. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3667. }
  3668. TEST_F(ServerTest, InvalidBaseDirMount) {
  3669. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3670. }
  3671. TEST_F(ServerTest, Binary) {
  3672. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3673. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3674. "application/octet-stream");
  3675. ASSERT_TRUE(res);
  3676. ASSERT_EQ(StatusCode::OK_200, res->status);
  3677. ASSERT_EQ(4U, res->body.size());
  3678. res = cli_.Put("/binary", binary.data(), binary.size(),
  3679. "application/octet-stream");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ(4U, res->body.size());
  3683. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3684. "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_.Delete("/binary", binary.data(), binary.size(),
  3689. "application/octet-stream");
  3690. ASSERT_TRUE(res);
  3691. ASSERT_EQ(StatusCode::OK_200, res->status);
  3692. ASSERT_EQ(4U, res->body.size());
  3693. }
  3694. TEST_F(ServerTest, BinaryString) {
  3695. auto binary = std::string("\x00\x01\x02\x03", 4);
  3696. auto res = cli_.Post("/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. res = cli_.Put("/binary", binary, "application/octet-stream");
  3701. ASSERT_TRUE(res);
  3702. ASSERT_EQ(StatusCode::OK_200, res->status);
  3703. ASSERT_EQ(4U, res->body.size());
  3704. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. ASSERT_EQ(4U, res->body.size());
  3708. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3709. ASSERT_TRUE(res);
  3710. ASSERT_EQ(StatusCode::OK_200, res->status);
  3711. ASSERT_EQ(4U, res->body.size());
  3712. }
  3713. TEST_F(ServerTest, EmptyRequest) {
  3714. auto res = cli_.Get("");
  3715. ASSERT_TRUE(!res);
  3716. EXPECT_EQ(Error::Connection, res.error());
  3717. }
  3718. TEST_F(ServerTest, LongRequest) {
  3719. std::string request;
  3720. for (size_t i = 0; i < 545; i++) {
  3721. request += "/TooLongRequest";
  3722. }
  3723. request += "OK";
  3724. auto res = cli_.Get(request.c_str());
  3725. ASSERT_TRUE(res);
  3726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, TooLongRequest) {
  3729. std::string request;
  3730. for (size_t i = 0; i < 546; i++) {
  3731. request += "/TooLongRequest";
  3732. }
  3733. request += "_NG";
  3734. auto start = std::chrono::high_resolution_clock::now();
  3735. cli_.set_keep_alive(true);
  3736. auto res = cli_.Get(request.c_str());
  3737. auto end = std::chrono::high_resolution_clock::now();
  3738. auto elapsed =
  3739. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3740. .count();
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3743. EXPECT_LE(elapsed, 1000);
  3744. EXPECT_EQ("close", res->get_header_value("Connection"));
  3745. EXPECT_FALSE(cli_.is_socket_open());
  3746. }
  3747. TEST_F(ServerTest, AlmostTooLongRequest) {
  3748. // test for #2046 - URI length check shouldn't include other content on req
  3749. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3750. // leading /, space, HTTP/1.1)
  3751. std::string request =
  3752. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3753. auto res = cli_.Get(request.c_str());
  3754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, LongHeader) {
  3758. Request req;
  3759. req.method = "GET";
  3760. req.path = "/hi";
  3761. std::string host_and_port;
  3762. host_and_port += HOST;
  3763. host_and_port += ":";
  3764. host_and_port += std::to_string(PORT);
  3765. req.headers.emplace("Host", host_and_port.c_str());
  3766. req.headers.emplace("Accept", "*/*");
  3767. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3768. req.headers.emplace(
  3769. "Header-Name",
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@");
  3799. auto res = std::make_shared<Response>();
  3800. auto error = Error::Success;
  3801. auto ret = cli_.send(req, *res, error);
  3802. ASSERT_TRUE(ret);
  3803. EXPECT_EQ(StatusCode::OK_200, res->status);
  3804. }
  3805. TEST_F(ServerTest, LongQueryValue) {
  3806. auto start = std::chrono::high_resolution_clock::now();
  3807. cli_.set_keep_alive(true);
  3808. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3809. auto end = std::chrono::high_resolution_clock::now();
  3810. auto elapsed =
  3811. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3812. .count();
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3815. EXPECT_LE(elapsed, 1000);
  3816. EXPECT_EQ("close", res->get_header_value("Connection"));
  3817. EXPECT_FALSE(cli_.is_socket_open());
  3818. }
  3819. TEST_F(ServerTest, TooLongQueryValue) {
  3820. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3821. ASSERT_FALSE(res);
  3822. EXPECT_EQ(Error::Read, res.error());
  3823. }
  3824. TEST_F(ServerTest, TooLongHeader) {
  3825. Request req;
  3826. req.method = "GET";
  3827. req.path = "/hi";
  3828. std::string host_and_port;
  3829. host_and_port += HOST;
  3830. host_and_port += ":";
  3831. host_and_port += std::to_string(PORT);
  3832. req.headers.emplace("Host", host_and_port.c_str());
  3833. req.headers.emplace("Accept", "*/*");
  3834. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3835. req.headers.emplace(
  3836. "Header-Name",
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@");
  3866. auto res = std::make_shared<Response>();
  3867. auto error = Error::Success;
  3868. auto ret = cli_.send(req, *res, error);
  3869. ASSERT_TRUE(ret);
  3870. EXPECT_EQ(StatusCode::OK_200, res->status);
  3871. }
  3872. TEST_F(ServerTest, HeaderCountAtLimit) {
  3873. // Test with headers just under the 100 limit
  3874. httplib::Headers headers;
  3875. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3876. // This should keep us just under the 100 header limit
  3877. for (int i = 0; i < 95; i++) {
  3878. std::string name = "X-Test-Header-" + std::to_string(i);
  3879. std::string value = "value" + std::to_string(i);
  3880. headers.emplace(name, value);
  3881. }
  3882. // This should work fine as we're under the limit
  3883. auto res = cli_.Get("/hi", headers);
  3884. EXPECT_TRUE(res);
  3885. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3886. }
  3887. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3888. // Test with many headers to exceed the 100 limit
  3889. httplib::Headers headers;
  3890. // Add 150 headers to definitely exceed the 100 limit
  3891. for (int i = 0; i < 150; i++) {
  3892. std::string name = "X-Test-Header-" + std::to_string(i);
  3893. std::string value = "value" + std::to_string(i);
  3894. headers.emplace(name, value);
  3895. }
  3896. // This should fail due to exceeding header count limit
  3897. cli_.set_keep_alive(true);
  3898. auto res = cli_.Get("/hi", headers);
  3899. // The request should either fail or return 400 Bad Request
  3900. if (res) {
  3901. // If we get a response, it should be 400 Bad Request
  3902. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3903. } else {
  3904. // Or the request should fail entirely
  3905. EXPECT_FALSE(res);
  3906. }
  3907. EXPECT_EQ("close", res->get_header_value("Connection"));
  3908. EXPECT_FALSE(cli_.is_socket_open());
  3909. }
  3910. TEST_F(ServerTest, PercentEncoding) {
  3911. auto res = cli_.Get("/e%6edwith%");
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. TEST_F(ServerTest, PercentEncodingUnicode) {
  3916. auto res = cli_.Get("/e%u006edwith%");
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::OK_200, res->status);
  3919. }
  3920. TEST_F(ServerTest, InvalidPercentEncoding) {
  3921. auto res = cli_.Get("/%endwith%");
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3924. }
  3925. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3926. auto res = cli_.Get("/%uendwith%");
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3929. }
  3930. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3931. auto res = cli_.Get("/hello?aaa=bbb%");
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3934. }
  3935. TEST_F(ServerTest, PlusSignEncoding) {
  3936. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("a +b", res->body);
  3940. }
  3941. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3942. // This test simulates a potential DoS attack using many headers
  3943. // to verify our security fix prevents memory exhaustion
  3944. httplib::Headers attack_headers;
  3945. // Attempt to add many headers like an attacker would (200 headers to far
  3946. // exceed limit)
  3947. for (int i = 0; i < 200; i++) {
  3948. std::string name = "X-Attack-Header-" + std::to_string(i);
  3949. std::string value = "attack_payload_" + std::to_string(i);
  3950. attack_headers.emplace(name, value);
  3951. }
  3952. // Try to POST with excessive headers
  3953. cli_.set_keep_alive(true);
  3954. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3955. // Should either fail or return 400 Bad Request due to security limit
  3956. if (res) {
  3957. // If we get a response, it should be 400 Bad Request
  3958. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3959. } else {
  3960. // Request failed, which is the expected behavior for DoS protection
  3961. EXPECT_FALSE(res);
  3962. }
  3963. EXPECT_EQ("close", res->get_header_value("Connection"));
  3964. EXPECT_FALSE(cli_.is_socket_open());
  3965. }
  3966. TEST_F(ServerTest, MultipartFormData) {
  3967. UploadFormDataItems items = {
  3968. {"text1", "text default", "", ""},
  3969. {"text2", "aωb", "", ""},
  3970. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3971. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3972. {"file3", "", "", "application/octet-stream"},
  3973. {"file4", "", "", " application/json tmp-string "}};
  3974. auto res = cli_.Post("/multipart", items);
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::OK_200, res->status);
  3977. }
  3978. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3979. UploadFormDataItems items = {
  3980. {"text", "default text", "", ""},
  3981. {"multi_text1", "aaaaa", "", ""},
  3982. {"multi_text1", "bbbbb", "", ""},
  3983. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3984. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3985. "application/json"},
  3986. };
  3987. auto res = cli_.Post("/multipart/multi_file_values", items);
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. }
  3991. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3992. auto res = cli_.Get("/hi");
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3996. EXPECT_EQ("Hello World!", res->body);
  3997. }
  3998. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3999. Request req;
  4000. req.method = "POST";
  4001. req.path = "/chunked";
  4002. std::string host_and_port;
  4003. host_and_port += HOST;
  4004. host_and_port += ":";
  4005. host_and_port += std::to_string(PORT);
  4006. req.headers.emplace("Host", host_and_port.c_str());
  4007. req.headers.emplace("Accept", "*/*");
  4008. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4009. req.headers.emplace("Content-Type", "text/plain");
  4010. req.headers.emplace("Content-Length", "0");
  4011. req.headers.emplace(
  4012. "Transfer-Encoding",
  4013. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4014. // Client does not chunk, so make a chunked body manually.
  4015. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4016. auto res = std::make_shared<Response>();
  4017. auto error = Error::Success;
  4018. auto ret = cli_.send(req, *res, error);
  4019. ASSERT_TRUE(ret);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. }
  4022. TEST_F(ServerTest, GetStreamed2) {
  4023. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4026. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4027. EXPECT_EQ(true, res->has_header("Content-Range"));
  4028. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4029. EXPECT_EQ(std::string("ab"), res->body);
  4030. }
  4031. TEST_F(ServerTest, GetStreamed) {
  4032. auto res = cli_.Get("/streamed");
  4033. ASSERT_TRUE(res);
  4034. EXPECT_EQ(StatusCode::OK_200, res->status);
  4035. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4036. EXPECT_EQ(std::string("aaabbb"), res->body);
  4037. }
  4038. TEST_F(ServerTest, GetStreamedWithRange1) {
  4039. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4040. ASSERT_TRUE(res);
  4041. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4042. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4043. EXPECT_EQ(true, res->has_header("Content-Range"));
  4044. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4045. EXPECT_EQ(std::string("def"), res->body);
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithRange2) {
  4048. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4049. ASSERT_TRUE(res);
  4050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4051. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4052. EXPECT_EQ(true, res->has_header("Content-Range"));
  4053. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4054. EXPECT_EQ(std::string("bcdefg"), res->body);
  4055. }
  4056. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4057. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4060. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ(true, res->has_header("Content-Range"));
  4062. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4063. EXPECT_EQ(std::string("efg"), res->body);
  4064. }
  4065. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4066. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4069. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4070. EXPECT_EQ(false, res->has_header("Content-Range"));
  4071. EXPECT_EQ(0U, res->body.size());
  4072. }
  4073. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4074. auto res = cli_.Get("/streamed-with-range",
  4075. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4076. "92233720368547758079223372036854775807"}});
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4079. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4080. EXPECT_EQ(false, res->has_header("Content-Range"));
  4081. EXPECT_EQ(0U, res->body.size());
  4082. }
  4083. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4084. auto res = cli_.Get(
  4085. "/with-range",
  4086. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4087. {"Accept-Encoding", ""}});
  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, GetRangeWithZeroToInfinite) {
  4096. auto res = cli_.Get("/with-range", {
  4097. {"Range", "bytes=0-"},
  4098. {"Accept-Encoding", ""},
  4099. });
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4102. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(true, res->has_header("Content-Range"));
  4104. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4105. EXPECT_EQ(std::string("abcdefg"), res->body);
  4106. }
  4107. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4108. auto res =
  4109. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4112. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4113. EXPECT_EQ(false, res->has_header("Content-Range"));
  4114. EXPECT_EQ(267U, res->body.size());
  4115. // Check that both range contents are present
  4116. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4117. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4118. // Check that Content-Range headers are present for both ranges
  4119. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4120. std::string::npos);
  4121. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4122. std::string::npos);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4125. Ranges ranges;
  4126. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4127. ranges.emplace_back(0, -1);
  4128. }
  4129. auto res =
  4130. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4131. ASSERT_TRUE(res);
  4132. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4133. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4134. EXPECT_EQ(false, res->has_header("Content-Range"));
  4135. EXPECT_EQ(0U, res->body.size());
  4136. }
  4137. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4138. auto res =
  4139. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4142. EXPECT_EQ(5U, res->body.size());
  4143. // Check that overlapping ranges are coalesced into a single range
  4144. EXPECT_EQ("bcdef", res->body);
  4145. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4146. // Should be single range, not multipart
  4147. EXPECT_TRUE(res->has_header("Content-Range"));
  4148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4149. }
  4150. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4151. auto res =
  4152. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4155. EXPECT_EQ(268U, res->body.size());
  4156. // Check that both range contents are present
  4157. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4158. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4159. // Check that Content-Range headers are present for both ranges
  4160. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4161. std::string::npos);
  4162. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4163. std::string::npos);
  4164. }
  4165. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4166. auto res =
  4167. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4170. EXPECT_EQ(269U, res->body.size());
  4171. // Check that both duplicate range contents are present
  4172. size_t first_abc = res->body.find("abc\r\n");
  4173. EXPECT_TRUE(first_abc != std::string::npos);
  4174. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4175. EXPECT_TRUE(second_abc != std::string::npos);
  4176. // Check that Content-Range headers are present for both ranges
  4177. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4178. EXPECT_TRUE(first_range != std::string::npos);
  4179. size_t second_range =
  4180. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4181. EXPECT_TRUE(second_range != std::string::npos);
  4182. }
  4183. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4184. auto res = cli_.Get("/streamed-with-range?error",
  4185. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4188. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4189. EXPECT_EQ(false, res->has_header("Content-Range"));
  4190. EXPECT_EQ(0U, res->body.size());
  4191. }
  4192. TEST_F(ServerTest, GetStreamedEndless) {
  4193. uint64_t offset = 0;
  4194. auto res = cli_.Get("/streamed-cancel",
  4195. [&](const char * /*data*/, uint64_t data_length) {
  4196. if (offset < 100) {
  4197. offset += data_length;
  4198. return true;
  4199. }
  4200. return false;
  4201. });
  4202. ASSERT_TRUE(!res);
  4203. EXPECT_EQ(Error::Canceled, res.error());
  4204. }
  4205. TEST_F(ServerTest, ClientStop) {
  4206. std::atomic_size_t count{4};
  4207. std::vector<std::thread> threads;
  4208. for (auto i = count.load(); i != 0; --i) {
  4209. threads.emplace_back([&]() {
  4210. auto res = cli_.Get("/streamed-cancel",
  4211. [&](const char *, uint64_t) { return true; });
  4212. --count;
  4213. ASSERT_TRUE(!res);
  4214. EXPECT_TRUE(res.error() == Error::Canceled ||
  4215. res.error() == Error::Read || res.error() == Error::Write);
  4216. });
  4217. }
  4218. std::this_thread::sleep_for(std::chrono::seconds(2));
  4219. while (count != 0) {
  4220. cli_.stop();
  4221. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4222. }
  4223. for (auto &t : threads) {
  4224. t.join();
  4225. }
  4226. }
  4227. TEST_F(ServerTest, GetWithRange1) {
  4228. auto res = cli_.Get("/with-range", {
  4229. make_range_header({{3, 5}}),
  4230. {"Accept-Encoding", ""},
  4231. });
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("def"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetWithRange2) {
  4240. auto res = cli_.Get("/with-range", {
  4241. make_range_header({{1, -1}}),
  4242. {"Accept-Encoding", ""},
  4243. });
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4246. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4247. EXPECT_EQ(true, res->has_header("Content-Range"));
  4248. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4249. EXPECT_EQ(std::string("bcdefg"), res->body);
  4250. }
  4251. TEST_F(ServerTest, GetWithRange3) {
  4252. auto res = cli_.Get("/with-range", {
  4253. make_range_header({{0, 0}}),
  4254. {"Accept-Encoding", ""},
  4255. });
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4258. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4259. EXPECT_EQ(true, res->has_header("Content-Range"));
  4260. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4261. EXPECT_EQ(std::string("a"), res->body);
  4262. }
  4263. TEST_F(ServerTest, GetWithRange4) {
  4264. auto res = cli_.Get("/with-range", {
  4265. make_range_header({{-1, 2}}),
  4266. {"Accept-Encoding", ""},
  4267. });
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4270. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4271. EXPECT_EQ(true, res->has_header("Content-Range"));
  4272. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4273. EXPECT_EQ(std::string("fg"), res->body);
  4274. }
  4275. TEST_F(ServerTest, GetWithRange5) {
  4276. auto res = cli_.Get("/with-range", {
  4277. make_range_header({{0, 5}}),
  4278. {"Accept-Encoding", ""},
  4279. });
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4282. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4283. EXPECT_EQ(true, res->has_header("Content-Range"));
  4284. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4285. EXPECT_EQ(std::string("abcdef"), res->body);
  4286. }
  4287. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4288. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4291. }
  4292. TEST_F(ServerTest, GetWithRangeMultipart) {
  4293. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4296. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4297. EXPECT_EQ(false, res->has_header("Content-Range"));
  4298. EXPECT_EQ(267U, res->body.size());
  4299. }
  4300. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4301. auto res =
  4302. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4305. }
  4306. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4307. auto res = cli_.Get("/with-range-customized-response",
  4308. {{make_range_header({{1, 2}})}});
  4309. ASSERT_TRUE(res);
  4310. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4311. EXPECT_EQ(true, res->has_header("Content-Length"));
  4312. EXPECT_EQ(false, res->has_header("Content-Range"));
  4313. EXPECT_EQ(JSON_DATA, res->body);
  4314. }
  4315. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4316. auto res = cli_.Get("/with-range-customized-response",
  4317. {{make_range_header({{1, 2}, {4, 5}})}});
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4320. EXPECT_EQ(true, res->has_header("Content-Length"));
  4321. EXPECT_EQ(false, res->has_header("Content-Range"));
  4322. EXPECT_EQ(JSON_DATA, res->body);
  4323. }
  4324. TEST_F(ServerTest, Issue1772) {
  4325. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4328. }
  4329. TEST_F(ServerTest, Issue609) {
  4330. auto res = cli_.Delete("/issue609");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. EXPECT_EQ(std::string("ok"), res->body);
  4334. }
  4335. TEST_F(ServerTest, GetStreamedChunked) {
  4336. auto res = cli_.Get("/streamed-chunked");
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::OK_200, res->status);
  4339. EXPECT_EQ(std::string("123456789"), res->body);
  4340. }
  4341. TEST_F(ServerTest, GetStreamedChunked2) {
  4342. auto res = cli_.Get("/streamed-chunked2");
  4343. ASSERT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. EXPECT_EQ(std::string("123456789"), res->body);
  4346. }
  4347. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4348. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. EXPECT_EQ(std::string("123456789"), res->body);
  4352. EXPECT_TRUE(res->has_header("Trailer"));
  4353. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4354. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4355. // Trailers are now stored separately from headers (security fix)
  4356. EXPECT_EQ(2U, res->trailers.size());
  4357. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4358. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4359. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4360. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4361. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4362. // Verify trailers are NOT in headers (security verification)
  4363. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4364. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4365. }
  4366. TEST_F(ServerTest, LargeChunkedPost) {
  4367. Request req;
  4368. req.method = "POST";
  4369. req.path = "/large-chunked";
  4370. std::string host_and_port;
  4371. host_and_port += HOST;
  4372. host_and_port += ":";
  4373. host_and_port += std::to_string(PORT);
  4374. req.headers.emplace("Host", host_and_port.c_str());
  4375. req.headers.emplace("Accept", "*/*");
  4376. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4377. req.headers.emplace("Content-Type", "text/plain");
  4378. req.headers.emplace("Content-Length", "0");
  4379. req.headers.emplace("Transfer-Encoding", "chunked");
  4380. std::string long_string(30 * 1024u, 'a');
  4381. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4382. // Attempt to make a large enough post to exceed OS buffers, to test that
  4383. // the server handles short reads if the full chunk data isn't available.
  4384. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4385. auto res = std::make_shared<Response>();
  4386. auto error = Error::Success;
  4387. auto ret = cli_.send(req, *res, error);
  4388. ASSERT_TRUE(ret);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. }
  4391. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4392. auto res = cli_.Get("/remote_addr");
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::OK_200, res->status);
  4395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4396. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4397. }
  4398. TEST_F(ServerTest, GetMethodLocalAddr) {
  4399. auto res = cli_.Get("/local_addr");
  4400. ASSERT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4403. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4404. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4405. }
  4406. TEST_F(ServerTest, HTTPResponseSplitting) {
  4407. auto res = cli_.Get("/http_response_splitting");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. }
  4411. TEST_F(ServerTest, SlowRequest) {
  4412. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4413. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4414. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4415. }
  4416. #if 0
  4417. TEST_F(ServerTest, SlowPost) {
  4418. char buffer[64 * 1024];
  4419. memset(buffer, 0x42, sizeof(buffer));
  4420. auto res = cli_.Post(
  4421. "/slowpost", 64 * 1024 * 1024,
  4422. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4423. auto ret = sink.write(buffer, sizeof(buffer));
  4424. EXPECT_TRUE(ret);
  4425. return true;
  4426. },
  4427. "text/plain");
  4428. ASSERT_TRUE(res);
  4429. EXPECT_EQ(StatusCode::OK_200, res->status);
  4430. }
  4431. TEST_F(ServerTest, SlowPostFail) {
  4432. char buffer[64 * 1024];
  4433. memset(buffer, 0x42, sizeof(buffer));
  4434. cli_.set_write_timeout(std::chrono::seconds(0));
  4435. auto res = cli_.Post(
  4436. "/slowpost", 64 * 1024 * 1024,
  4437. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4438. sink.write(buffer, sizeof(buffer));
  4439. return true;
  4440. },
  4441. "text/plain");
  4442. ASSERT_TRUE(!res);
  4443. EXPECT_EQ(Error::Write, res.error());
  4444. }
  4445. #endif
  4446. TEST_F(ServerTest, Put) {
  4447. auto res = cli_.Put("/put", "PUT", "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, PutWithContentProvider) {
  4453. auto res = cli_.Put(
  4454. "/put", 3,
  4455. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4456. sink.os << "PUT";
  4457. return true;
  4458. },
  4459. "text/plain");
  4460. ASSERT_TRUE(res);
  4461. EXPECT_EQ(StatusCode::OK_200, res->status);
  4462. EXPECT_EQ("PUT", res->body);
  4463. }
  4464. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4465. auto res = cli_.Post(
  4466. "/post", 42,
  4467. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4468. return false;
  4469. },
  4470. "text/plain");
  4471. ASSERT_TRUE(!res);
  4472. EXPECT_EQ(Error::Canceled, res.error());
  4473. }
  4474. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4475. auto res = cli_.Put(
  4476. "/put",
  4477. [](size_t /*offset*/, DataSink &sink) {
  4478. sink.os << "PUT";
  4479. sink.done();
  4480. return true;
  4481. },
  4482. "text/plain");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ("PUT", res->body);
  4486. }
  4487. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4488. auto res = cli_.Post(
  4489. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4490. "text/plain");
  4491. ASSERT_TRUE(!res);
  4492. EXPECT_EQ(Error::Canceled, res.error());
  4493. }
  4494. TEST_F(ServerTest, PostLoopBack) {
  4495. std::string body;
  4496. auto res = cli_.Post(
  4497. "/post-loopback", 9,
  4498. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4499. EXPECT_EQ(9u, length);
  4500. sink.write("123", 3);
  4501. sink.write("456", 3);
  4502. sink.write("789", 3);
  4503. return true;
  4504. },
  4505. "text/plain",
  4506. [&body](const char *data, size_t data_length) {
  4507. body.append(data, data_length);
  4508. return true;
  4509. });
  4510. ASSERT_TRUE(res);
  4511. EXPECT_EQ(StatusCode::OK_200, res->status);
  4512. EXPECT_EQ("123456789", body);
  4513. }
  4514. TEST_F(ServerTest, PutLoopBack) {
  4515. std::string body;
  4516. auto res = cli_.Put(
  4517. "/put-loopback", 9,
  4518. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4519. EXPECT_EQ(9u, length);
  4520. sink.write("123", 3);
  4521. sink.write("456", 3);
  4522. sink.write("789", 3);
  4523. return true;
  4524. },
  4525. "text/plain",
  4526. [&body](const char *data, size_t data_length) {
  4527. body.append(data, data_length);
  4528. return true;
  4529. });
  4530. ASSERT_TRUE(res);
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("123456789", body);
  4533. }
  4534. TEST_F(ServerTest, PatchLoopBack) {
  4535. std::string body;
  4536. auto res = cli_.Patch(
  4537. "/patch-loopback", 9,
  4538. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4539. EXPECT_EQ(9u, length);
  4540. sink.write("123", 3);
  4541. sink.write("456", 3);
  4542. sink.write("789", 3);
  4543. return true;
  4544. },
  4545. "text/plain",
  4546. [&body](const char *data, size_t data_length) {
  4547. body.append(data, data_length);
  4548. return true;
  4549. });
  4550. ASSERT_TRUE(res);
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("123456789", body);
  4553. }
  4554. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4555. std::string body;
  4556. auto res = cli_.Post(
  4557. "/post-loopback",
  4558. [](size_t /*offset*/, DataSink &sink) {
  4559. sink.write("123", 3);
  4560. sink.write("456", 3);
  4561. sink.write("789", 3);
  4562. sink.done();
  4563. return true;
  4564. },
  4565. "text/plain",
  4566. [&body](const char *data, size_t data_length) {
  4567. body.append(data, data_length);
  4568. return true;
  4569. });
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. EXPECT_EQ("123456789", body);
  4573. }
  4574. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4575. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4576. cli_.set_compress(true);
  4577. auto res = cli_.Put(
  4578. "/put", 3,
  4579. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4580. sink.os << "PUT";
  4581. return true;
  4582. },
  4583. "text/plain");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("PUT", res->body);
  4587. }
  4588. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4589. cli_.set_compress(true);
  4590. auto res = cli_.Post(
  4591. "/post", 42,
  4592. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4593. return false;
  4594. },
  4595. "text/plain");
  4596. ASSERT_TRUE(!res);
  4597. EXPECT_EQ(Error::Canceled, res.error());
  4598. }
  4599. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4600. cli_.set_compress(true);
  4601. auto res = cli_.Put(
  4602. "/put",
  4603. [](size_t /*offset*/, DataSink &sink) {
  4604. sink.os << "PUT";
  4605. sink.done();
  4606. return true;
  4607. },
  4608. "text/plain");
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("PUT", res->body);
  4612. }
  4613. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4614. cli_.set_compress(true);
  4615. auto res = cli_.Post(
  4616. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4617. "text/plain");
  4618. ASSERT_TRUE(!res);
  4619. EXPECT_EQ(Error::Canceled, res.error());
  4620. }
  4621. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4622. cli_.set_compress(true);
  4623. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::OK_200, res->status);
  4626. EXPECT_EQ(LARGE_DATA, res->body);
  4627. }
  4628. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4629. #ifdef CPPHTTPLIB_SSL_ENABLED
  4630. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4631. Client cli(s.c_str());
  4632. cli.enable_server_certificate_verification(false);
  4633. #else
  4634. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4635. Client cli(s.c_str());
  4636. #endif
  4637. cli.set_compress(true);
  4638. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ(LARGE_DATA, res->body);
  4642. // The compressed size should be less than a 10th of the original. May vary
  4643. // depending on the zlib library.
  4644. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4645. static_cast<uint64_t>(10 * 1024 * 1024));
  4646. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4647. }
  4648. TEST_F(ServerTest, PutContentWithDeflate) {
  4649. cli_.set_compress(false);
  4650. Headers headers;
  4651. headers.emplace("Content-Encoding", "deflate");
  4652. // PUT in deflate format:
  4653. auto res = cli_.Put("/put", headers,
  4654. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("PUT", res->body);
  4658. }
  4659. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4660. Headers headers;
  4661. headers.emplace("Accept-Encoding", "gzip, deflate");
  4662. auto res = cli_.Get("/streamed-chunked", headers);
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::OK_200, res->status);
  4665. EXPECT_EQ(std::string("123456789"), res->body);
  4666. }
  4667. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4668. Headers headers;
  4669. headers.emplace("Accept-Encoding", "gzip, deflate");
  4670. auto res = cli_.Get("/streamed-chunked2", headers);
  4671. ASSERT_TRUE(res);
  4672. EXPECT_EQ(StatusCode::OK_200, res->status);
  4673. EXPECT_EQ(std::string("123456789"), res->body);
  4674. }
  4675. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4676. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4677. ASSERT_TRUE(res);
  4678. EXPECT_EQ(StatusCode::OK_200, res->status);
  4679. }
  4680. TEST(GzipDecompressor, ChunkedDecompression) {
  4681. std::string data;
  4682. for (size_t i = 0; i < 32 * 1024; ++i) {
  4683. data.push_back(static_cast<char>('a' + i % 26));
  4684. }
  4685. std::string compressed_data;
  4686. {
  4687. httplib::detail::gzip_compressor compressor;
  4688. bool result = compressor.compress(
  4689. data.data(), data.size(),
  4690. /*last=*/true,
  4691. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4692. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4693. compressed_data_size);
  4694. return true;
  4695. });
  4696. ASSERT_TRUE(result);
  4697. }
  4698. std::string decompressed_data;
  4699. {
  4700. httplib::detail::gzip_decompressor decompressor;
  4701. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4702. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4703. size_t chunk_size = 130;
  4704. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4705. chunk_begin += chunk_size) {
  4706. size_t current_chunk_size =
  4707. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4708. bool result = decompressor.decompress(
  4709. compressed_data.data() + chunk_begin, current_chunk_size,
  4710. [&](const char *decompressed_data_chunk,
  4711. size_t decompressed_data_chunk_size) {
  4712. decompressed_data.insert(decompressed_data.size(),
  4713. decompressed_data_chunk,
  4714. decompressed_data_chunk_size);
  4715. return true;
  4716. });
  4717. ASSERT_TRUE(result);
  4718. }
  4719. }
  4720. ASSERT_EQ(data, decompressed_data);
  4721. }
  4722. TEST(GzipDecompressor, DeflateDecompression) {
  4723. std::string original_text = "Raw deflate without gzip";
  4724. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4725. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4726. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4727. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4728. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4729. std::string decompressed_data;
  4730. {
  4731. httplib::detail::gzip_decompressor decompressor;
  4732. bool result = decompressor.decompress(
  4733. compressed_data.data(), compressed_data.size(),
  4734. [&](const char *decompressed_data_chunk,
  4735. size_t decompressed_data_chunk_size) {
  4736. decompressed_data.insert(decompressed_data.size(),
  4737. decompressed_data_chunk,
  4738. decompressed_data_chunk_size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. }
  4743. ASSERT_EQ(original_text, decompressed_data);
  4744. }
  4745. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4746. std::string original_text = "Raw deflate without gzip";
  4747. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4748. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4749. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4750. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4751. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4752. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4753. std::string decompressed_data;
  4754. {
  4755. httplib::detail::gzip_decompressor decompressor;
  4756. bool result = decompressor.decompress(
  4757. compressed_data.data(), compressed_data.size(),
  4758. [&](const char *decompressed_data_chunk,
  4759. size_t decompressed_data_chunk_size) {
  4760. decompressed_data.insert(decompressed_data.size(),
  4761. decompressed_data_chunk,
  4762. decompressed_data_chunk_size);
  4763. return true;
  4764. });
  4765. ASSERT_TRUE(result);
  4766. }
  4767. ASSERT_EQ(original_text, decompressed_data);
  4768. }
  4769. #ifdef _WIN32
  4770. TEST(GzipDecompressor, LargeRandomData) {
  4771. // prepare large random data that is difficult to be compressed and is
  4772. // expected to have large size even when compressed
  4773. std::random_device seed_gen;
  4774. std::mt19937 random(seed_gen());
  4775. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4776. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4777. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4778. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4779. // compress data over 4GiB
  4780. std::string compressed_data;
  4781. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4782. httplib::detail::gzip_compressor compressor;
  4783. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4784. data.size() * sizeof(std::uint32_t), true,
  4785. [&](const char *data, size_t size) {
  4786. compressed_data.insert(
  4787. compressed_data.size(), data, size);
  4788. return true;
  4789. });
  4790. ASSERT_TRUE(result);
  4791. // FIXME: compressed data size is expected to be greater than 4GiB,
  4792. // but there is no guarantee
  4793. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4794. // decompress data over 4GiB
  4795. std::string decompressed_data;
  4796. decompressed_data.reserve(data_size);
  4797. httplib::detail::gzip_decompressor decompressor;
  4798. result = decompressor.decompress(
  4799. compressed_data.data(), compressed_data.size(),
  4800. [&](const char *data, size_t size) {
  4801. decompressed_data.insert(decompressed_data.size(), data, size);
  4802. return true;
  4803. });
  4804. ASSERT_TRUE(result);
  4805. // compare
  4806. ASSERT_EQ(data_size, decompressed_data.size());
  4807. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4808. 0);
  4809. }
  4810. #endif
  4811. #endif
  4812. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4813. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4814. Headers headers;
  4815. headers.emplace("Accept-Encoding", "br");
  4816. auto res = cli_.Get("/streamed-chunked", headers);
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::OK_200, res->status);
  4819. EXPECT_EQ(std::string("123456789"), res->body);
  4820. }
  4821. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4822. Headers headers;
  4823. headers.emplace("Accept-Encoding", "br");
  4824. auto res = cli_.Get("/streamed-chunked2", headers);
  4825. ASSERT_TRUE(res);
  4826. EXPECT_EQ(StatusCode::OK_200, res->status);
  4827. EXPECT_EQ(std::string("123456789"), res->body);
  4828. }
  4829. #endif
  4830. TEST_F(ServerTest, Patch) {
  4831. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::OK_200, res->status);
  4834. EXPECT_EQ("PATCH", res->body);
  4835. }
  4836. TEST_F(ServerTest, Delete) {
  4837. auto res = cli_.Delete("/delete");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("DELETE", res->body);
  4841. }
  4842. TEST_F(ServerTest, DeleteContentReceiver) {
  4843. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("content", res->body);
  4847. }
  4848. TEST_F(ServerTest, Options) {
  4849. auto res = cli_.Options("*");
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::OK_200, res->status);
  4852. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4853. EXPECT_TRUE(res->body.empty());
  4854. }
  4855. TEST_F(ServerTest, URL) {
  4856. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. }
  4860. TEST_F(ServerTest, ArrayParam) {
  4861. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4862. ASSERT_TRUE(res);
  4863. EXPECT_EQ(StatusCode::OK_200, res->status);
  4864. }
  4865. TEST_F(ServerTest, NoMultipleHeaders) {
  4866. Headers headers = {{"Content-Length", "5"}};
  4867. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4868. "text/plain");
  4869. ASSERT_TRUE(res);
  4870. EXPECT_EQ(StatusCode::OK_200, res->status);
  4871. }
  4872. TEST_F(ServerTest, PostContentReceiver) {
  4873. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4874. ASSERT_TRUE(res);
  4875. ASSERT_EQ(StatusCode::OK_200, res->status);
  4876. ASSERT_EQ("content", res->body);
  4877. }
  4878. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  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 res = cli_.Post("/content_receiver", items);
  4887. ASSERT_TRUE(res);
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. }
  4890. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4891. UploadFormDataItems items = {
  4892. {"text1", "text default", "", ""},
  4893. {"text2", "aωb", "", ""},
  4894. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4895. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4896. {"file3", "", "", "application/octet-stream"},
  4897. };
  4898. auto boundary = std::string("+++++");
  4899. std::string body;
  4900. for (const auto &item : items) {
  4901. body += "--" + boundary + "\r\n";
  4902. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4903. if (!item.filename.empty()) {
  4904. body += "; filename=\"" + item.filename + "\"";
  4905. }
  4906. body += "\r\n";
  4907. if (!item.content_type.empty()) {
  4908. body += "Content-Type: " + item.content_type + "\r\n";
  4909. }
  4910. body += "\r\n";
  4911. body += item.content + "\r\n";
  4912. }
  4913. body += "--" + boundary + "--\r\n";
  4914. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4915. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4916. ASSERT_TRUE(res);
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. }
  4919. TEST_F(ServerTest, PostContentReceiverGzip) {
  4920. cli_.set_compress(true);
  4921. auto res = cli_.Post("/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. TEST_F(ServerTest, PutContentReceiver) {
  4927. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4928. ASSERT_TRUE(res);
  4929. ASSERT_EQ(StatusCode::OK_200, res->status);
  4930. ASSERT_EQ("content", res->body);
  4931. }
  4932. TEST_F(ServerTest, PatchContentReceiver) {
  4933. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4934. ASSERT_TRUE(res);
  4935. ASSERT_EQ(StatusCode::OK_200, res->status);
  4936. ASSERT_EQ("content", res->body);
  4937. }
  4938. template <typename ClientType>
  4939. void TestWithHeadersAndContentReceiver(
  4940. ClientType &cli,
  4941. std::function<Result(ClientType &, const std::string &, const Headers &,
  4942. const std::string &, const std::string &,
  4943. ContentReceiver, DownloadProgress)>
  4944. request_func) {
  4945. Headers headers;
  4946. headers.emplace("X-Custom-Header", "test-value");
  4947. std::string received_body;
  4948. auto res = request_func(
  4949. cli, "/content_receiver", headers, "content", "application/json",
  4950. [&](const char *data, size_t data_length) {
  4951. received_body.append(data, data_length);
  4952. return true;
  4953. },
  4954. nullptr);
  4955. ASSERT_TRUE(res);
  4956. EXPECT_EQ(StatusCode::OK_200, res->status);
  4957. EXPECT_EQ("content", received_body);
  4958. }
  4959. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4960. #ifdef CPPHTTPLIB_SSL_ENABLED
  4961. using ClientT = SSLClient;
  4962. #else
  4963. using ClientT = Client;
  4964. #endif
  4965. TestWithHeadersAndContentReceiver<ClientT>(
  4966. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4967. const std::string &body, const std::string &content_type,
  4968. ContentReceiver receiver, DownloadProgress progress) {
  4969. return cli.Post(path, headers, body, content_type, receiver, progress);
  4970. });
  4971. }
  4972. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4973. #ifdef CPPHTTPLIB_SSL_ENABLED
  4974. using ClientT = SSLClient;
  4975. #else
  4976. using ClientT = Client;
  4977. #endif
  4978. TestWithHeadersAndContentReceiver<ClientT>(
  4979. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4980. const std::string &body, const std::string &content_type,
  4981. ContentReceiver receiver, DownloadProgress progress) {
  4982. return cli.Put(path, headers, body, content_type, receiver, progress);
  4983. });
  4984. }
  4985. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4986. #ifdef CPPHTTPLIB_SSL_ENABLED
  4987. using ClientT = SSLClient;
  4988. #else
  4989. using ClientT = Client;
  4990. #endif
  4991. TestWithHeadersAndContentReceiver<ClientT>(
  4992. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4993. const std::string &body, const std::string &content_type,
  4994. ContentReceiver receiver, DownloadProgress progress) {
  4995. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4996. });
  4997. }
  4998. template <typename ClientType>
  4999. void TestWithHeadersAndContentReceiverWithProgress(
  5000. ClientType &cli,
  5001. std::function<Result(ClientType &, const std::string &, const Headers &,
  5002. const std::string &, const std::string &,
  5003. ContentReceiver, DownloadProgress)>
  5004. request_func) {
  5005. Headers headers;
  5006. headers.emplace("X-Test-Header", "progress-test");
  5007. std::string received_body;
  5008. auto progress_called = false;
  5009. auto res = request_func(
  5010. cli, "/content_receiver", headers, "content", "text/plain",
  5011. [&](const char *data, size_t data_length) {
  5012. received_body.append(data, data_length);
  5013. return true;
  5014. },
  5015. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5016. progress_called = true;
  5017. return true;
  5018. });
  5019. ASSERT_TRUE(res);
  5020. EXPECT_EQ(StatusCode::OK_200, res->status);
  5021. EXPECT_EQ("content", received_body);
  5022. EXPECT_TRUE(progress_called);
  5023. }
  5024. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5025. #ifdef CPPHTTPLIB_SSL_ENABLED
  5026. using ClientT = SSLClient;
  5027. #else
  5028. using ClientT = Client;
  5029. #endif
  5030. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5031. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5032. const std::string &body, const std::string &content_type,
  5033. ContentReceiver receiver, DownloadProgress progress) {
  5034. return cli.Post(path, headers, body, content_type, receiver, progress);
  5035. });
  5036. }
  5037. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5038. #ifdef CPPHTTPLIB_SSL_ENABLED
  5039. using ClientT = SSLClient;
  5040. #else
  5041. using ClientT = Client;
  5042. #endif
  5043. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5044. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5045. const std::string &body, const std::string &content_type,
  5046. ContentReceiver receiver, DownloadProgress progress) {
  5047. return cli.Put(path, headers, body, content_type, receiver, progress);
  5048. });
  5049. }
  5050. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5051. #ifdef CPPHTTPLIB_SSL_ENABLED
  5052. using ClientT = SSLClient;
  5053. #else
  5054. using ClientT = Client;
  5055. #endif
  5056. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5057. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5058. const std::string &body, const std::string &content_type,
  5059. ContentReceiver receiver, DownloadProgress progress) {
  5060. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5061. });
  5062. }
  5063. template <typename ClientType>
  5064. void TestWithHeadersAndContentReceiverError(
  5065. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5066. const Headers &, const std::string &,
  5067. const std::string &, ContentReceiver)>
  5068. request_func) {
  5069. Headers headers;
  5070. headers.emplace("X-Error-Test", "true");
  5071. std::string received_body;
  5072. auto receiver_failed = false;
  5073. auto res =
  5074. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5075. [&](const char *data, size_t data_length) {
  5076. received_body.append(data, data_length);
  5077. receiver_failed = true;
  5078. return false;
  5079. });
  5080. ASSERT_FALSE(res);
  5081. EXPECT_TRUE(receiver_failed);
  5082. }
  5083. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5084. #ifdef CPPHTTPLIB_SSL_ENABLED
  5085. using ClientT = SSLClient;
  5086. #else
  5087. using ClientT = Client;
  5088. #endif
  5089. TestWithHeadersAndContentReceiverError<ClientT>(
  5090. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5091. const std::string &body, const std::string &content_type,
  5092. ContentReceiver receiver) {
  5093. return cli.Post(path, headers, body, content_type, receiver);
  5094. });
  5095. }
  5096. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5097. #ifdef CPPHTTPLIB_SSL_ENABLED
  5098. using ClientT = SSLClient;
  5099. #else
  5100. using ClientT = Client;
  5101. #endif
  5102. TestWithHeadersAndContentReceiverError<ClientT>(
  5103. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5104. const std::string &body, const std::string &content_type,
  5105. ContentReceiver receiver) {
  5106. return cli.Put(path, headers, body, content_type, receiver);
  5107. });
  5108. }
  5109. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5110. #ifdef CPPHTTPLIB_SSL_ENABLED
  5111. using ClientT = SSLClient;
  5112. #else
  5113. using ClientT = Client;
  5114. #endif
  5115. TestWithHeadersAndContentReceiverError<ClientT>(
  5116. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5117. const std::string &body, const std::string &content_type,
  5118. ContentReceiver receiver) {
  5119. return cli.Patch(path, headers, body, content_type, receiver);
  5120. });
  5121. }
  5122. TEST_F(ServerTest, PostQueryStringAndBody) {
  5123. auto res =
  5124. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5125. ASSERT_TRUE(res);
  5126. ASSERT_EQ(StatusCode::OK_200, res->status);
  5127. }
  5128. TEST_F(ServerTest, HTTP2Magic) {
  5129. Request req;
  5130. req.method = "PRI";
  5131. req.path = "*";
  5132. req.body = "SM";
  5133. auto res = std::make_shared<Response>();
  5134. auto error = Error::Success;
  5135. auto ret = cli_.send(req, *res, error);
  5136. ASSERT_TRUE(ret);
  5137. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5138. }
  5139. TEST_F(ServerTest, KeepAlive) {
  5140. auto res = cli_.Get("/hi");
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5144. EXPECT_EQ("Hello World!", res->body);
  5145. res = cli_.Get("/hi");
  5146. ASSERT_TRUE(res);
  5147. EXPECT_EQ(StatusCode::OK_200, res->status);
  5148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5149. EXPECT_EQ("Hello World!", res->body);
  5150. res = cli_.Get("/hi");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("Hello World!", res->body);
  5155. res = cli_.Get("/not-exist");
  5156. ASSERT_TRUE(res);
  5157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5158. res = cli_.Post("/empty", "", "text/plain");
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ(StatusCode::OK_200, res->status);
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_EQ("empty", res->body);
  5163. EXPECT_EQ("close", res->get_header_value("Connection"));
  5164. res = cli_.Post(
  5165. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5166. "text/plain");
  5167. ASSERT_TRUE(res);
  5168. EXPECT_EQ(StatusCode::OK_200, res->status);
  5169. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5170. EXPECT_EQ("empty", res->body);
  5171. cli_.set_keep_alive(false);
  5172. res = cli_.Get("/last-request");
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. EXPECT_EQ("close", res->get_header_value("Connection"));
  5176. }
  5177. TEST_F(ServerTest, TooManyRedirect) {
  5178. cli_.set_follow_location(true);
  5179. auto res = cli_.Get("/redirect/0");
  5180. ASSERT_TRUE(!res);
  5181. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5182. }
  5183. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5184. Request req;
  5185. req.method = "FOOBAR";
  5186. req.path = "/hi";
  5187. cli_.set_keep_alive(true);
  5188. auto res = cli_.send(req);
  5189. ASSERT_TRUE(res);
  5190. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5191. EXPECT_EQ("close", res->get_header_value("Connection"));
  5192. EXPECT_FALSE(cli_.is_socket_open());
  5193. }
  5194. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5195. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5196. TEST_F(ServerTest, Gzip) {
  5197. Headers headers;
  5198. headers.emplace("Accept-Encoding", "gzip, deflate");
  5199. auto res = cli_.Get("/compress", headers);
  5200. ASSERT_TRUE(res);
  5201. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5203. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5204. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5205. "7890123456789012345678901234567890",
  5206. res->body);
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5210. Headers headers;
  5211. headers.emplace("Accept-Encoding", "");
  5212. auto res = cli_.Get("/compress", headers);
  5213. ASSERT_TRUE(res);
  5214. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5216. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5217. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5218. "7890123456789012345678901234567890",
  5219. res->body);
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. }
  5222. TEST_F(ServerTest, GzipWithContentReceiver) {
  5223. Headers headers;
  5224. headers.emplace("Accept-Encoding", "gzip, deflate");
  5225. std::string body;
  5226. auto res = cli_.Get("/compress", headers,
  5227. [&](const char *data, uint64_t data_length) {
  5228. EXPECT_EQ(100U, data_length);
  5229. body.append(data, data_length);
  5230. return true;
  5231. });
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5237. "7890123456789012345678901234567890",
  5238. body);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "gzip, deflate");
  5244. cli_.set_decompress(false);
  5245. auto res = cli_.Get("/compress", headers);
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5250. EXPECT_EQ(33U, res->body.size());
  5251. EXPECT_EQ(StatusCode::OK_200, res->status);
  5252. }
  5253. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5254. Headers headers;
  5255. headers.emplace("Accept-Encoding", "");
  5256. std::string body;
  5257. auto res = cli_.Get("/compress", headers,
  5258. [&](const char *data, uint64_t data_length) {
  5259. EXPECT_EQ(100U, data_length);
  5260. body.append(data, data_length);
  5261. return true;
  5262. });
  5263. ASSERT_TRUE(res);
  5264. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5265. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5266. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5267. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5268. "7890123456789012345678901234567890",
  5269. body);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. }
  5272. TEST_F(ServerTest, NoGzip) {
  5273. Headers headers;
  5274. headers.emplace("Accept-Encoding", "gzip, deflate");
  5275. auto res = cli_.Get("/nocompress", headers);
  5276. ASSERT_TRUE(res);
  5277. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5278. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5279. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5280. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5281. "7890123456789012345678901234567890",
  5282. res->body);
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. }
  5285. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5286. Headers headers;
  5287. headers.emplace("Accept-Encoding", "gzip, deflate");
  5288. std::string body;
  5289. auto res = cli_.Get("/nocompress", headers,
  5290. [&](const char *data, uint64_t data_length) {
  5291. EXPECT_EQ(100U, data_length);
  5292. body.append(data, data_length);
  5293. return true;
  5294. });
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5297. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5298. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5299. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5300. "7890123456789012345678901234567890",
  5301. body);
  5302. EXPECT_EQ(StatusCode::OK_200, res->status);
  5303. }
  5304. TEST_F(ServerTest, MultipartFormDataGzip) {
  5305. UploadFormDataItems items = {
  5306. {"key1", "test", "", ""},
  5307. {"key2", "--abcdefg123", "", ""},
  5308. };
  5309. cli_.set_compress(true);
  5310. auto res = cli_.Post("/compress-multipart", items);
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. }
  5314. #endif
  5315. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5316. TEST_F(ServerTest, Brotli) {
  5317. Headers headers;
  5318. headers.emplace("Accept-Encoding", "br");
  5319. auto res = cli_.Get("/compress", headers);
  5320. ASSERT_TRUE(res);
  5321. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5323. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5324. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5325. "7890123456789012345678901234567890",
  5326. res->body);
  5327. EXPECT_EQ(StatusCode::OK_200, res->status);
  5328. }
  5329. #endif
  5330. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5331. TEST_F(ServerTest, Zstd) {
  5332. Headers headers;
  5333. headers.emplace("Accept-Encoding", "zstd");
  5334. auto res = cli_.Get("/compress", headers);
  5335. ASSERT_TRUE(res);
  5336. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5338. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5339. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5340. "7890123456789012345678901234567890",
  5341. res->body);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. }
  5344. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5345. Headers headers;
  5346. headers.emplace("Accept-Encoding", "");
  5347. auto res = cli_.Get("/compress", headers);
  5348. ASSERT_TRUE(res);
  5349. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5350. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5351. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5352. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5353. "7890123456789012345678901234567890",
  5354. res->body);
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. }
  5357. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5358. Headers headers;
  5359. headers.emplace("Accept-Encoding", "zstd");
  5360. std::string body;
  5361. auto res = cli_.Get("/compress", headers,
  5362. [&](const char *data, uint64_t data_length) {
  5363. EXPECT_EQ(100U, data_length);
  5364. body.append(data, data_length);
  5365. return true;
  5366. });
  5367. ASSERT_TRUE(res);
  5368. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5369. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5370. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5371. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5372. "7890123456789012345678901234567890",
  5373. body);
  5374. EXPECT_EQ(StatusCode::OK_200, res->status);
  5375. }
  5376. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5377. Headers headers;
  5378. headers.emplace("Accept-Encoding", "zstd");
  5379. cli_.set_decompress(false);
  5380. auto res = cli_.Get("/compress", headers);
  5381. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5382. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5383. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5384. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5385. ASSERT_TRUE(res);
  5386. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5387. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5388. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. ASSERT_EQ(26U, res->body.size());
  5391. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5392. 0);
  5393. }
  5394. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5395. Headers headers;
  5396. headers.emplace("Accept-Encoding", "");
  5397. std::string body;
  5398. auto res = cli_.Get("/compress", headers,
  5399. [&](const char *data, uint64_t data_length) {
  5400. EXPECT_EQ(100U, data_length);
  5401. body.append(data, data_length);
  5402. return true;
  5403. });
  5404. ASSERT_TRUE(res);
  5405. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5406. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5407. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5408. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5409. "7890123456789012345678901234567890",
  5410. body);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. }
  5413. TEST_F(ServerTest, NoZstd) {
  5414. Headers headers;
  5415. headers.emplace("Accept-Encoding", "zstd");
  5416. auto res = cli_.Get("/nocompress", headers);
  5417. ASSERT_TRUE(res);
  5418. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5419. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5420. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5421. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5422. "7890123456789012345678901234567890",
  5423. res->body);
  5424. EXPECT_EQ(StatusCode::OK_200, res->status);
  5425. }
  5426. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5427. Headers headers;
  5428. headers.emplace("Accept-Encoding", "zstd");
  5429. std::string body;
  5430. auto res = cli_.Get("/nocompress", headers,
  5431. [&](const char *data, uint64_t data_length) {
  5432. EXPECT_EQ(100U, data_length);
  5433. body.append(data, data_length);
  5434. return true;
  5435. });
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5438. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5439. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5440. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5441. "7890123456789012345678901234567890",
  5442. body);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. // TODO: How to enable zstd ??
  5446. TEST_F(ServerTest, MultipartFormDataZstd) {
  5447. UploadFormDataItems items = {
  5448. {"key1", "test", "", ""},
  5449. {"key2", "--abcdefg123", "", ""},
  5450. };
  5451. Headers headers;
  5452. headers.emplace("Accept-Encoding", "zstd");
  5453. cli_.set_compress(true);
  5454. auto res = cli_.Post("/compress-multipart", headers, items);
  5455. ASSERT_TRUE(res);
  5456. EXPECT_EQ(StatusCode::OK_200, res->status);
  5457. }
  5458. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5459. Headers headers;
  5460. headers.emplace("Accept-Encoding", "zstd");
  5461. cli_.set_compress(true);
  5462. auto res = cli_.Put(
  5463. "/put", headers, 3,
  5464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5465. sink.os << "PUT";
  5466. return true;
  5467. },
  5468. "text/plain");
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ(StatusCode::OK_200, res->status);
  5471. EXPECT_EQ("PUT", res->body);
  5472. }
  5473. // Pre-compression logging tests
  5474. TEST_F(ServerTest, PreCompressionLogging) {
  5475. // Test data for compression (matches the actual /compress endpoint content)
  5476. const std::string test_content =
  5477. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5478. "3456789012345678901234567890";
  5479. // Variables to capture logging data
  5480. std::string pre_compression_body;
  5481. std::string pre_compression_content_type;
  5482. std::string pre_compression_content_encoding;
  5483. std::string post_compression_body;
  5484. std::string post_compression_content_type;
  5485. std::string post_compression_content_encoding;
  5486. // Set up pre-compression logger
  5487. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5488. const Response &res) {
  5489. pre_compression_body = res.body;
  5490. pre_compression_content_type = res.get_header_value("Content-Type");
  5491. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5492. });
  5493. // Set up post-compression logger
  5494. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5495. post_compression_body = res.body;
  5496. post_compression_content_type = res.get_header_value("Content-Type");
  5497. post_compression_content_encoding =
  5498. res.get_header_value("Content-Encoding");
  5499. });
  5500. // Test with gzip compression
  5501. Headers headers;
  5502. headers.emplace("Accept-Encoding", "gzip");
  5503. auto res = cli_.Get("/compress", headers);
  5504. // Verify response was compressed
  5505. ASSERT_TRUE(res);
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5508. // Verify pre-compression logger captured uncompressed content
  5509. EXPECT_EQ(test_content, pre_compression_body);
  5510. EXPECT_EQ("text/plain", pre_compression_content_type);
  5511. EXPECT_TRUE(pre_compression_content_encoding
  5512. .empty()); // No encoding header before compression
  5513. // Verify post-compression logger captured compressed content
  5514. EXPECT_NE(test_content,
  5515. post_compression_body); // Should be different after compression
  5516. EXPECT_EQ("text/plain", post_compression_content_type);
  5517. EXPECT_EQ("gzip", post_compression_content_encoding);
  5518. // Verify compressed content is smaller
  5519. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5520. }
  5521. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5522. const std::string test_content =
  5523. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5524. "3456789012345678901234567890";
  5525. std::string pre_compression_body;
  5526. std::string post_compression_body;
  5527. svr_.set_pre_compression_logger(
  5528. [&](const Request & /*req*/, const Response &res) {
  5529. pre_compression_body = res.body;
  5530. });
  5531. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5532. post_compression_body = res.body;
  5533. });
  5534. Headers headers;
  5535. headers.emplace("Accept-Encoding", "br");
  5536. auto res = cli_.Get("/compress", headers);
  5537. ASSERT_TRUE(res);
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5540. // Verify pre-compression content is uncompressed
  5541. EXPECT_EQ(test_content, pre_compression_body);
  5542. // Verify post-compression content is compressed
  5543. EXPECT_NE(test_content, post_compression_body);
  5544. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5545. }
  5546. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5547. const std::string test_content =
  5548. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5549. "3456789012345678901234567890";
  5550. std::string pre_compression_body;
  5551. std::string post_compression_body;
  5552. svr_.set_pre_compression_logger(
  5553. [&](const Request & /*req*/, const Response &res) {
  5554. pre_compression_body = res.body;
  5555. });
  5556. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5557. post_compression_body = res.body;
  5558. });
  5559. // Request without compression (use /nocompress endpoint)
  5560. Headers headers;
  5561. auto res = cli_.Get("/nocompress", headers);
  5562. ASSERT_TRUE(res);
  5563. EXPECT_EQ(StatusCode::OK_200, res->status);
  5564. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5565. // Pre-compression logger should not be called when no compression is applied
  5566. EXPECT_TRUE(
  5567. pre_compression_body.empty()); // Pre-compression logger not called
  5568. EXPECT_EQ(
  5569. test_content,
  5570. post_compression_body); // Post-compression logger captures final content
  5571. }
  5572. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5573. const std::string test_content =
  5574. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5575. "3456789012345678901234567890";
  5576. std::string pre_compression_body;
  5577. bool pre_logger_called = false;
  5578. // Set only pre-compression logger
  5579. svr_.set_pre_compression_logger(
  5580. [&](const Request & /*req*/, const Response &res) {
  5581. pre_compression_body = res.body;
  5582. pre_logger_called = true;
  5583. });
  5584. Headers headers;
  5585. headers.emplace("Accept-Encoding", "gzip");
  5586. auto res = cli_.Get("/compress", headers);
  5587. ASSERT_TRUE(res);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5590. // Verify pre-compression logger was called
  5591. EXPECT_TRUE(pre_logger_called);
  5592. EXPECT_EQ(test_content, pre_compression_body);
  5593. }
  5594. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5595. {
  5596. // Test with Expect: 100-continue header - success case
  5597. // Server returns 100 Continue, client sends body, server returns 200 OK
  5598. Request req;
  5599. req.method = "POST";
  5600. req.path = "/post-large";
  5601. req.set_header("Expect", "100-continue");
  5602. req.body = LARGE_DATA;
  5603. Response res;
  5604. auto error = Error::Success;
  5605. cli_.set_keep_alive(true);
  5606. auto ret = cli_.send(req, res, error);
  5607. EXPECT_TRUE(ret);
  5608. EXPECT_EQ(StatusCode::OK_200, res.status);
  5609. EXPECT_EQ(LARGE_DATA, res.body);
  5610. }
  5611. {
  5612. // Test with Expect: 100-continue header - error case
  5613. // Client should not send the body when server returns an error
  5614. Request req;
  5615. req.method = "POST";
  5616. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5617. req.set_header("Expect", "100-continue");
  5618. req.body = LARGE_DATA;
  5619. Response res;
  5620. auto error = Error::Success;
  5621. auto start = std::chrono::high_resolution_clock::now();
  5622. cli_.set_keep_alive(true);
  5623. auto ret = cli_.send(req, res, error);
  5624. auto end = std::chrono::high_resolution_clock::now();
  5625. auto elapsed =
  5626. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5627. .count();
  5628. // With Expect: 100-continue, request completes successfully but with error
  5629. EXPECT_TRUE(ret);
  5630. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5631. EXPECT_EQ("close", res.get_header_value("Connection"));
  5632. EXPECT_FALSE(cli_.is_socket_open());
  5633. EXPECT_LE(elapsed, 200);
  5634. }
  5635. {
  5636. // Send an extra GET request to ensure error recovery without hanging
  5637. Request req;
  5638. req.method = "GET";
  5639. req.path = "/hi";
  5640. auto start = std::chrono::high_resolution_clock::now();
  5641. auto res = cli_.send(req);
  5642. auto end = std::chrono::high_resolution_clock::now();
  5643. auto elapsed =
  5644. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5645. .count();
  5646. ASSERT_TRUE(res);
  5647. EXPECT_EQ(StatusCode::OK_200, res->status);
  5648. EXPECT_EQ("Hello World!", res->body);
  5649. EXPECT_LE(elapsed, 500);
  5650. }
  5651. }
  5652. TEST(ZstdDecompressor, ChunkedDecompression) {
  5653. std::string data;
  5654. for (size_t i = 0; i < 32 * 1024; ++i) {
  5655. data.push_back(static_cast<char>('a' + i % 26));
  5656. }
  5657. std::string compressed_data;
  5658. {
  5659. httplib::detail::zstd_compressor compressor;
  5660. bool result = compressor.compress(
  5661. data.data(), data.size(),
  5662. /*last=*/true,
  5663. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5664. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5665. compressed_data_size);
  5666. return true;
  5667. });
  5668. ASSERT_TRUE(result);
  5669. }
  5670. std::string decompressed_data;
  5671. {
  5672. httplib::detail::zstd_decompressor decompressor;
  5673. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5674. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5675. size_t chunk_size = 130;
  5676. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5677. chunk_begin += chunk_size) {
  5678. size_t current_chunk_size =
  5679. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5680. bool result = decompressor.decompress(
  5681. compressed_data.data() + chunk_begin, current_chunk_size,
  5682. [&](const char *decompressed_data_chunk,
  5683. size_t decompressed_data_chunk_size) {
  5684. decompressed_data.insert(decompressed_data.size(),
  5685. decompressed_data_chunk,
  5686. decompressed_data_chunk_size);
  5687. return true;
  5688. });
  5689. ASSERT_TRUE(result);
  5690. }
  5691. }
  5692. ASSERT_EQ(data, decompressed_data);
  5693. }
  5694. TEST(ZstdDecompressor, Decompress) {
  5695. std::string original_text = "Compressed with ZSTD";
  5696. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5697. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5698. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5699. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5700. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5701. std::string decompressed_data;
  5702. {
  5703. httplib::detail::zstd_decompressor decompressor;
  5704. bool result = decompressor.decompress(
  5705. compressed_data.data(), compressed_data.size(),
  5706. [&](const char *decompressed_data_chunk,
  5707. size_t decompressed_data_chunk_size) {
  5708. decompressed_data.insert(decompressed_data.size(),
  5709. decompressed_data_chunk,
  5710. decompressed_data_chunk_size);
  5711. return true;
  5712. });
  5713. ASSERT_TRUE(result);
  5714. }
  5715. ASSERT_EQ(original_text, decompressed_data);
  5716. }
  5717. #endif
  5718. // Sends a raw request to a server listening at HOST:PORT.
  5719. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5720. std::string *resp = nullptr) {
  5721. auto error = Error::Success;
  5722. auto client_sock = detail::create_client_socket(
  5723. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5724. /*connection_timeout_sec=*/5, 0,
  5725. /*read_timeout_sec=*/5, 0,
  5726. /*write_timeout_sec=*/5, 0, std::string(), error);
  5727. if (client_sock == INVALID_SOCKET) { return false; }
  5728. auto ret = detail::process_client_socket(
  5729. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5730. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5731. if (req.size() !=
  5732. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5733. return false;
  5734. }
  5735. char buf[512];
  5736. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5737. while (line_reader.getline()) {
  5738. if (resp) { *resp += line_reader.ptr(); }
  5739. }
  5740. return true;
  5741. });
  5742. detail::close_socket(client_sock);
  5743. return ret;
  5744. }
  5745. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5746. Server svr;
  5747. std::string header_value;
  5748. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5749. header_value = req.get_header_value("foo");
  5750. res.set_content("ok", "text/plain");
  5751. });
  5752. thread t = thread([&] { svr.listen(HOST, PORT); });
  5753. auto se = detail::scope_exit([&] {
  5754. svr.stop();
  5755. t.join();
  5756. ASSERT_FALSE(svr.is_running());
  5757. });
  5758. svr.wait_until_ready();
  5759. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5760. // like characters are not treated the same - use vertical tab and escape.
  5761. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5762. "foo: \t \v bar \x1B\t \r\n"
  5763. "Connection: close\r\n"
  5764. "\r\n";
  5765. std::string res;
  5766. ASSERT_TRUE(send_request(5, req, &res));
  5767. EXPECT_EQ(header_value, "");
  5768. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5769. }
  5770. // Sends a raw request and verifies that there isn't a crash or exception.
  5771. static void test_raw_request(const std::string &req,
  5772. std::string *out = nullptr) {
  5773. Server svr;
  5774. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5775. res.set_content("ok", "text/plain");
  5776. });
  5777. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5778. res.set_content("ok", "text/plain");
  5779. });
  5780. svr.Get("/header_field_value_check",
  5781. [&](const Request & /*req*/, Response &res) {
  5782. res.set_content("ok", "text/plain");
  5783. });
  5784. // Server read timeout must be longer than the client read timeout for the
  5785. // bug to reproduce, probably to force the server to process a request
  5786. // without a trailing blank line.
  5787. const time_t client_read_timeout_sec = 1;
  5788. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5789. bool listen_thread_ok = false;
  5790. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5791. auto se = detail::scope_exit([&] {
  5792. svr.stop();
  5793. t.join();
  5794. ASSERT_FALSE(svr.is_running());
  5795. EXPECT_TRUE(listen_thread_ok);
  5796. });
  5797. svr.wait_until_ready();
  5798. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5799. }
  5800. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5801. // A certain header line causes an exception if the header property is parsed
  5802. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5803. test_raw_request(
  5804. "GET /hi HTTP/1.1\r\n"
  5805. " : "
  5806. " "
  5807. " ");
  5808. }
  5809. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5810. // A certain header line causes an exception if the header property *name* is
  5811. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5812. // greedy matcher and requires backtracking when there are a lot of ":"
  5813. // characters.
  5814. // This occurs with libc++ but not libstdc++.
  5815. test_raw_request(
  5816. "GET /hi HTTP/1.1\r\n"
  5817. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5818. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5819. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5820. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5821. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5822. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5823. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5824. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5825. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5826. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5827. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5828. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5829. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5830. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5831. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5832. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5833. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5834. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5835. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5836. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5837. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5838. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5839. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5840. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5841. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5842. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5843. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5844. "&&&%%%");
  5845. }
  5846. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5847. // Make sure this doesn't crash the server.
  5848. // In a previous version of the header line regex, the "\r" rendered the line
  5849. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5850. // a new position where the leading white space ended and the field value
  5851. // began.
  5852. // The crash occurs with libc++ but not libstdc++.
  5853. test_raw_request("GET /hi HTTP/1.1\r\n"
  5854. "a:" +
  5855. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5856. "\r\n"
  5857. "\r\n");
  5858. }
  5859. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5860. std::string out;
  5861. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5862. "Content-Type: text/plain\r\n"
  5863. "Transfer-Encoding: chunked\r\n"
  5864. "\r\n"
  5865. "nothex\r\n",
  5866. &out);
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5868. }
  5869. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  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. "3\r\n"
  5876. "xyz\r\n"
  5877. "NaN\r\n",
  5878. &out);
  5879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5880. }
  5881. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5882. std::string out;
  5883. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5884. "Content-Type: text/plain\r\n"
  5885. "Transfer-Encoding: chunked\r\n"
  5886. "\r\n"
  5887. // Length is too large for 64 bits.
  5888. "1ffffffffffffffff\r\n"
  5889. "xyz\r\n",
  5890. &out);
  5891. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5892. }
  5893. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5894. test_raw_request("GET /hi HTTP/1.1\r\n"
  5895. "Content-Type: text/plain\r\n\r");
  5896. }
  5897. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5898. std::string out;
  5899. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5900. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5901. }
  5902. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5903. Server svr;
  5904. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5905. EXPECT_TRUE(!req.remote_addr.empty());
  5906. });
  5907. thread t = thread([&] { svr.listen(HOST, PORT); });
  5908. auto se = detail::scope_exit([&] {
  5909. svr.stop();
  5910. t.join();
  5911. ASSERT_FALSE(svr.is_running());
  5912. });
  5913. svr.wait_until_ready();
  5914. // Send an invalid request line to trigger Bad Request
  5915. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5916. std::string out;
  5917. ASSERT_TRUE(send_request(5, bad_req, &out));
  5918. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5919. }
  5920. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5921. std::string out;
  5922. std::string request(
  5923. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5924. test_raw_request(request, &out);
  5925. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5926. }
  5927. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5928. std::string out;
  5929. std::string request(
  5930. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5931. test_raw_request(request, &out);
  5932. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5933. }
  5934. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5935. std::string out;
  5936. std::string request(
  5937. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5938. test_raw_request(request, &out);
  5939. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5940. }
  5941. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5942. std::string out;
  5943. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5944. "Test: \r\n\r\n",
  5945. &out);
  5946. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5947. }
  5948. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5949. Server svr;
  5950. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5951. res.set_header("Cache-Control", "no-cache");
  5952. res.set_chunked_content_provider(
  5953. "text/event-stream", [](size_t offset, DataSink &sink) {
  5954. std::string s = "data:";
  5955. s += std::to_string(offset);
  5956. s += "\n\n";
  5957. auto ret = sink.write(s.data(), s.size());
  5958. EXPECT_TRUE(ret);
  5959. std::this_thread::sleep_for(std::chrono::seconds(1));
  5960. return true;
  5961. });
  5962. });
  5963. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5964. svr.wait_until_ready();
  5965. Client client(HOST, PORT);
  5966. const Headers headers = {{"Accept", "text/event-stream"}};
  5967. auto get_thread = std::thread([&client, &headers]() {
  5968. auto res = client.Get(
  5969. "/events", headers,
  5970. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5971. });
  5972. auto se = detail::scope_exit([&] {
  5973. svr.stop();
  5974. get_thread.join();
  5975. listen_thread.join();
  5976. ASSERT_FALSE(svr.is_running());
  5977. });
  5978. // Give GET time to get a few messages.
  5979. std::this_thread::sleep_for(std::chrono::seconds(2));
  5980. }
  5981. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5982. httplib::Server svr;
  5983. svr.Post("/hi",
  5984. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5985. res.status = StatusCode::OK_200;
  5986. });
  5987. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5988. svr.wait_until_ready();
  5989. Client cli(HOST, PORT);
  5990. auto res = cli.Post("/hi", "data", "text/plain");
  5991. ASSERT_TRUE(res);
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. svr.stop();
  5994. thread.join();
  5995. ASSERT_FALSE(svr.is_running());
  5996. res = cli.Post("/hi", "data", "text/plain");
  5997. ASSERT_FALSE(res);
  5998. }
  5999. TEST(ServerStopTest, ListenFailure) {
  6000. Server svr;
  6001. auto t = thread([&]() {
  6002. auto ret = svr.listen("????", PORT);
  6003. EXPECT_FALSE(ret);
  6004. });
  6005. svr.wait_until_ready();
  6006. svr.stop();
  6007. t.join();
  6008. }
  6009. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6010. TEST(ServerStopTest, Decommision) {
  6011. Server svr;
  6012. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6013. for (int i = 0; i < 4; i++) {
  6014. auto is_even = !(i % 2);
  6015. std::thread t{[&] {
  6016. try {
  6017. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6018. if (is_even) {
  6019. throw std::runtime_error("Some thing that happens to go wrong.");
  6020. }
  6021. svr.listen(HOST, PORT);
  6022. } catch (...) { svr.decommission(); }
  6023. }};
  6024. svr.wait_until_ready();
  6025. // Server is up
  6026. {
  6027. Client cli(HOST, PORT);
  6028. auto res = cli.Get("/hi");
  6029. if (is_even) {
  6030. EXPECT_FALSE(res);
  6031. } else {
  6032. EXPECT_TRUE(res);
  6033. EXPECT_EQ("hi...", res->body);
  6034. }
  6035. }
  6036. svr.stop();
  6037. t.join();
  6038. // Server is down...
  6039. {
  6040. Client cli(HOST, PORT);
  6041. auto res = cli.Get("/hi");
  6042. EXPECT_FALSE(res);
  6043. }
  6044. }
  6045. }
  6046. #endif
  6047. // Helper function for string body upload progress tests
  6048. template <typename SetupHandler, typename ClientCall>
  6049. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6050. ClientCall &&client_call,
  6051. const string &body) {
  6052. Server svr;
  6053. setup_handler(svr);
  6054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6055. auto se = detail::scope_exit([&] {
  6056. svr.stop();
  6057. t.join();
  6058. });
  6059. svr.wait_until_ready();
  6060. Client cli(HOST, PORT);
  6061. vector<uint64_t> progress_values;
  6062. bool progress_called = false;
  6063. auto res =
  6064. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6065. progress_values.push_back(current);
  6066. progress_called = true;
  6067. return true;
  6068. });
  6069. ASSERT_TRUE(res);
  6070. EXPECT_EQ(200, res->status);
  6071. EXPECT_TRUE(progress_called);
  6072. }
  6073. TEST(UploadProgressTest, PostStringBodyBasic) {
  6074. TestStringBodyUploadProgress(
  6075. [](Server &svr) {
  6076. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6077. res.set_content("received", "text/plain");
  6078. });
  6079. },
  6080. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6081. return cli.Post("/test", body, "text/plain", progress_callback);
  6082. },
  6083. "test data for upload progress");
  6084. }
  6085. TEST(UploadProgressTest, PutStringBodyBasic) {
  6086. TestStringBodyUploadProgress(
  6087. [](Server &svr) {
  6088. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6089. res.set_content("put received", "text/plain");
  6090. });
  6091. },
  6092. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6093. return cli.Put("/test", body, "text/plain", progress_callback);
  6094. },
  6095. "put test data for upload progress");
  6096. }
  6097. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6098. TestStringBodyUploadProgress(
  6099. [](Server &svr) {
  6100. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6101. res.set_content("patch received", "text/plain");
  6102. });
  6103. },
  6104. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6105. return cli.Patch("/test", body, "text/plain", progress_callback);
  6106. },
  6107. "patch test data for upload progress");
  6108. }
  6109. // Helper function for content provider upload progress tests
  6110. template <typename SetupHandler, typename ClientCall>
  6111. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6112. ClientCall &&client_call) {
  6113. Server svr;
  6114. setup_handler(svr);
  6115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6116. auto se = detail::scope_exit([&] {
  6117. svr.stop();
  6118. t.join();
  6119. });
  6120. svr.wait_until_ready();
  6121. Client cli(HOST, PORT);
  6122. vector<uint64_t> progress_values;
  6123. auto res =
  6124. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6125. progress_values.push_back(current);
  6126. return true;
  6127. });
  6128. ASSERT_TRUE(res);
  6129. EXPECT_EQ(200, res->status);
  6130. EXPECT_FALSE(progress_values.empty());
  6131. }
  6132. TEST(UploadProgressTest, PostContentProviderProgress) {
  6133. TestContentProviderUploadProgress(
  6134. [](Server &svr) {
  6135. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6136. res.set_content("provider received", "text/plain");
  6137. });
  6138. },
  6139. [](Client &cli, UploadProgress progress_callback) {
  6140. return cli.Post(
  6141. "/test", 10,
  6142. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6143. sink.os << "test data";
  6144. return true;
  6145. },
  6146. "text/plain", progress_callback);
  6147. });
  6148. }
  6149. // Helper function for multipart upload progress tests
  6150. template <typename SetupHandler, typename ClientCall>
  6151. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6152. ClientCall &&client_call,
  6153. const string &endpoint) {
  6154. Server svr;
  6155. setup_handler(svr);
  6156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6157. auto se = detail::scope_exit([&] {
  6158. svr.stop();
  6159. t.join();
  6160. });
  6161. svr.wait_until_ready();
  6162. Client cli(HOST, PORT);
  6163. vector<uint64_t> progress_values;
  6164. UploadFormDataItems items = {
  6165. {"field1", "value1", "", ""},
  6166. {"field2", "longer value for progress tracking test", "", ""},
  6167. {"file1", "file content data for upload progress", "test.txt",
  6168. "text/plain"}};
  6169. auto res = client_call(cli, endpoint, items,
  6170. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6171. progress_values.push_back(current);
  6172. return true;
  6173. });
  6174. ASSERT_TRUE(res);
  6175. EXPECT_EQ(200, res->status);
  6176. EXPECT_FALSE(progress_values.empty());
  6177. }
  6178. TEST(UploadProgressTest, PostMultipartProgress) {
  6179. TestMultipartUploadProgress(
  6180. [](Server &svr) {
  6181. svr.Post("/multipart", [](const Request &req, Response &res) {
  6182. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6183. res.set_content("multipart received", "text/plain");
  6184. });
  6185. },
  6186. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6187. UploadProgress progress_callback) {
  6188. return cli.Post(endpoint, items, progress_callback);
  6189. },
  6190. "/multipart");
  6191. }
  6192. // Helper function for basic download progress tests
  6193. template <typename SetupHandler, typename ClientCall>
  6194. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6195. ClientCall &&client_call, const string &endpoint,
  6196. size_t expected_content_size) {
  6197. Server svr;
  6198. setup_handler(svr);
  6199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6200. auto se = detail::scope_exit([&] {
  6201. svr.stop();
  6202. t.join();
  6203. });
  6204. svr.wait_until_ready();
  6205. Client cli(HOST, PORT);
  6206. vector<uint64_t> progress_values;
  6207. auto res = client_call(cli, endpoint,
  6208. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6209. progress_values.push_back(current);
  6210. return true;
  6211. });
  6212. ASSERT_TRUE(res);
  6213. EXPECT_EQ(200, res->status);
  6214. EXPECT_FALSE(progress_values.empty());
  6215. EXPECT_EQ(expected_content_size, res->body.size());
  6216. }
  6217. TEST(DownloadProgressTest, GetBasic) {
  6218. TestBasicDownloadProgress(
  6219. [](Server &svr) {
  6220. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6221. string content(1000, 'D');
  6222. res.set_content(content, "text/plain");
  6223. });
  6224. },
  6225. [](Client &cli, const string &endpoint,
  6226. DownloadProgress progress_callback) {
  6227. return cli.Get(endpoint, progress_callback);
  6228. },
  6229. "/download", 1000u);
  6230. }
  6231. // Helper function for content receiver download progress tests
  6232. template <typename SetupHandler, typename ClientCall>
  6233. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6234. ClientCall &&client_call,
  6235. const string &endpoint,
  6236. size_t expected_content_size) {
  6237. Server svr;
  6238. setup_handler(svr);
  6239. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6240. auto se = detail::scope_exit([&] {
  6241. svr.stop();
  6242. t.join();
  6243. });
  6244. svr.wait_until_ready();
  6245. Client cli(HOST, PORT);
  6246. vector<uint64_t> progress_values;
  6247. string received_body;
  6248. auto res = client_call(
  6249. cli, endpoint,
  6250. [&](const char *data, size_t data_length) -> bool {
  6251. received_body.append(data, data_length);
  6252. return true;
  6253. },
  6254. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6255. progress_values.push_back(current);
  6256. return true;
  6257. });
  6258. ASSERT_TRUE(res);
  6259. EXPECT_EQ(200, res->status);
  6260. EXPECT_FALSE(progress_values.empty());
  6261. EXPECT_EQ(expected_content_size, received_body.size());
  6262. EXPECT_TRUE(res->body.empty());
  6263. }
  6264. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6265. TestContentReceiverDownloadProgress(
  6266. [](Server &svr) {
  6267. svr.Get("/download-receiver",
  6268. [](const Request & /*req*/, Response &res) {
  6269. string content(2000, 'R');
  6270. res.set_content(content, "text/plain");
  6271. });
  6272. },
  6273. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6274. DownloadProgress progress_callback) {
  6275. return cli.Get(endpoint, content_receiver, progress_callback);
  6276. },
  6277. "/download-receiver", 2000u);
  6278. }
  6279. TEST(StreamingTest, NoContentLengthStreaming) {
  6280. Server svr;
  6281. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6282. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6283. if (offset < 6) {
  6284. sink.os << (offset < 3 ? "a" : "b");
  6285. } else {
  6286. sink.done();
  6287. }
  6288. return true;
  6289. });
  6290. });
  6291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6292. auto listen_se = detail::scope_exit([&] {
  6293. svr.stop();
  6294. listen_thread.join();
  6295. ASSERT_FALSE(svr.is_running());
  6296. });
  6297. svr.wait_until_ready();
  6298. Client client(HOST, PORT);
  6299. auto get_thread = std::thread([&client]() {
  6300. std::string s;
  6301. auto res =
  6302. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6303. s += std::string(data, len);
  6304. return true;
  6305. });
  6306. ASSERT_TRUE(res);
  6307. EXPECT_EQ(StatusCode::OK_200, res->status);
  6308. EXPECT_EQ("aaabbb", s);
  6309. });
  6310. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6311. // Give GET time to get a few messages.
  6312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6313. }
  6314. TEST(MountTest, Unmount) {
  6315. Server svr;
  6316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. listen_thread.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. Client cli("localhost", PORT);
  6324. svr.set_mount_point("/mount2", "./www2");
  6325. auto res = cli.Get("/");
  6326. ASSERT_TRUE(res);
  6327. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6328. res = cli.Get("/mount2/dir/test.html");
  6329. ASSERT_TRUE(res);
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. svr.set_mount_point("/", "./www");
  6332. res = cli.Get("/dir/");
  6333. ASSERT_TRUE(res);
  6334. EXPECT_EQ(StatusCode::OK_200, res->status);
  6335. svr.remove_mount_point("/");
  6336. res = cli.Get("/dir/");
  6337. ASSERT_TRUE(res);
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. svr.remove_mount_point("/mount2");
  6340. res = cli.Get("/mount2/dir/test.html");
  6341. ASSERT_TRUE(res);
  6342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6343. }
  6344. TEST(MountTest, Redicect) {
  6345. Server svr;
  6346. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6347. auto se = detail::scope_exit([&] {
  6348. svr.stop();
  6349. listen_thread.join();
  6350. ASSERT_FALSE(svr.is_running());
  6351. });
  6352. svr.set_mount_point("/", "./www");
  6353. svr.wait_until_ready();
  6354. Client cli("localhost", PORT);
  6355. auto res = cli.Get("/dir/");
  6356. ASSERT_TRUE(res);
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. res = cli.Get("/dir");
  6359. ASSERT_TRUE(res);
  6360. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6361. res = cli.Get("/file");
  6362. ASSERT_TRUE(res);
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. res = cli.Get("/file/");
  6365. ASSERT_TRUE(res);
  6366. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6367. cli.set_follow_location(true);
  6368. res = cli.Get("/dir");
  6369. ASSERT_TRUE(res);
  6370. EXPECT_EQ(StatusCode::OK_200, res->status);
  6371. }
  6372. TEST(MountTest, MultibytesPathName) {
  6373. Server svr;
  6374. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6375. auto se = detail::scope_exit([&] {
  6376. svr.stop();
  6377. listen_thread.join();
  6378. ASSERT_FALSE(svr.is_running());
  6379. });
  6380. svr.set_mount_point("/", "./www");
  6381. svr.wait_until_ready();
  6382. Client cli("localhost", PORT);
  6383. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6384. ASSERT_TRUE(res);
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6387. }
  6388. TEST(KeepAliveTest, ReadTimeout) {
  6389. Server svr;
  6390. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6391. std::this_thread::sleep_for(std::chrono::seconds(2));
  6392. res.set_content("a", "text/plain");
  6393. });
  6394. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6395. res.set_content("b", "text/plain");
  6396. });
  6397. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6398. auto se = detail::scope_exit([&] {
  6399. svr.stop();
  6400. listen_thread.join();
  6401. ASSERT_FALSE(svr.is_running());
  6402. });
  6403. svr.wait_until_ready();
  6404. Client cli("localhost", PORT);
  6405. cli.set_keep_alive(true);
  6406. cli.set_read_timeout(std::chrono::seconds(1));
  6407. auto resa = cli.Get("/a");
  6408. ASSERT_FALSE(resa);
  6409. EXPECT_EQ(Error::Read, resa.error());
  6410. auto resb = cli.Get("/b");
  6411. ASSERT_TRUE(resb);
  6412. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6413. EXPECT_EQ("b", resb->body);
  6414. }
  6415. TEST(KeepAliveTest, MaxCount) {
  6416. size_t keep_alive_max_count = 3;
  6417. Server svr;
  6418. svr.set_keep_alive_max_count(keep_alive_max_count);
  6419. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6420. res.set_content("Hello World!", "text/plain");
  6421. });
  6422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6423. auto se = detail::scope_exit([&] {
  6424. svr.stop();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. svr.wait_until_ready();
  6429. Client cli(HOST, PORT);
  6430. cli.set_keep_alive(true);
  6431. for (size_t i = 0; i < 5; i++) {
  6432. auto result = cli.Get("/hi");
  6433. ASSERT_TRUE(result);
  6434. EXPECT_EQ(StatusCode::OK_200, result->status);
  6435. if (i == keep_alive_max_count - 1) {
  6436. EXPECT_EQ("close", result->get_header_value("Connection"));
  6437. } else {
  6438. EXPECT_FALSE(result->has_header("Connection"));
  6439. }
  6440. }
  6441. }
  6442. TEST(KeepAliveTest, Issue1041) {
  6443. Server svr;
  6444. svr.set_keep_alive_timeout(3);
  6445. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6446. res.set_content("Hello World!", "text/plain");
  6447. });
  6448. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6449. auto se = detail::scope_exit([&] {
  6450. svr.stop();
  6451. listen_thread.join();
  6452. ASSERT_FALSE(svr.is_running());
  6453. });
  6454. svr.wait_until_ready();
  6455. Client cli(HOST, PORT);
  6456. cli.set_keep_alive(true);
  6457. auto result = cli.Get("/hi");
  6458. ASSERT_TRUE(result);
  6459. EXPECT_EQ(StatusCode::OK_200, result->status);
  6460. std::this_thread::sleep_for(std::chrono::seconds(5));
  6461. result = cli.Get("/hi");
  6462. ASSERT_TRUE(result);
  6463. EXPECT_EQ(StatusCode::OK_200, result->status);
  6464. }
  6465. TEST(KeepAliveTest, Issue1959) {
  6466. Server svr;
  6467. svr.set_keep_alive_timeout(5);
  6468. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6469. res.set_content("a", "text/plain");
  6470. });
  6471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6472. auto se = detail::scope_exit([&] {
  6473. if (!svr.is_running()) return;
  6474. svr.stop();
  6475. listen_thread.join();
  6476. ASSERT_FALSE(svr.is_running());
  6477. });
  6478. svr.wait_until_ready();
  6479. Client cli("localhost", PORT);
  6480. cli.set_keep_alive(true);
  6481. using namespace std::chrono;
  6482. auto start = steady_clock::now();
  6483. cli.Get("/a");
  6484. svr.stop();
  6485. listen_thread.join();
  6486. auto end = steady_clock::now();
  6487. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6488. EXPECT_LT(elapsed, 5000);
  6489. }
  6490. #ifdef CPPHTTPLIB_SSL_ENABLED
  6491. TEST(KeepAliveTest, SSLClientReconnection) {
  6492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6493. ASSERT_TRUE(svr.is_valid());
  6494. svr.set_keep_alive_timeout(1);
  6495. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6496. res.set_content("Hello World!", "text/plain");
  6497. });
  6498. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6499. auto se = detail::scope_exit([&] {
  6500. svr.stop();
  6501. listen_thread.join();
  6502. ASSERT_FALSE(svr.is_running());
  6503. });
  6504. svr.wait_until_ready();
  6505. SSLClient cli(HOST, PORT);
  6506. cli.enable_server_certificate_verification(false);
  6507. cli.set_keep_alive(true);
  6508. auto result = cli.Get("/hi");
  6509. ASSERT_TRUE(result);
  6510. EXPECT_EQ(StatusCode::OK_200, result->status);
  6511. result = cli.Get("/hi");
  6512. ASSERT_TRUE(result);
  6513. EXPECT_EQ(StatusCode::OK_200, result->status);
  6514. std::this_thread::sleep_for(std::chrono::seconds(2));
  6515. // Recoonect
  6516. result = cli.Get("/hi");
  6517. ASSERT_TRUE(result);
  6518. EXPECT_EQ(StatusCode::OK_200, result->status);
  6519. result = cli.Get("/hi");
  6520. ASSERT_TRUE(result);
  6521. EXPECT_EQ(StatusCode::OK_200, result->status);
  6522. }
  6523. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6525. ASSERT_TRUE(svr.is_valid());
  6526. svr.set_keep_alive_timeout(1);
  6527. std::string content = "reconnect";
  6528. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6529. res.set_content("Hello World!", "text/plain");
  6530. });
  6531. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6532. auto se = detail::scope_exit([&] {
  6533. svr.stop();
  6534. listen_thread.join();
  6535. ASSERT_FALSE(svr.is_running());
  6536. });
  6537. svr.wait_until_ready();
  6538. SSLClient cli(HOST, PORT);
  6539. cli.enable_server_certificate_verification(false);
  6540. cli.set_keep_alive(true);
  6541. auto result = cli.Post(
  6542. "/hi", content.size(),
  6543. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6544. sink.write(content.c_str(), content.size());
  6545. return true;
  6546. },
  6547. "text/plain");
  6548. ASSERT_TRUE(result);
  6549. EXPECT_EQ(200, result->status);
  6550. std::this_thread::sleep_for(std::chrono::seconds(2));
  6551. // Recoonect
  6552. result = cli.Post(
  6553. "/hi", content.size(),
  6554. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6555. sink.write(content.c_str(), content.size());
  6556. return true;
  6557. },
  6558. "text/plain");
  6559. ASSERT_TRUE(result);
  6560. EXPECT_EQ(200, result->status);
  6561. result = cli.Post(
  6562. "/hi", content.size(),
  6563. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6564. sink.write(content.c_str(), content.size());
  6565. return true;
  6566. },
  6567. "text/plain");
  6568. ASSERT_TRUE(result);
  6569. EXPECT_EQ(200, result->status);
  6570. }
  6571. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6572. using namespace httplib::tls;
  6573. {
  6574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6575. ASSERT_TRUE(svr.is_valid());
  6576. svr.Get("/sni", [&](const Request &req, Response &res) {
  6577. std::string expected = req.sni();
  6578. EXPECT_EQ(expected, req.get_param_value("expected"));
  6579. res.set_content("ok", "text/plain");
  6580. });
  6581. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6582. auto se = detail::scope_exit([&] {
  6583. svr.stop();
  6584. listen_thread.join();
  6585. ASSERT_FALSE(svr.is_running());
  6586. });
  6587. svr.wait_until_ready();
  6588. {
  6589. SSLClient cli("localhost", PORT);
  6590. cli.enable_server_certificate_verification(false);
  6591. auto res = cli.Get("/sni?expected=localhost");
  6592. ASSERT_TRUE(res);
  6593. }
  6594. {
  6595. SSLClient cli("::1", PORT);
  6596. cli.enable_server_certificate_verification(false);
  6597. auto res = cli.Get("/sni?expected=");
  6598. // NOTE: This may fail if the server is listening on IPv4 only
  6599. // (e.g., when localhost resolves to 127.0.0.1 only)
  6600. if (res) {
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. } else {
  6603. EXPECT_EQ(Error::Connection, res.error());
  6604. }
  6605. }
  6606. }
  6607. }
  6608. #endif
  6609. TEST(ClientProblemDetectionTest, ContentProvider) {
  6610. Server svr;
  6611. size_t content_length = 1024 * 1024;
  6612. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6613. res.set_content_provider(
  6614. content_length, "text/plain",
  6615. [&](size_t offset, size_t length, DataSink &sink) {
  6616. auto out_len = std::min(length, static_cast<size_t>(1024));
  6617. std::string out(out_len, '@');
  6618. sink.write(out.data(), out_len);
  6619. return offset < 4096;
  6620. },
  6621. [](bool success) { ASSERT_FALSE(success); });
  6622. });
  6623. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6624. res.set_content_provider(
  6625. 0, "text/plain",
  6626. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6627. EXPECT_TRUE(false);
  6628. return true;
  6629. },
  6630. [](bool success) { ASSERT_FALSE(success); });
  6631. });
  6632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6633. auto se = detail::scope_exit([&] {
  6634. svr.stop();
  6635. listen_thread.join();
  6636. ASSERT_FALSE(svr.is_running());
  6637. });
  6638. svr.wait_until_ready();
  6639. Client cli("localhost", PORT);
  6640. {
  6641. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6642. size_t /*data_length*/) { return false; });
  6643. ASSERT_FALSE(res);
  6644. }
  6645. {
  6646. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6647. size_t /*data_length*/) { return false; });
  6648. ASSERT_TRUE(res);
  6649. }
  6650. }
  6651. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6652. Server svr;
  6653. svr.set_error_handler([](Request const &, Response &res) -> void {
  6654. res.set_chunked_content_provider(
  6655. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6656. sink.os << "hello";
  6657. sink.os << "world";
  6658. sink.done();
  6659. return true;
  6660. });
  6661. });
  6662. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. Client cli("localhost", PORT);
  6670. auto res = cli.Get("/");
  6671. ASSERT_TRUE(res);
  6672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6673. EXPECT_EQ("helloworld", res->body);
  6674. }
  6675. TEST(LongPollingTest, ClientCloseDetection) {
  6676. Server svr;
  6677. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6678. res.set_chunked_content_provider(
  6679. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6680. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6681. sink.os << "hello";
  6682. auto count = 10;
  6683. while (count > 0 && sink.is_writable()) {
  6684. this_thread::sleep_for(chrono::milliseconds(10));
  6685. count--;
  6686. }
  6687. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6688. return true;
  6689. });
  6690. });
  6691. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6692. auto se = detail::scope_exit([&] {
  6693. svr.stop();
  6694. listen_thread.join();
  6695. ASSERT_FALSE(svr.is_running());
  6696. });
  6697. svr.wait_until_ready();
  6698. Client cli("localhost", PORT);
  6699. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6700. EXPECT_EQ("hello", string(data, data_length));
  6701. return false; // close the socket immediately.
  6702. });
  6703. ASSERT_FALSE(res);
  6704. }
  6705. TEST(GetWithParametersTest, GetWithParameters) {
  6706. Server svr;
  6707. svr.Get("/", [&](const Request &req, Response &) {
  6708. EXPECT_EQ("world", req.get_param_value("hello"));
  6709. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6710. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6711. });
  6712. svr.Get("/params", [&](const Request &req, Response &) {
  6713. EXPECT_EQ("world", req.get_param_value("hello"));
  6714. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6715. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6716. });
  6717. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6718. EXPECT_EQ("resource-id", req.matches[1]);
  6719. EXPECT_EQ("foo", req.get_param_value("param1"));
  6720. EXPECT_EQ("bar", req.get_param_value("param2"));
  6721. });
  6722. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6723. EXPECT_EQ("user-id", req.path_params.at("id"));
  6724. EXPECT_EQ("foo", req.get_param_value("param1"));
  6725. EXPECT_EQ("bar", req.get_param_value("param2"));
  6726. });
  6727. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6728. auto se = detail::scope_exit([&] {
  6729. svr.stop();
  6730. listen_thread.join();
  6731. ASSERT_FALSE(svr.is_running());
  6732. });
  6733. svr.wait_until_ready();
  6734. {
  6735. Client cli(HOST, PORT);
  6736. Params params;
  6737. params.emplace("hello", "world");
  6738. params.emplace("hello2", "world2");
  6739. params.emplace("hello3", "world3");
  6740. auto res = cli.Get("/", params, Headers{});
  6741. ASSERT_TRUE(res);
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. }
  6744. {
  6745. Client cli(HOST, PORT);
  6746. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6747. ASSERT_TRUE(res);
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. {
  6751. Client cli(HOST, PORT);
  6752. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6753. ASSERT_TRUE(res);
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. }
  6756. {
  6757. Client cli(HOST, PORT);
  6758. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6759. ASSERT_TRUE(res);
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. }
  6762. }
  6763. TEST(GetWithParametersTest, GetWithParameters2) {
  6764. Server svr;
  6765. svr.Get("/", [&](const Request &req, Response &res) {
  6766. auto text = req.get_param_value("hello");
  6767. res.set_content(text, "text/plain");
  6768. });
  6769. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6770. auto se = detail::scope_exit([&] {
  6771. svr.stop();
  6772. listen_thread.join();
  6773. ASSERT_FALSE(svr.is_running());
  6774. });
  6775. svr.wait_until_ready();
  6776. Client cli("localhost", PORT);
  6777. Params params;
  6778. params.emplace("hello", "world");
  6779. std::string body;
  6780. auto res = cli.Get("/", params, Headers{},
  6781. [&](const char *data, size_t data_length) {
  6782. body.append(data, data_length);
  6783. return true;
  6784. });
  6785. ASSERT_TRUE(res);
  6786. EXPECT_EQ(StatusCode::OK_200, res->status);
  6787. EXPECT_EQ("world", body);
  6788. }
  6789. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6790. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6791. auto host = "httpcan.org";
  6792. auto path = std::string{"/range/32"};
  6793. #else
  6794. auto host = "nghttp2.org";
  6795. auto path = std::string{"/httpbin/range/32"};
  6796. #endif
  6797. #ifdef CPPHTTPLIB_SSL_ENABLED
  6798. SSLClient cli(host);
  6799. #else
  6800. Client cli(host);
  6801. #endif
  6802. cli.set_default_headers({make_range_header({{1, 10}})});
  6803. cli.set_connection_timeout(5);
  6804. {
  6805. auto res = cli.Get(path);
  6806. ASSERT_TRUE(res);
  6807. EXPECT_EQ("bcdefghijk", res->body);
  6808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6809. }
  6810. {
  6811. auto res = cli.Get(path);
  6812. ASSERT_TRUE(res);
  6813. EXPECT_EQ("bcdefghijk", res->body);
  6814. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6815. }
  6816. }
  6817. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6818. Server svr;
  6819. svr.set_default_headers({{"Hello", "World"}});
  6820. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6821. res.set_content("ok", "text/plain");
  6822. });
  6823. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6824. auto se = detail::scope_exit([&] {
  6825. svr.stop();
  6826. listen_thread.join();
  6827. ASSERT_FALSE(svr.is_running());
  6828. });
  6829. svr.wait_until_ready();
  6830. Client cli("localhost", PORT);
  6831. auto res = cli.Get("/");
  6832. ASSERT_TRUE(res);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("ok", res->body);
  6835. EXPECT_EQ("World", res->get_header_value("Hello"));
  6836. }
  6837. #ifdef CPPHTTPLIB_SSL_ENABLED
  6838. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6840. ASSERT_TRUE(svr.is_valid());
  6841. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6842. std::this_thread::sleep_for(std::chrono::seconds(2));
  6843. res.set_content("a", "text/plain");
  6844. });
  6845. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6846. res.set_content("b", "text/plain");
  6847. });
  6848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6849. auto se = detail::scope_exit([&] {
  6850. svr.stop();
  6851. listen_thread.join();
  6852. ASSERT_FALSE(svr.is_running());
  6853. });
  6854. svr.wait_until_ready();
  6855. SSLClient cli("localhost", PORT);
  6856. cli.enable_server_certificate_verification(false);
  6857. cli.set_keep_alive(true);
  6858. cli.set_read_timeout(std::chrono::seconds(1));
  6859. auto resa = cli.Get("/a");
  6860. ASSERT_TRUE(!resa);
  6861. EXPECT_EQ(Error::Read, resa.error());
  6862. auto resb = cli.Get("/b");
  6863. ASSERT_TRUE(resb);
  6864. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6865. EXPECT_EQ("b", resb->body);
  6866. }
  6867. #endif
  6868. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6869. protected:
  6870. ServerTestWithAI_PASSIVE()
  6871. : cli_(HOST, PORT)
  6872. #ifdef CPPHTTPLIB_SSL_ENABLED
  6873. ,
  6874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6875. #endif
  6876. {
  6877. #ifdef CPPHTTPLIB_SSL_ENABLED
  6878. cli_.enable_server_certificate_verification(false);
  6879. #endif
  6880. }
  6881. virtual void SetUp() {
  6882. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6883. res.set_content("Hello World!", "text/plain");
  6884. });
  6885. t_ = thread(
  6886. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6887. svr_.wait_until_ready();
  6888. }
  6889. virtual void TearDown() {
  6890. svr_.stop();
  6891. t_.join();
  6892. }
  6893. #ifdef CPPHTTPLIB_SSL_ENABLED
  6894. SSLClient cli_;
  6895. SSLServer svr_;
  6896. #else
  6897. Client cli_;
  6898. Server svr_;
  6899. #endif
  6900. thread t_;
  6901. };
  6902. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6903. auto res = cli_.Get("/hi");
  6904. ASSERT_TRUE(res);
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6907. EXPECT_EQ("Hello World!", res->body);
  6908. }
  6909. class ServerUpDownTest : public ::testing::Test {
  6910. protected:
  6911. ServerUpDownTest() : cli_(HOST, PORT) {}
  6912. virtual void SetUp() {
  6913. t_ = thread([&]() {
  6914. svr_.bind_to_any_port(HOST);
  6915. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6916. ASSERT_TRUE(svr_.listen_after_bind());
  6917. });
  6918. svr_.wait_until_ready();
  6919. }
  6920. virtual void TearDown() {
  6921. svr_.stop();
  6922. t_.join();
  6923. }
  6924. Client cli_;
  6925. Server svr_;
  6926. thread t_;
  6927. };
  6928. TEST_F(ServerUpDownTest, QuickStartStop) {
  6929. // Should not crash, especially when run with
  6930. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6931. }
  6932. class PayloadMaxLengthTest : public ::testing::Test {
  6933. protected:
  6934. PayloadMaxLengthTest()
  6935. : cli_(HOST, PORT)
  6936. #ifdef CPPHTTPLIB_SSL_ENABLED
  6937. ,
  6938. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6939. #endif
  6940. {
  6941. #ifdef CPPHTTPLIB_SSL_ENABLED
  6942. cli_.enable_server_certificate_verification(false);
  6943. #endif
  6944. }
  6945. virtual void SetUp() {
  6946. svr_.set_payload_max_length(8);
  6947. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6948. res.set_content("test", "text/plain");
  6949. });
  6950. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6951. svr_.wait_until_ready();
  6952. }
  6953. virtual void TearDown() {
  6954. svr_.stop();
  6955. t_.join();
  6956. }
  6957. #ifdef CPPHTTPLIB_SSL_ENABLED
  6958. SSLClient cli_;
  6959. SSLServer svr_;
  6960. #else
  6961. Client cli_;
  6962. Server svr_;
  6963. #endif
  6964. thread t_;
  6965. };
  6966. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6967. auto res = cli_.Post("/test", "123456789", "text/plain");
  6968. ASSERT_TRUE(res);
  6969. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6970. res = cli_.Post("/test", "12345678", "text/plain");
  6971. ASSERT_TRUE(res);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6975. // Test chunked encoding with payload exceeding the 8-byte limit
  6976. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6977. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6978. ASSERT_TRUE(res);
  6979. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6980. }
  6981. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6982. // Test chunked encoding with payload within the 8-byte limit
  6983. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6984. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6985. ASSERT_TRUE(res);
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. }
  6988. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6989. // Test using send_request to send chunked data exceeding payload limit
  6990. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6991. "Host: " +
  6992. std::string(HOST) + ":" + std::to_string(PORT) +
  6993. "\r\n"
  6994. "Transfer-Encoding: chunked\r\n"
  6995. "Connection: close\r\n"
  6996. "\r\n"
  6997. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6998. "0123456789\r\n"
  6999. "0\r\n" // End chunk
  7000. "\r\n";
  7001. std::string response;
  7002. bool result = send_request(1, chunked_request, &response);
  7003. if (!result) {
  7004. // If send_request fails, it might be because the server closed the
  7005. // connection due to payload limit enforcement, which is acceptable
  7006. SUCCEED()
  7007. << "Server rejected oversized chunked request (connection closed)";
  7008. } else {
  7009. // If we got a response, check if it's an error response or connection was
  7010. // closed early Short response length indicates connection was closed due to
  7011. // payload limit
  7012. if (response.length() <= 10) {
  7013. SUCCEED() << "Server closed connection for oversized chunked request";
  7014. } else {
  7015. // Check for error status codes
  7016. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7017. response.find("Payload Too Large") != std::string::npos ||
  7018. response.find("400") != std::string::npos);
  7019. }
  7020. }
  7021. }
  7022. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7023. // Test request without Content-Length header exceeding payload limit
  7024. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7025. "Host: " +
  7026. std::string(HOST) + ":" +
  7027. std::to_string(PORT) +
  7028. "\r\n"
  7029. "Connection: close\r\n"
  7030. "\r\n";
  7031. // Add payload exceeding the 8-byte limit
  7032. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7033. request_without_content_length += large_payload;
  7034. std::string response;
  7035. bool result = send_request(1, request_without_content_length, &response);
  7036. if (!result) {
  7037. // If send_request fails, server likely closed connection due to payload
  7038. // limit
  7039. SUCCEED() << "Server rejected oversized request without Content-Length "
  7040. "(connection closed)";
  7041. } else {
  7042. // Check if server responded with error or closed connection early
  7043. if (response.length() <= 10) {
  7044. SUCCEED() << "Server closed connection for oversized request without "
  7045. "Content-Length";
  7046. } else {
  7047. // Check for error status codes
  7048. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7049. response.find("Payload Too Large") != std::string::npos ||
  7050. response.find("400") != std::string::npos);
  7051. }
  7052. }
  7053. }
  7054. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7055. // Test request without Content-Length header within payload limit
  7056. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7057. "Host: " +
  7058. std::string(HOST) + ":" +
  7059. std::to_string(PORT) +
  7060. "\r\n"
  7061. "Connection: close\r\n"
  7062. "\r\n";
  7063. // Add payload within the 8-byte limit
  7064. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7065. request_without_content_length += small_payload;
  7066. std::string response;
  7067. bool result = send_request(1, request_without_content_length, &response);
  7068. // For requests without Content-Length, the server may have different behavior
  7069. // The key is that it should not reject due to payload limit for small
  7070. // payloads
  7071. if (result) {
  7072. // Check for any HTTP response (success or error, but not connection closed)
  7073. if (response.length() > 10) {
  7074. SUCCEED()
  7075. << "Server processed request without Content-Length within limit";
  7076. } else {
  7077. // Short response might indicate connection closed, which is acceptable
  7078. SUCCEED() << "Server closed connection for request without "
  7079. "Content-Length (acceptable behavior)";
  7080. }
  7081. } else {
  7082. // Connection failure might be due to protocol requirements
  7083. SUCCEED() << "Connection issue with request without Content-Length "
  7084. "(environment-specific)";
  7085. }
  7086. }
  7087. class LargePayloadMaxLengthTest : public ::testing::Test {
  7088. protected:
  7089. LargePayloadMaxLengthTest()
  7090. : cli_(HOST, PORT)
  7091. #ifdef CPPHTTPLIB_SSL_ENABLED
  7092. ,
  7093. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7094. #endif
  7095. {
  7096. #ifdef CPPHTTPLIB_SSL_ENABLED
  7097. cli_.enable_server_certificate_verification(false);
  7098. #endif
  7099. }
  7100. virtual void SetUp() {
  7101. // Set 10MB payload limit
  7102. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7103. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7104. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7105. res.set_content("Large payload test", "text/plain");
  7106. });
  7107. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7108. svr_.wait_until_ready();
  7109. }
  7110. virtual void TearDown() {
  7111. svr_.stop();
  7112. t_.join();
  7113. }
  7114. #ifdef CPPHTTPLIB_SSL_ENABLED
  7115. SSLClient cli_;
  7116. SSLServer svr_;
  7117. #else
  7118. Client cli_;
  7119. Server svr_;
  7120. #endif
  7121. thread t_;
  7122. };
  7123. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7124. // Test chunked encoding with payload within 10MB limit
  7125. std::string medium_payload(5 * 1024 * 1024,
  7126. 'A'); // 5MB payload, within 10MB limit
  7127. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7128. ASSERT_TRUE(res);
  7129. EXPECT_EQ(StatusCode::OK_200, res->status);
  7130. }
  7131. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7132. // Test chunked encoding with payload exceeding 10MB limit
  7133. std::string large_payload(12 * 1024 * 1024,
  7134. 'B'); // 12MB payload, exceeds 10MB limit
  7135. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7136. // Server may either return 413 or close the connection
  7137. if (res) {
  7138. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7139. } else {
  7140. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7141. }
  7142. }
  7143. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7144. // Test request without Content-Length header within 10MB limit
  7145. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7146. "Host: " +
  7147. std::string(HOST) + ":" +
  7148. std::to_string(PORT) +
  7149. "\r\n"
  7150. "Connection: close\r\n"
  7151. "\r\n";
  7152. // Add 1MB payload (within 10MB limit)
  7153. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7154. request_without_content_length += medium_payload;
  7155. std::string response;
  7156. bool result = send_request(5, request_without_content_length, &response);
  7157. if (result) {
  7158. // Should get a proper HTTP response for payloads within limit
  7159. if (response.length() > 10) {
  7160. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7161. "10MB limit";
  7162. } else {
  7163. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7164. "Content-Length)";
  7165. }
  7166. } else {
  7167. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7168. }
  7169. }
  7170. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7171. // Test request without Content-Length header exceeding 10MB limit
  7172. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7173. "Host: " +
  7174. std::string(HOST) + ":" +
  7175. std::to_string(PORT) +
  7176. "\r\n"
  7177. "Connection: close\r\n"
  7178. "\r\n";
  7179. // Add 12MB payload (exceeds 10MB limit)
  7180. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7181. request_without_content_length += large_payload;
  7182. std::string response;
  7183. bool result = send_request(10, request_without_content_length, &response);
  7184. if (!result) {
  7185. // Server should close connection due to payload limit
  7186. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7187. "(connection closed)";
  7188. } else {
  7189. // Check for error response
  7190. if (response.length() <= 10) {
  7191. SUCCEED()
  7192. << "Server closed connection for 12MB request exceeding 10MB limit";
  7193. } else {
  7194. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7195. response.find("Payload Too Large") != std::string::npos ||
  7196. response.find("400") != std::string::npos);
  7197. }
  7198. }
  7199. }
  7200. // Regression test for DoS vulnerability: a malicious server sending a response
  7201. // without Content-Length header must not cause unbounded memory consumption on
  7202. // the client side. The client should stop reading after a reasonable limit,
  7203. // similar to the server-side set_payload_max_length protection.
  7204. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7205. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7206. #ifndef _WIN32
  7207. signal(SIGPIPE, SIG_IGN);
  7208. #endif
  7209. auto server_thread = std::thread([] {
  7210. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7211. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7212. default_socket_options(srv);
  7213. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7214. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7215. sockaddr_in addr{};
  7216. addr.sin_family = AF_INET;
  7217. addr.sin_port = htons(PORT + 2);
  7218. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7219. int opt = 1;
  7220. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7221. #ifdef _WIN32
  7222. reinterpret_cast<const char *>(&opt),
  7223. #else
  7224. &opt,
  7225. #endif
  7226. sizeof(opt));
  7227. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7228. ::listen(srv, 1);
  7229. sockaddr_in cli_addr{};
  7230. socklen_t cli_len = sizeof(cli_addr);
  7231. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7232. if (cli != INVALID_SOCKET) {
  7233. char buf[4096];
  7234. ::recv(cli, buf, sizeof(buf), 0);
  7235. // Malicious response: no Content-Length, no chunked encoding
  7236. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7237. "Connection: close\r\n"
  7238. "\r\n";
  7239. ::send(cli,
  7240. #ifdef _WIN32
  7241. static_cast<const char *>(response_header.c_str()),
  7242. static_cast<int>(response_header.size()),
  7243. #else
  7244. response_header.c_str(), response_header.size(),
  7245. #endif
  7246. 0);
  7247. // Send 10MB of data
  7248. std::string chunk(64 * 1024, 'A');
  7249. size_t total_sent = 0;
  7250. while (total_sent < MALICIOUS_DATA_SIZE) {
  7251. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7252. auto sent = ::send(cli,
  7253. #ifdef _WIN32
  7254. static_cast<const char *>(chunk.c_str()),
  7255. static_cast<int>(to_send),
  7256. #else
  7257. chunk.c_str(), to_send,
  7258. #endif
  7259. 0);
  7260. if (sent <= 0) break;
  7261. total_sent += static_cast<size_t>(sent);
  7262. }
  7263. detail::close_socket(cli);
  7264. }
  7265. detail::close_socket(srv);
  7266. });
  7267. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7268. size_t total_read = 0;
  7269. {
  7270. Client cli("127.0.0.1", PORT + 2);
  7271. cli.set_read_timeout(5, 0);
  7272. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7273. auto stream = cli.open_stream("GET", "/malicious");
  7274. ASSERT_TRUE(stream.is_valid());
  7275. char buffer[64 * 1024];
  7276. ssize_t n;
  7277. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7278. total_read += static_cast<size_t>(n);
  7279. }
  7280. } // StreamHandle and Client destroyed here, closing the socket
  7281. server_thread.join();
  7282. // With set_payload_max_length, the client must stop reading before consuming
  7283. // all 10MB. The read loop should be cut off at or near the configured limit.
  7284. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7285. << "Client read " << total_read << " bytes, exceeding the configured "
  7286. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7287. }
  7288. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7289. // the entire response body without truncation.
  7290. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7291. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7292. #ifndef _WIN32
  7293. signal(SIGPIPE, SIG_IGN);
  7294. #endif
  7295. auto server_thread = std::thread([] {
  7296. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7297. default_socket_options(srv);
  7298. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7299. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7300. sockaddr_in addr{};
  7301. addr.sin_family = AF_INET;
  7302. addr.sin_port = htons(PORT + 2);
  7303. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7304. int opt = 1;
  7305. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7306. #ifdef _WIN32
  7307. reinterpret_cast<const char *>(&opt),
  7308. #else
  7309. &opt,
  7310. #endif
  7311. sizeof(opt));
  7312. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7313. ::listen(srv, 1);
  7314. sockaddr_in cli_addr{};
  7315. socklen_t cli_len = sizeof(cli_addr);
  7316. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7317. if (cli != INVALID_SOCKET) {
  7318. char buf[4096];
  7319. ::recv(cli, buf, sizeof(buf), 0);
  7320. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7321. "Connection: close\r\n"
  7322. "\r\n";
  7323. ::send(cli,
  7324. #ifdef _WIN32
  7325. static_cast<const char *>(response_header.c_str()),
  7326. static_cast<int>(response_header.size()),
  7327. #else
  7328. response_header.c_str(), response_header.size(),
  7329. #endif
  7330. 0);
  7331. std::string chunk(64 * 1024, 'A');
  7332. size_t total_sent = 0;
  7333. while (total_sent < DATA_SIZE) {
  7334. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7335. auto sent = ::send(cli,
  7336. #ifdef _WIN32
  7337. static_cast<const char *>(chunk.c_str()),
  7338. static_cast<int>(to_send),
  7339. #else
  7340. chunk.c_str(), to_send,
  7341. #endif
  7342. 0);
  7343. if (sent <= 0) break;
  7344. total_sent += static_cast<size_t>(sent);
  7345. }
  7346. #ifdef _WIN32
  7347. ::shutdown(cli, SD_SEND);
  7348. #else
  7349. ::shutdown(cli, SHUT_WR);
  7350. #endif
  7351. // Drain until the client closes its end, ensuring all data is delivered
  7352. char drain[1024];
  7353. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7354. detail::close_socket(cli);
  7355. }
  7356. detail::close_socket(srv);
  7357. });
  7358. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7359. size_t total_read = 0;
  7360. {
  7361. Client cli("127.0.0.1", PORT + 2);
  7362. cli.set_read_timeout(5, 0);
  7363. cli.set_payload_max_length(0); // 0 means no limit
  7364. auto stream = cli.open_stream("GET", "/data");
  7365. ASSERT_TRUE(stream.is_valid());
  7366. char buffer[64 * 1024];
  7367. ssize_t n;
  7368. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7369. total_read += static_cast<size_t>(n);
  7370. }
  7371. }
  7372. server_thread.join();
  7373. EXPECT_EQ(total_read, DATA_SIZE)
  7374. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7375. << " bytes without truncation, but only read " << total_read << " bytes.";
  7376. }
  7377. // Verify that content_receiver bypasses the default payload_max_length,
  7378. // allowing streaming downloads larger than 100MB without requiring an explicit
  7379. // set_payload_max_length call.
  7380. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7381. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7382. #ifndef _WIN32
  7383. signal(SIGPIPE, SIG_IGN);
  7384. #endif
  7385. auto server_thread = std::thread([] {
  7386. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7387. default_socket_options(srv);
  7388. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7389. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7390. sockaddr_in addr{};
  7391. addr.sin_family = AF_INET;
  7392. addr.sin_port = htons(PORT + 2);
  7393. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7394. int opt = 1;
  7395. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7396. #ifdef _WIN32
  7397. reinterpret_cast<const char *>(&opt),
  7398. #else
  7399. &opt,
  7400. #endif
  7401. sizeof(opt));
  7402. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7403. ::listen(srv, 1);
  7404. sockaddr_in cli_addr{};
  7405. socklen_t cli_len = sizeof(cli_addr);
  7406. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7407. if (cli != INVALID_SOCKET) {
  7408. char buf[4096];
  7409. ::recv(cli, buf, sizeof(buf), 0);
  7410. // Response with Content-Length larger than default 100MB limit
  7411. auto content_length = std::to_string(DATA_SIZE);
  7412. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7413. "Content-Length: " +
  7414. content_length +
  7415. "\r\n"
  7416. "Connection: close\r\n"
  7417. "\r\n";
  7418. ::send(cli,
  7419. #ifdef _WIN32
  7420. static_cast<const char *>(response_header.c_str()),
  7421. static_cast<int>(response_header.size()),
  7422. #else
  7423. response_header.c_str(), response_header.size(),
  7424. #endif
  7425. 0);
  7426. std::string chunk(64 * 1024, 'A');
  7427. size_t total_sent = 0;
  7428. while (total_sent < DATA_SIZE) {
  7429. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7430. auto sent = ::send(cli,
  7431. #ifdef _WIN32
  7432. static_cast<const char *>(chunk.c_str()),
  7433. static_cast<int>(to_send),
  7434. #else
  7435. chunk.c_str(), to_send,
  7436. #endif
  7437. 0);
  7438. if (sent <= 0) break;
  7439. total_sent += static_cast<size_t>(sent);
  7440. }
  7441. detail::close_socket(cli);
  7442. }
  7443. detail::close_socket(srv);
  7444. });
  7445. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7446. size_t total_received = 0;
  7447. {
  7448. Client cli("127.0.0.1", PORT + 2);
  7449. cli.set_read_timeout(10, 0);
  7450. // Do NOT call set_payload_max_length — use the default 100MB limit
  7451. auto res =
  7452. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7453. total_received += data_length;
  7454. return true;
  7455. });
  7456. ASSERT_TRUE(res);
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. }
  7459. server_thread.join();
  7460. EXPECT_EQ(total_received, DATA_SIZE)
  7461. << "With content_receiver, the client should read all " << DATA_SIZE
  7462. << " bytes despite the default 100MB payload_max_length, but only read "
  7463. << total_received << " bytes.";
  7464. }
  7465. // Verify that an explicit set_payload_max_length smaller than the response is
  7466. // enforced even when a content_receiver is used.
  7467. TEST(ClientVulnerabilityTest,
  7468. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7469. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7470. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7471. #ifndef _WIN32
  7472. signal(SIGPIPE, SIG_IGN);
  7473. #endif
  7474. auto server_thread = std::thread([] {
  7475. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7476. default_socket_options(srv);
  7477. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7478. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7479. sockaddr_in addr{};
  7480. addr.sin_family = AF_INET;
  7481. addr.sin_port = htons(PORT + 2);
  7482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7483. int opt = 1;
  7484. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7485. #ifdef _WIN32
  7486. reinterpret_cast<const char *>(&opt),
  7487. #else
  7488. &opt,
  7489. #endif
  7490. sizeof(opt));
  7491. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7492. ::listen(srv, 1);
  7493. sockaddr_in cli_addr{};
  7494. socklen_t cli_len = sizeof(cli_addr);
  7495. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7496. if (cli != INVALID_SOCKET) {
  7497. char buf[4096];
  7498. ::recv(cli, buf, sizeof(buf), 0);
  7499. auto content_length = std::to_string(DATA_SIZE);
  7500. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7501. "Content-Length: " +
  7502. content_length +
  7503. "\r\n"
  7504. "Connection: close\r\n"
  7505. "\r\n";
  7506. ::send(cli,
  7507. #ifdef _WIN32
  7508. static_cast<const char *>(response_header.c_str()),
  7509. static_cast<int>(response_header.size()),
  7510. #else
  7511. response_header.c_str(), response_header.size(),
  7512. #endif
  7513. 0);
  7514. std::string chunk(64 * 1024, 'A');
  7515. size_t total_sent = 0;
  7516. while (total_sent < DATA_SIZE) {
  7517. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7518. auto sent = ::send(cli,
  7519. #ifdef _WIN32
  7520. static_cast<const char *>(chunk.c_str()),
  7521. static_cast<int>(to_send),
  7522. #else
  7523. chunk.c_str(), to_send,
  7524. #endif
  7525. 0);
  7526. if (sent <= 0) break;
  7527. total_sent += static_cast<size_t>(sent);
  7528. }
  7529. detail::close_socket(cli);
  7530. }
  7531. detail::close_socket(srv);
  7532. });
  7533. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7534. size_t total_received = 0;
  7535. {
  7536. Client cli("127.0.0.1", PORT + 2);
  7537. cli.set_read_timeout(10, 0);
  7538. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7539. auto res =
  7540. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7541. total_received += data_length;
  7542. return true;
  7543. });
  7544. // Should fail because 200MB exceeds the explicit 150MB limit
  7545. EXPECT_FALSE(res);
  7546. }
  7547. server_thread.join();
  7548. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7549. << "Client with content_receiver should respect the explicit "
  7550. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7551. << total_received << " bytes.";
  7552. }
  7553. // Verify that an explicit set_payload_max_length larger than the response
  7554. // allows the content_receiver to read all data successfully.
  7555. TEST(ClientVulnerabilityTest,
  7556. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7557. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7558. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7559. #ifndef _WIN32
  7560. signal(SIGPIPE, SIG_IGN);
  7561. #endif
  7562. auto server_thread = std::thread([] {
  7563. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7564. default_socket_options(srv);
  7565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7566. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7567. sockaddr_in addr{};
  7568. addr.sin_family = AF_INET;
  7569. addr.sin_port = htons(PORT + 2);
  7570. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7571. int opt = 1;
  7572. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7573. #ifdef _WIN32
  7574. reinterpret_cast<const char *>(&opt),
  7575. #else
  7576. &opt,
  7577. #endif
  7578. sizeof(opt));
  7579. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7580. ::listen(srv, 1);
  7581. sockaddr_in cli_addr{};
  7582. socklen_t cli_len = sizeof(cli_addr);
  7583. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7584. if (cli != INVALID_SOCKET) {
  7585. char buf[4096];
  7586. ::recv(cli, buf, sizeof(buf), 0);
  7587. auto content_length = std::to_string(DATA_SIZE);
  7588. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7589. "Content-Length: " +
  7590. content_length +
  7591. "\r\n"
  7592. "Connection: close\r\n"
  7593. "\r\n";
  7594. ::send(cli,
  7595. #ifdef _WIN32
  7596. static_cast<const char *>(response_header.c_str()),
  7597. static_cast<int>(response_header.size()),
  7598. #else
  7599. response_header.c_str(), response_header.size(),
  7600. #endif
  7601. 0);
  7602. std::string chunk(64 * 1024, 'A');
  7603. size_t total_sent = 0;
  7604. while (total_sent < DATA_SIZE) {
  7605. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7606. auto sent = ::send(cli,
  7607. #ifdef _WIN32
  7608. static_cast<const char *>(chunk.c_str()),
  7609. static_cast<int>(to_send),
  7610. #else
  7611. chunk.c_str(), to_send,
  7612. #endif
  7613. 0);
  7614. if (sent <= 0) break;
  7615. total_sent += static_cast<size_t>(sent);
  7616. }
  7617. #ifdef _WIN32
  7618. ::shutdown(cli, SD_SEND);
  7619. #else
  7620. ::shutdown(cli, SHUT_WR);
  7621. #endif
  7622. char drain[1024];
  7623. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7624. detail::close_socket(cli);
  7625. }
  7626. detail::close_socket(srv);
  7627. });
  7628. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7629. size_t total_received = 0;
  7630. {
  7631. Client cli("127.0.0.1", PORT + 2);
  7632. cli.set_read_timeout(10, 0);
  7633. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7634. auto res =
  7635. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7636. total_received += data_length;
  7637. return true;
  7638. });
  7639. ASSERT_TRUE(res);
  7640. EXPECT_EQ(StatusCode::OK_200, res->status);
  7641. }
  7642. server_thread.join();
  7643. EXPECT_EQ(total_received, DATA_SIZE)
  7644. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7645. << " bytes (larger than " << DATA_SIZE
  7646. << " bytes response), content_receiver should read all data, but only "
  7647. "read "
  7648. << total_received << " bytes.";
  7649. }
  7650. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7651. // Regression test for "zip bomb" attack on the client side: a malicious server
  7652. // sends a small gzip-compressed response that decompresses to a huge payload.
  7653. // The client must enforce payload_max_length on the decompressed size.
  7654. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7655. constexpr size_t DECOMPRESSED_SIZE =
  7656. 10 * 1024 * 1024; // 10MB after decompression
  7657. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7658. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7659. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7660. std::string compressed;
  7661. {
  7662. httplib::detail::gzip_compressor compressor;
  7663. bool ok =
  7664. compressor.compress(uncompressed.data(), uncompressed.size(),
  7665. /*last=*/true, [&](const char *buf, size_t len) {
  7666. compressed.append(buf, len);
  7667. return true;
  7668. });
  7669. ASSERT_TRUE(ok);
  7670. }
  7671. // Sanity: compressed data should be much smaller than the decompressed size
  7672. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7673. #ifndef _WIN32
  7674. signal(SIGPIPE, SIG_IGN);
  7675. #endif
  7676. // Set up the listening socket in the main thread so the server is guaranteed
  7677. // to be ready before the client connects (eliminates race condition).
  7678. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7679. default_socket_options(srv);
  7680. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7681. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7682. sockaddr_in addr{};
  7683. addr.sin_family = AF_INET;
  7684. addr.sin_port = htons(PORT + 3);
  7685. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7686. int opt = 1;
  7687. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7688. #ifdef _WIN32
  7689. reinterpret_cast<const char *>(&opt),
  7690. #else
  7691. &opt,
  7692. #endif
  7693. sizeof(opt));
  7694. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7695. ASSERT_EQ(0, ::listen(srv, 1));
  7696. auto server_thread = std::thread([&compressed, srv] {
  7697. sockaddr_in cli_addr{};
  7698. socklen_t cli_len = sizeof(cli_addr);
  7699. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7700. if (cli != INVALID_SOCKET) {
  7701. char buf[4096];
  7702. ::recv(cli, buf, sizeof(buf), 0);
  7703. // Malicious response: gzip-compressed body, no Content-Length
  7704. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7705. "Content-Encoding: gzip\r\n"
  7706. "Connection: close\r\n"
  7707. "\r\n";
  7708. ::send(cli,
  7709. #ifdef _WIN32
  7710. static_cast<const char *>(response_header.c_str()),
  7711. static_cast<int>(response_header.size()),
  7712. #else
  7713. response_header.c_str(), response_header.size(),
  7714. #endif
  7715. 0);
  7716. // Send the compressed payload (small on the wire, huge when decompressed)
  7717. size_t total_sent = 0;
  7718. while (total_sent < compressed.size()) {
  7719. auto to_send = std::min(compressed.size() - total_sent,
  7720. static_cast<size_t>(64 * 1024));
  7721. auto sent =
  7722. ::send(cli,
  7723. #ifdef _WIN32
  7724. static_cast<const char *>(compressed.c_str() + total_sent),
  7725. static_cast<int>(to_send),
  7726. #else
  7727. compressed.c_str() + total_sent, to_send,
  7728. #endif
  7729. 0);
  7730. if (sent <= 0) break;
  7731. total_sent += static_cast<size_t>(sent);
  7732. }
  7733. detail::close_socket(cli);
  7734. }
  7735. });
  7736. auto se = detail::scope_exit([&] {
  7737. detail::close_socket(srv);
  7738. server_thread.join();
  7739. });
  7740. size_t total_decompressed = 0;
  7741. {
  7742. Client cli("127.0.0.1", PORT + 3);
  7743. cli.set_read_timeout(5, 0);
  7744. cli.set_decompress(true);
  7745. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7746. auto stream = cli.open_stream("GET", "/zipbomb");
  7747. ASSERT_TRUE(stream.is_valid());
  7748. char buffer[64 * 1024];
  7749. ssize_t n;
  7750. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7751. total_decompressed += static_cast<size_t>(n);
  7752. }
  7753. }
  7754. // The decompressed size must be capped by payload_max_length. Without
  7755. // protection, the client would decompress the full 10MB from a tiny
  7756. // compressed payload, enabling a zip bomb DoS attack.
  7757. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7758. << "Client decompressed " << total_decompressed
  7759. << " bytes from a gzip response. The decompressed size should be "
  7760. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7761. }
  7762. #endif
  7763. TEST(HostAndPortPropertiesTest, NoSSL) {
  7764. httplib::Client cli("www.google.com", 1234);
  7765. ASSERT_EQ("www.google.com", cli.host());
  7766. ASSERT_EQ(1234, cli.port());
  7767. }
  7768. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7769. httplib::Client cli("www.google.com:1234");
  7770. ASSERT_EQ("www.google.com", cli.host());
  7771. ASSERT_EQ(1234, cli.port());
  7772. }
  7773. #ifdef CPPHTTPLIB_SSL_ENABLED
  7774. TEST(HostAndPortPropertiesTest, SSL) {
  7775. httplib::SSLClient cli("www.google.com");
  7776. ASSERT_EQ("www.google.com", cli.host());
  7777. ASSERT_EQ(443, cli.port());
  7778. }
  7779. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7780. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7781. std::string cert;
  7782. read_file(CA_CERT_FILE, cert);
  7783. httplib::SSLClient httplib_client("www.google.com");
  7784. // Load CA store first time
  7785. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7786. // Load CA store second time (update)
  7787. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7788. // Verify client is still valid and can make connections
  7789. httplib_client.enable_server_certificate_verification(true);
  7790. auto res = httplib_client.Get("/");
  7791. ASSERT_TRUE(res);
  7792. // Google may return 200 or 301 depending on various factors
  7793. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7794. res->status == StatusCode::MovedPermanently_301);
  7795. }
  7796. TEST(SSLClientTest, ServerNameIndication_Online) {
  7797. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7798. auto host = "httpcan.org";
  7799. auto path = std::string{"/get"};
  7800. #else
  7801. auto host = "nghttp2.org";
  7802. auto path = std::string{"/httpbin/get"};
  7803. #endif
  7804. SSLClient cli(host, 443);
  7805. auto res = cli.Get(path);
  7806. ASSERT_TRUE(res);
  7807. ASSERT_EQ(StatusCode::OK_200, res->status);
  7808. }
  7809. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7810. // Use a site that will cause SSL verification failure due to self-signed cert
  7811. SSLClient cli("self-signed.badssl.com", 443);
  7812. cli.enable_server_certificate_verification(true);
  7813. auto res = cli.Get("/");
  7814. ASSERT_TRUE(!res);
  7815. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7816. // Verify backend error is captured for SSLServerVerification
  7817. // This occurs when certificate verification fails
  7818. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7819. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7820. EXPECT_NE(0UL, res.ssl_backend_error());
  7821. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7822. // For OpenSSL, ssl_error is 0 for verification errors
  7823. EXPECT_EQ(0, res.ssl_error());
  7824. #if !defined(_WIN32) || \
  7825. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7826. // On non-Windows or when Windows Schannel is disabled, the error comes
  7827. // from OpenSSL's verification
  7828. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7829. res.ssl_backend_error());
  7830. #endif
  7831. #endif
  7832. }
  7833. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7834. // Use a site where hostname doesn't match the certificate
  7835. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7836. SSLClient cli("wrong.host.badssl.com", 443);
  7837. cli.enable_server_certificate_verification(true);
  7838. cli.enable_server_hostname_verification(true);
  7839. auto res = cli.Get("/");
  7840. ASSERT_TRUE(!res);
  7841. // The error type depends on when hostname verification occurs:
  7842. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7843. // - Mbed TLS: SSLServerVerification (during handshake)
  7844. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7845. res.error() == Error::SSLServerVerification);
  7846. // Verify backend error is captured for hostname verification failure
  7847. EXPECT_NE(0UL, res.ssl_backend_error());
  7848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7849. // For OpenSSL, ssl_error is 0 for verification errors
  7850. EXPECT_EQ(0, res.ssl_error());
  7851. #if !defined(_WIN32) || \
  7852. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7853. // On non-Windows or when Windows Schannel is disabled, the error comes
  7854. // from OpenSSL's hostname verification
  7855. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7856. res.ssl_backend_error());
  7857. #endif
  7858. #endif
  7859. }
  7860. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  7861. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7862. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  7863. SSLClient cli("www.google.com", 443);
  7864. cli.enable_server_certificate_verification(true);
  7865. auto res = cli.Get("/");
  7866. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7867. }
  7868. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  7869. SSLClient cli("www.google.com", 443);
  7870. cli.enable_server_certificate_verification(true);
  7871. cli.enable_windows_certificate_verification(false);
  7872. auto res = cli.Get("/");
  7873. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7874. }
  7875. #endif
  7876. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7877. Client cli("https://google.com");
  7878. auto res = cli.Get("/");
  7879. ASSERT_TRUE(res);
  7880. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7881. }
  7882. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7883. SSLClient cli("google.com");
  7884. cli.set_ca_cert_path(CA_CERT_FILE);
  7885. auto res = cli.Get("/");
  7886. ASSERT_TRUE(res);
  7887. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7888. }
  7889. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7890. SSLClient cli("google.com");
  7891. cli.enable_server_certificate_verification(true);
  7892. cli.set_ca_cert_path("hello");
  7893. auto res = cli.Get("/");
  7894. ASSERT_TRUE(!res);
  7895. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7896. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7897. // should be set
  7898. EXPECT_EQ(0, res.ssl_error());
  7899. // Verify backend error is captured for SSLLoadingCerts
  7900. // This error occurs when loading CA certificates fails
  7901. EXPECT_NE(0UL, res.ssl_backend_error());
  7902. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7903. // OpenSSL specific error codes:
  7904. // > openssl errstr 0x80000002
  7905. // error:80000002:system library::No such file or directory
  7906. // > openssl errstr 0xA000126
  7907. // error:0A000126:SSL routines::unexpected eof while reading
  7908. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7909. res.ssl_backend_error() == 0xA000126);
  7910. #endif
  7911. }
  7912. TEST(SSLClientTest, ServerCertificateVerification4) {
  7913. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7914. ASSERT_TRUE(svr.is_valid());
  7915. svr.Get("/test", [&](const Request &, Response &res) {
  7916. res.set_content("test", "text/plain");
  7917. svr.stop();
  7918. ASSERT_TRUE(true);
  7919. });
  7920. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7921. auto se = detail::scope_exit([&] {
  7922. t.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. SSLClient cli("127.0.0.1", PORT);
  7927. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7928. cli.enable_server_certificate_verification(true);
  7929. cli.set_connection_timeout(30);
  7930. auto res = cli.Get("/test");
  7931. ASSERT_TRUE(res);
  7932. ASSERT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7935. std::string cert;
  7936. read_file(CA_CERT_FILE, cert);
  7937. SSLClient cli("google.com");
  7938. cli.load_ca_cert_store(cert.data(), cert.size());
  7939. const auto res = cli.Get("/");
  7940. ASSERT_TRUE(res);
  7941. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7942. }
  7943. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7944. // clang-format off
  7945. static constexpr char cert[] =
  7946. "GlobalSign Root CA\n"
  7947. "==================\n"
  7948. "-----BEGIN CERTIFICATE-----\n"
  7949. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7950. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7951. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7952. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7953. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7954. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7955. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7956. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7957. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7958. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7959. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7960. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7961. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7962. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7963. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7964. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7965. "-----END CERTIFICATE-----\n";
  7966. // clang-format on
  7967. SSLClient cli("google.com");
  7968. cli.load_ca_cert_store(cert, sizeof(cert));
  7969. const auto res = cli.Get("/");
  7970. ASSERT_TRUE(res);
  7971. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7972. }
  7973. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7974. SSLClient cli("www.youtube.com");
  7975. cli.set_ca_cert_path(CA_CERT_FILE);
  7976. cli.enable_server_certificate_verification(true);
  7977. cli.set_follow_location(true);
  7978. auto res = cli.Get("/");
  7979. ASSERT_TRUE(res);
  7980. ASSERT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7983. SSLClient cli("wWw.YouTube.Com");
  7984. cli.set_ca_cert_path(CA_CERT_FILE);
  7985. cli.enable_server_certificate_verification(true);
  7986. cli.enable_server_hostname_verification(true);
  7987. cli.set_follow_location(true);
  7988. auto res = cli.Get("/");
  7989. ASSERT_TRUE(res);
  7990. ASSERT_EQ(StatusCode::OK_200, res->status);
  7991. }
  7992. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7993. SSLClient cli("gOoGlE.COm");
  7994. cli.enable_server_certificate_verification(true);
  7995. cli.enable_server_hostname_verification(true);
  7996. cli.set_follow_location(true);
  7997. auto res = cli.Get("/");
  7998. ASSERT_TRUE(res);
  7999. ASSERT_EQ(StatusCode::OK_200, res->status);
  8000. }
  8001. TEST(SSLClientTest, Issue2004_Online) {
  8002. Client client("https://google.com");
  8003. client.set_follow_location(true);
  8004. auto res = client.Get("/");
  8005. ASSERT_TRUE(res);
  8006. ASSERT_EQ(StatusCode::OK_200, res->status);
  8007. auto body = res->body;
  8008. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8009. }
  8010. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8011. // Create SSLClient with invalid cert/key to make is_valid() return false
  8012. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8013. "nonexistent_key.pem");
  8014. // is_valid() should be false due to cert loading failure
  8015. ASSERT_FALSE(cli.is_valid());
  8016. auto res = cli.Get("/");
  8017. ASSERT_FALSE(res);
  8018. EXPECT_EQ(Error::SSLConnection, res.error());
  8019. }
  8020. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8021. // Test for Issue #2251: SSL error not properly reported when client cert
  8022. // and key paths are swapped or mismatched
  8023. // This simulates the scenario where user accidentally swaps the cert and key
  8024. // files
  8025. // Using client cert file as private key and vice versa (completely wrong)
  8026. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8027. // Should fail validation due to cert/key mismatch
  8028. ASSERT_FALSE(cli.is_valid());
  8029. // Attempt to make a request should fail with proper error
  8030. auto res = cli.Get("/");
  8031. ASSERT_FALSE(res);
  8032. EXPECT_EQ(Error::SSLConnection, res.error());
  8033. // SSL error should be recorded in the Result object (this is the key fix for
  8034. // Issue #2251)
  8035. auto backend_error = res.ssl_backend_error();
  8036. EXPECT_NE(0u, backend_error);
  8037. }
  8038. // Tests cert/key mismatch detection at the TLS context level
  8039. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8040. // Test that using mismatched cert/key causes connection failure.
  8041. // We verify this at the SSLClient level rather than through internal
  8042. // TLS API functions.
  8043. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8044. cli.enable_server_certificate_verification(false);
  8045. cli.set_connection_timeout(2);
  8046. // The mismatch should cause a connection or handshake error
  8047. auto res = cli.Get("/test");
  8048. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8049. // Either way, the request should fail
  8050. EXPECT_FALSE(res);
  8051. }
  8052. #endif
  8053. #if 0
  8054. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8055. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8056. ASSERT_TRUE(cli != nullptr);
  8057. cli->set_address_family(AF_INET6);
  8058. cli->set_interface("en0");
  8059. auto res = cli->Get("/get");
  8060. ASSERT_TRUE(res);
  8061. ASSERT_EQ(StatusCode::OK_200, res->status);
  8062. }
  8063. #endif
  8064. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8065. #ifdef CPPHTTPLIB_SSL_ENABLED
  8066. void ClientCertPresent(
  8067. const std::string &client_cert_file,
  8068. const std::string &client_private_key_file,
  8069. const std::string &client_encrypted_private_key_pass = std::string()) {
  8070. using namespace httplib::tls;
  8071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8072. CLIENT_CA_CERT_DIR);
  8073. ASSERT_TRUE(svr.is_valid());
  8074. svr.Get("/test", [&](const Request &req, Response &res) {
  8075. res.set_content("test", "text/plain");
  8076. auto cert = req.peer_cert();
  8077. ASSERT_TRUE(static_cast<bool>(cert));
  8078. std::string common_name = cert.subject_cn();
  8079. EXPECT_EQ("Common Name", common_name);
  8080. });
  8081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8082. auto se = detail::scope_exit([&] {
  8083. svr.stop();
  8084. t.join();
  8085. ASSERT_FALSE(svr.is_running());
  8086. });
  8087. svr.wait_until_ready();
  8088. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8089. client_encrypted_private_key_pass);
  8090. cli.enable_server_certificate_verification(false);
  8091. cli.set_connection_timeout(30);
  8092. auto res = cli.Get("/test");
  8093. ASSERT_TRUE(res);
  8094. ASSERT_EQ(StatusCode::OK_200, res->status);
  8095. }
  8096. TEST(SSLClientServerTest, ClientCertPresent) {
  8097. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8098. }
  8099. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8100. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8101. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8102. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8103. }
  8104. // PEM memory-based constructor tests (works with all TLS backends)
  8105. void PemMemoryClientCertPresent(
  8106. const std::string &client_cert_file,
  8107. const std::string &client_private_key_file,
  8108. const std::string &client_encrypted_private_key_pass = std::string()) {
  8109. // Read PEM files into memory
  8110. std::string server_cert_pem, server_key_pem;
  8111. std::string client_ca_pem;
  8112. std::string client_cert_pem, client_key_pem;
  8113. read_file(SERVER_CERT_FILE, server_cert_pem);
  8114. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8115. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8116. read_file(client_cert_file, client_cert_pem);
  8117. read_file(client_private_key_file, client_key_pem);
  8118. // Create server with PEM memory
  8119. SSLServer::PemMemory server_pem = {
  8120. server_cert_pem.c_str(),
  8121. server_cert_pem.size(),
  8122. server_key_pem.c_str(),
  8123. server_key_pem.size(),
  8124. client_ca_pem.c_str(),
  8125. client_ca_pem.size(),
  8126. nullptr // no password for server key
  8127. };
  8128. SSLServer svr(server_pem);
  8129. ASSERT_TRUE(svr.is_valid());
  8130. svr.Get("/test", [&](const Request &, Response &res) {
  8131. res.set_content("test", "text/plain");
  8132. });
  8133. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8134. auto se = detail::scope_exit([&] {
  8135. svr.stop();
  8136. t.join();
  8137. ASSERT_FALSE(svr.is_running());
  8138. });
  8139. svr.wait_until_ready();
  8140. // Create client with PEM memory
  8141. const char *password = client_encrypted_private_key_pass.empty()
  8142. ? nullptr
  8143. : client_encrypted_private_key_pass.c_str();
  8144. SSLClient::PemMemory client_pem = {
  8145. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8146. client_key_pem.size(), password};
  8147. SSLClient cli(HOST, PORT, client_pem);
  8148. cli.enable_server_certificate_verification(false);
  8149. cli.set_connection_timeout(30);
  8150. auto res = cli.Get("/test");
  8151. ASSERT_TRUE(res);
  8152. ASSERT_EQ(StatusCode::OK_200, res->status);
  8153. }
  8154. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8155. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8156. }
  8157. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8158. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8159. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8160. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8161. }
  8162. TEST(SSLClientServerTest, ClientCertMissing) {
  8163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8164. CLIENT_CA_CERT_DIR);
  8165. ASSERT_TRUE(svr.is_valid());
  8166. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8168. auto se = detail::scope_exit([&] {
  8169. svr.stop();
  8170. t.join();
  8171. ASSERT_FALSE(svr.is_running());
  8172. });
  8173. svr.wait_until_ready();
  8174. SSLClient cli(HOST, PORT);
  8175. cli.set_connection_timeout(30);
  8176. auto res = cli.Get("/test");
  8177. ASSERT_TRUE(!res);
  8178. // When client cert is missing and server requires it, connection fails
  8179. // Error type depends on backend implementation
  8180. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8181. res.error() == Error::SSLConnection);
  8182. // Verify backend error is captured
  8183. // Note: This test may have different error codes depending on the exact
  8184. // verification failure
  8185. EXPECT_NE(0UL, res.ssl_backend_error());
  8186. }
  8187. TEST(SSLClientServerTest, TrustDirOptional) {
  8188. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8189. ASSERT_TRUE(svr.is_valid());
  8190. svr.Get("/test", [&](const Request &, Response &res) {
  8191. res.set_content("test", "text/plain");
  8192. });
  8193. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8194. auto se = detail::scope_exit([&] {
  8195. svr.stop();
  8196. t.join();
  8197. ASSERT_FALSE(svr.is_running());
  8198. });
  8199. svr.wait_until_ready();
  8200. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8201. cli.enable_server_certificate_verification(false);
  8202. cli.set_connection_timeout(30);
  8203. auto res = cli.Get("/test");
  8204. ASSERT_TRUE(res);
  8205. ASSERT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8208. class NoListenSSLServer : public SSLServer {
  8209. public:
  8210. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8211. const char *client_ca_cert_file_path,
  8212. const char *client_ca_cert_dir_path = nullptr)
  8213. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8214. client_ca_cert_dir_path),
  8215. stop_(false) {}
  8216. std::atomic_bool stop_;
  8217. private:
  8218. bool process_and_close_socket(socket_t /*sock*/) override {
  8219. // Don't create SSL context
  8220. while (!stop_.load()) {
  8221. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8222. }
  8223. return true;
  8224. }
  8225. };
  8226. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8227. CLIENT_CA_CERT_FILE);
  8228. ASSERT_TRUE(svr.is_valid());
  8229. svr.Get("/test", [&](const Request &, Response &res) {
  8230. res.set_content("test", "text/plain");
  8231. });
  8232. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8233. auto se = detail::scope_exit([&] {
  8234. svr.stop_ = true;
  8235. svr.stop();
  8236. t.join();
  8237. ASSERT_FALSE(svr.is_running());
  8238. });
  8239. svr.wait_until_ready();
  8240. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8241. cli.enable_server_certificate_verification(false);
  8242. cli.set_connection_timeout(1);
  8243. auto res = cli.Get("/test");
  8244. ASSERT_TRUE(!res);
  8245. EXPECT_EQ(Error::SSLConnection, res.error());
  8246. // Timeout results in WantRead error code (maps to backend-specific value)
  8247. EXPECT_NE(0, res.ssl_error());
  8248. }
  8249. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8250. // Test SSLServer with client certificate verification using the standard
  8251. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8253. CLIENT_CA_CERT_DIR);
  8254. ASSERT_TRUE(svr.is_valid());
  8255. svr.Get("/test", [&](const Request &req, Response &res) {
  8256. res.set_content("test", "text/plain");
  8257. auto cert = req.peer_cert();
  8258. ASSERT_TRUE(static_cast<bool>(cert));
  8259. auto common_name = cert.subject_cn();
  8260. EXPECT_EQ("Common Name", common_name);
  8261. });
  8262. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8263. auto se = detail::scope_exit([&] {
  8264. svr.stop();
  8265. t.join();
  8266. ASSERT_FALSE(svr.is_running());
  8267. });
  8268. svr.wait_until_ready();
  8269. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8270. cli.enable_server_certificate_verification(false);
  8271. cli.set_connection_timeout(30);
  8272. auto res = cli.Get("/test");
  8273. ASSERT_TRUE(res);
  8274. ASSERT_EQ(StatusCode::OK_200, res->status);
  8275. }
  8276. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8277. // Verifies that wildcard matching and exact matching work consistently
  8278. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8279. using namespace httplib::tls;
  8280. // We need a running server to test against
  8281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8282. ASSERT_TRUE(svr.is_valid());
  8283. svr.Get("/test", [](const Request &, Response &res) {
  8284. res.set_content("ok", "text/plain");
  8285. });
  8286. thread t([&]() { svr.listen(HOST, PORT); });
  8287. auto se = detail::scope_exit([&] {
  8288. svr.stop();
  8289. t.join();
  8290. });
  8291. svr.wait_until_ready();
  8292. bool verify_callback_called = false;
  8293. bool verify_result_wrong = false;
  8294. SSLClient cli(HOST, PORT);
  8295. cli.enable_server_certificate_verification(true);
  8296. cli.set_ca_cert_path(CA_CERT_FILE);
  8297. cli.set_connection_timeout(5);
  8298. // Note: Test certificate has CN="Common Name", not "localhost"
  8299. bool verify_result_cn = false;
  8300. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8301. verify_callback_called = true;
  8302. if (!ctx.cert) return false;
  8303. // Test 1: "Common Name" should match (our test server cert CN)
  8304. verify_result_cn = ctx.check_hostname("Common Name");
  8305. // Test 2: wrong hostname should not match
  8306. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8307. return true; // Accept for the purpose of this test
  8308. });
  8309. auto res = cli.Get("/test");
  8310. // The request may succeed or fail depending on cert configuration
  8311. // but the callback should have been called
  8312. ASSERT_TRUE(verify_callback_called)
  8313. << "Verify callback should have been called";
  8314. // CN="Common Name" should match our test certificate
  8315. EXPECT_TRUE(verify_result_cn)
  8316. << "verify_hostname should match 'Common Name' (certificate CN)";
  8317. // Wrong hostname should not match
  8318. EXPECT_FALSE(verify_result_wrong)
  8319. << "verify_hostname should not match 'wronghost.example.com'";
  8320. }
  8321. #endif
  8322. // mbedTLS-specific callback constructor test
  8323. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8324. #ifdef CPPHTTPLIB_SSL_ENABLED
  8325. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8326. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8327. ASSERT_TRUE(svr.is_valid());
  8328. // Set up a handler to verify client certificate is present
  8329. bool client_cert_verified = false;
  8330. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8331. // Verify that client certificate was provided
  8332. client_cert_verified = true;
  8333. res.set_content("success", "text/plain");
  8334. });
  8335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8336. auto se = detail::scope_exit([&] {
  8337. svr.stop();
  8338. t.join();
  8339. ASSERT_FALSE(svr.is_running());
  8340. });
  8341. svr.wait_until_ready();
  8342. // Client with certificate
  8343. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8344. cli.enable_server_certificate_verification(false);
  8345. cli.set_connection_timeout(30);
  8346. auto res = cli.Get("/test");
  8347. ASSERT_TRUE(res);
  8348. ASSERT_EQ(StatusCode::OK_200, res->status);
  8349. ASSERT_TRUE(client_cert_verified);
  8350. EXPECT_EQ("success", res->body);
  8351. }
  8352. #endif
  8353. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8354. // backends
  8355. #ifdef CPPHTTPLIB_SSL_ENABLED
  8356. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8357. using namespace httplib::tls;
  8358. // Test that when client CA cert file is provided,
  8359. // the server properly requests and validates client certificates
  8360. // Create a server with client authentication
  8361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8362. ASSERT_TRUE(svr.is_valid());
  8363. bool handler_called = false;
  8364. svr.Get("/test", [&](const Request &req, Response &res) {
  8365. handler_called = true;
  8366. // Verify that a client certificate was provided
  8367. auto cert = req.peer_cert();
  8368. ASSERT_TRUE(static_cast<bool>(cert));
  8369. // Get the issuer name
  8370. std::string issuer_str = cert.issuer_name();
  8371. ASSERT_FALSE(issuer_str.empty());
  8372. // The client certificate should be issued by our test CA
  8373. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8374. res.set_content("authenticated", "text/plain");
  8375. });
  8376. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8377. auto se = detail::scope_exit([&] {
  8378. svr.stop();
  8379. t.join();
  8380. ASSERT_FALSE(svr.is_running());
  8381. });
  8382. svr.wait_until_ready();
  8383. // Connect with a client certificate issued by the CA
  8384. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8385. cli.enable_server_certificate_verification(false);
  8386. cli.set_connection_timeout(30);
  8387. auto res = cli.Get("/test");
  8388. ASSERT_TRUE(res);
  8389. ASSERT_EQ(StatusCode::OK_200, res->status);
  8390. ASSERT_TRUE(handler_called);
  8391. EXPECT_EQ("authenticated", res->body);
  8392. }
  8393. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8394. using namespace httplib::tls;
  8395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8396. ASSERT_TRUE(svr.is_valid());
  8397. svr.Get("/test", [](const Request &, Response &res) {
  8398. res.set_content("ok", "text/plain");
  8399. });
  8400. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8401. auto se = detail::scope_exit([&] {
  8402. svr.stop();
  8403. t.join();
  8404. });
  8405. svr.wait_until_ready();
  8406. SSLClient cli(HOST, PORT);
  8407. cli.enable_server_certificate_verification(false);
  8408. cli.set_connection_timeout(30);
  8409. bool cert_checked = false;
  8410. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8411. if (ctx.cert) {
  8412. auto sans = ctx.sans();
  8413. // Test certificate may or may not have SANs - just verify the API
  8414. // works If SANs exist, verify the types are valid
  8415. for (const auto &san : sans) {
  8416. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8417. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8418. san.type == SanType::OTHER);
  8419. EXPECT_FALSE(san.value.empty());
  8420. }
  8421. cert_checked = true;
  8422. }
  8423. return true;
  8424. });
  8425. auto res = cli.Get("/test");
  8426. ASSERT_TRUE(res);
  8427. EXPECT_TRUE(cert_checked);
  8428. }
  8429. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8430. using namespace httplib::tls;
  8431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8432. ASSERT_TRUE(svr.is_valid());
  8433. svr.Get("/test", [](const Request &, Response &res) {
  8434. res.set_content("ok", "text/plain");
  8435. });
  8436. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8437. auto se = detail::scope_exit([&] {
  8438. svr.stop();
  8439. t.join();
  8440. });
  8441. svr.wait_until_ready();
  8442. SSLClient cli(HOST, PORT);
  8443. cli.enable_server_certificate_verification(false);
  8444. cli.set_connection_timeout(30);
  8445. bool validity_checked = false;
  8446. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8447. if (ctx.cert) {
  8448. time_t not_before = 0, not_after = 0;
  8449. bool result = ctx.validity(not_before, not_after);
  8450. EXPECT_TRUE(result);
  8451. // Verify that not_before < now < not_after for a valid cert
  8452. time_t now = time(nullptr);
  8453. EXPECT_LT(not_before, now);
  8454. EXPECT_GT(not_after, now);
  8455. validity_checked = true;
  8456. }
  8457. return true;
  8458. });
  8459. auto res = cli.Get("/test");
  8460. ASSERT_TRUE(res);
  8461. EXPECT_TRUE(validity_checked);
  8462. }
  8463. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8464. using namespace httplib::tls;
  8465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8466. ASSERT_TRUE(svr.is_valid());
  8467. svr.Get("/test", [](const Request &, Response &res) {
  8468. res.set_content("ok", "text/plain");
  8469. });
  8470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8471. auto se = detail::scope_exit([&] {
  8472. svr.stop();
  8473. t.join();
  8474. });
  8475. svr.wait_until_ready();
  8476. SSLClient cli(HOST, PORT);
  8477. cli.enable_server_certificate_verification(false);
  8478. cli.set_connection_timeout(30);
  8479. bool serial_checked = false;
  8480. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8481. if (ctx.cert) {
  8482. std::string serial = ctx.serial();
  8483. EXPECT_FALSE(serial.empty());
  8484. // Serial should be a hex string
  8485. for (char c : serial) {
  8486. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8487. (c >= 'a' && c <= 'f'));
  8488. }
  8489. serial_checked = true;
  8490. }
  8491. return true;
  8492. });
  8493. auto res = cli.Get("/test");
  8494. ASSERT_TRUE(res);
  8495. EXPECT_TRUE(serial_checked);
  8496. }
  8497. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8498. // Test 1: Valid CA file - no error should be recorded
  8499. {
  8500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8501. CLIENT_CA_CERT_FILE);
  8502. ASSERT_TRUE(svr.is_valid());
  8503. // With valid setup, last_ssl_error should be 0
  8504. EXPECT_EQ(0, svr.ssl_last_error());
  8505. }
  8506. // Test 2: Invalid CA file content
  8507. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8508. {
  8509. // Create a temporary file with completely invalid content
  8510. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8511. {
  8512. std::ofstream ofs(temp_invalid_ca);
  8513. ofs << "This is not a certificate file at all\n";
  8514. ofs << "Just plain text content\n";
  8515. }
  8516. // Create server with invalid CA file
  8517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8518. // Clean up temporary file
  8519. std::remove(temp_invalid_ca);
  8520. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8521. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8522. // Note: SSL_CTX_load_verify_locations typically fails first,
  8523. // but our error handling code path is still exercised
  8524. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8525. }
  8526. }
  8527. TEST(VerifyCallbackTest, VerifyContextFields) {
  8528. using namespace httplib::tls;
  8529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8530. ASSERT_TRUE(svr.is_valid());
  8531. svr.Get("/test", [](const Request &, Response &res) {
  8532. res.set_content("ok", "text/plain");
  8533. });
  8534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8535. auto se = detail::scope_exit([&] {
  8536. svr.stop();
  8537. t.join();
  8538. });
  8539. svr.wait_until_ready();
  8540. SSLClient cli(HOST, PORT);
  8541. cli.enable_server_certificate_verification(false);
  8542. cli.set_connection_timeout(30);
  8543. int callback_count = 0;
  8544. bool saw_leaf_cert = false;
  8545. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8546. if (ctx.cert) {
  8547. callback_count++;
  8548. // We should see at least one certificate (the leaf)
  8549. std::string cn = ctx.subject_cn();
  8550. if (!cn.empty()) { saw_leaf_cert = true; }
  8551. // Verify context fields are populated
  8552. EXPECT_NE(ctx.session, nullptr);
  8553. EXPECT_GE(ctx.depth, 0);
  8554. }
  8555. return true;
  8556. });
  8557. auto res = cli.Get("/test");
  8558. ASSERT_TRUE(res);
  8559. EXPECT_GT(callback_count, 0);
  8560. EXPECT_TRUE(saw_leaf_cert);
  8561. }
  8562. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8563. using httplib::tls::TlsError;
  8564. // Test that verify_error_to_string returns empty for success
  8565. std::string success_str = TlsError::verify_error_to_string(0);
  8566. EXPECT_TRUE(success_str.empty());
  8567. // Test that verify_error_to_string returns non-empty for error codes
  8568. // Using a common error code (certificate expired)
  8569. std::string error_str =
  8570. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8571. EXPECT_FALSE(error_str.empty());
  8572. }
  8573. TEST(SessionVerifierTest, CertificateAccepted) {
  8574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8575. ASSERT_TRUE(svr.is_valid());
  8576. svr.Get("/test", [](const Request &, Response &res) {
  8577. res.set_content("ok", "text/plain");
  8578. });
  8579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8580. auto se = detail::scope_exit([&] {
  8581. svr.stop();
  8582. t.join();
  8583. });
  8584. svr.wait_until_ready();
  8585. SSLClient cli(HOST, PORT);
  8586. cli.enable_server_certificate_verification(false);
  8587. cli.set_connection_timeout(30);
  8588. bool callback_called = false;
  8589. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8590. EXPECT_NE(session, nullptr);
  8591. callback_called = true;
  8592. return SSLVerifierResponse::CertificateAccepted;
  8593. });
  8594. auto res = cli.Get("/test");
  8595. ASSERT_TRUE(res);
  8596. EXPECT_EQ(200, res->status);
  8597. EXPECT_TRUE(callback_called);
  8598. }
  8599. TEST(SessionVerifierTest, CertificateRejected) {
  8600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8601. ASSERT_TRUE(svr.is_valid());
  8602. svr.Get("/test", [](const Request &, Response &res) {
  8603. res.set_content("ok", "text/plain");
  8604. });
  8605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8606. auto se = detail::scope_exit([&] {
  8607. svr.stop();
  8608. t.join();
  8609. });
  8610. svr.wait_until_ready();
  8611. SSLClient cli(HOST, PORT);
  8612. cli.enable_server_certificate_verification(false);
  8613. cli.set_connection_timeout(30);
  8614. bool callback_called = false;
  8615. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8616. EXPECT_NE(session, nullptr);
  8617. callback_called = true;
  8618. return SSLVerifierResponse::CertificateRejected;
  8619. });
  8620. auto res = cli.Get("/test");
  8621. EXPECT_FALSE(res);
  8622. EXPECT_TRUE(callback_called);
  8623. }
  8624. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8626. ASSERT_TRUE(svr.is_valid());
  8627. svr.Get("/test", [](const Request &, Response &res) {
  8628. res.set_content("ok", "text/plain");
  8629. });
  8630. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8631. auto se = detail::scope_exit([&] {
  8632. svr.stop();
  8633. t.join();
  8634. });
  8635. svr.wait_until_ready();
  8636. // NoDecisionMade with verification disabled should succeed (no default check)
  8637. SSLClient cli(HOST, PORT);
  8638. cli.enable_server_certificate_verification(false);
  8639. cli.set_connection_timeout(30);
  8640. bool callback_called = false;
  8641. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8642. EXPECT_NE(session, nullptr);
  8643. callback_called = true;
  8644. return SSLVerifierResponse::NoDecisionMade;
  8645. });
  8646. auto res = cli.Get("/test");
  8647. ASSERT_TRUE(res);
  8648. EXPECT_EQ(200, res->status);
  8649. EXPECT_TRUE(callback_called);
  8650. }
  8651. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8653. ASSERT_TRUE(svr.is_valid());
  8654. svr.Get("/test", [](const Request &, Response &res) {
  8655. res.set_content("ok", "text/plain");
  8656. });
  8657. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8658. auto se = detail::scope_exit([&] {
  8659. svr.stop();
  8660. t.join();
  8661. });
  8662. svr.wait_until_ready();
  8663. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8664. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8665. // so we only check that the request fails, not whether the callback was
  8666. // called.
  8667. SSLClient cli(HOST, PORT);
  8668. cli.enable_server_certificate_verification(true);
  8669. cli.set_connection_timeout(30);
  8670. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8671. EXPECT_NE(session, nullptr);
  8672. return SSLVerifierResponse::NoDecisionMade;
  8673. });
  8674. auto res = cli.Get("/test");
  8675. EXPECT_FALSE(res);
  8676. }
  8677. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8678. // Test SSL server using PemMemory constructor with client CA certificates
  8679. // Read PEM files
  8680. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8681. read_file(SERVER_CERT_FILE, server_cert_pem);
  8682. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8683. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8684. // Create SSLServer with PemMemory constructor including client CA
  8685. SSLServer::PemMemory server_pem = {
  8686. server_cert_pem.c_str(),
  8687. server_cert_pem.size(),
  8688. server_key_pem.c_str(),
  8689. server_key_pem.size(),
  8690. client_ca_pem.c_str(),
  8691. client_ca_pem.size(),
  8692. nullptr // no password for server key
  8693. };
  8694. SSLServer svr(server_pem);
  8695. ASSERT_TRUE(svr.is_valid());
  8696. // No SSL error should be recorded for valid setup
  8697. EXPECT_EQ(0, svr.ssl_last_error());
  8698. // Set up server endpoints
  8699. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8700. res.set_content("ok", "text/plain");
  8701. });
  8702. // Start server in a thread
  8703. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8704. svr.wait_until_ready();
  8705. // Connect with client certificate (using constructor with paths)
  8706. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8707. cli.enable_server_certificate_verification(false);
  8708. auto res = cli.Get("/test-pem-ca");
  8709. ASSERT_TRUE(res);
  8710. EXPECT_EQ(200, res->status);
  8711. EXPECT_EQ("ok", res->body);
  8712. svr.stop();
  8713. server_thread.join();
  8714. }
  8715. #endif
  8716. #ifdef _WIN32
  8717. TEST(CleanupTest, WSACleanup) {
  8718. int ret = WSACleanup();
  8719. ASSERT_EQ(0, ret);
  8720. }
  8721. #endif
  8722. #ifndef CPPHTTPLIB_SSL_ENABLED
  8723. TEST(NoSSLSupport, SimpleInterface) {
  8724. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8725. }
  8726. #endif
  8727. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8728. TEST(InvalidScheme, SimpleInterface) {
  8729. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8730. }
  8731. #endif
  8732. TEST(NoScheme, SimpleInterface) {
  8733. Client cli("yahoo.com:80");
  8734. ASSERT_TRUE(cli.is_valid());
  8735. }
  8736. TEST(SendAPI, SimpleInterface_Online) {
  8737. Client cli("http://yahoo.com");
  8738. Request req;
  8739. req.method = "GET";
  8740. req.path = "/";
  8741. auto res = cli.send(req);
  8742. ASSERT_TRUE(res);
  8743. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8744. }
  8745. TEST(SendAPI, WithParamsInRequest) {
  8746. Server svr;
  8747. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8748. EXPECT_TRUE(req.has_param("test"));
  8749. EXPECT_EQ("test_value", req.get_param_value("test"));
  8750. });
  8751. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8752. auto se = detail::scope_exit([&] {
  8753. svr.stop();
  8754. t.join();
  8755. ASSERT_FALSE(svr.is_running());
  8756. });
  8757. svr.wait_until_ready();
  8758. Client cli(HOST, PORT);
  8759. {
  8760. Request req;
  8761. req.method = "GET";
  8762. req.path = "/";
  8763. req.params.emplace("test", "test_value");
  8764. auto res = cli.send(req);
  8765. ASSERT_TRUE(res);
  8766. }
  8767. {
  8768. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8769. ASSERT_TRUE(res);
  8770. }
  8771. }
  8772. TEST(ClientImplMethods, GetSocketTest) {
  8773. httplib::Server svr;
  8774. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8775. res.status = StatusCode::OK_200;
  8776. });
  8777. auto port = svr.bind_to_any_port("127.0.0.1");
  8778. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8779. auto se = detail::scope_exit([&] {
  8780. svr.stop();
  8781. thread.join();
  8782. ASSERT_FALSE(svr.is_running());
  8783. });
  8784. svr.wait_until_ready();
  8785. {
  8786. httplib::Client cli("127.0.0.1", port);
  8787. cli.set_keep_alive(true);
  8788. // Use the behavior of cpp-httplib of opening the connection
  8789. // only when the first request happens. If that changes,
  8790. // this test would be obsolete.
  8791. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8792. // This also implicitly tests the server. But other tests would fail much
  8793. // earlier than this one to be considered.
  8794. auto res = cli.Get("/");
  8795. ASSERT_TRUE(res);
  8796. EXPECT_EQ(StatusCode::OK_200, res->status);
  8797. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8798. }
  8799. }
  8800. // Disabled due to out-of-memory problem on GitHub Actions
  8801. #ifdef _WIN64
  8802. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8803. // allocate content size larger than 2GB in memory
  8804. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8805. char *content = (char *)malloc(content_size);
  8806. ASSERT_TRUE(content);
  8807. Server svr;
  8808. svr.Get("/foo",
  8809. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8810. res.set_content(content, content_size, "application/octet-stream");
  8811. });
  8812. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8813. auto se = detail::scope_exit([&] {
  8814. svr.stop();
  8815. listen_thread.join();
  8816. if (content) free(content);
  8817. ASSERT_FALSE(svr.is_running());
  8818. });
  8819. svr.wait_until_ready();
  8820. Client cli(HOST, PORT);
  8821. auto res = cli.Get("/foo");
  8822. ASSERT_TRUE(res);
  8823. EXPECT_EQ(StatusCode::OK_200, res->status);
  8824. EXPECT_EQ(content_size, res->body.length());
  8825. }
  8826. #endif
  8827. #ifdef CPPHTTPLIB_SSL_ENABLED
  8828. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8829. Client cli("http://yahoo.com");
  8830. auto res = cli.Get("/");
  8831. ASSERT_TRUE(res);
  8832. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8833. cli.set_follow_location(true);
  8834. res = cli.Get("/");
  8835. ASSERT_TRUE(res);
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8838. }
  8839. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8840. Client cli("https://yahoo.com");
  8841. auto res = cli.Get("/");
  8842. ASSERT_TRUE(res);
  8843. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8844. cli.set_follow_location(true);
  8845. res = cli.Get("/");
  8846. ASSERT_TRUE(res);
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8849. }
  8850. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8851. Client cli("https://yahoo.com");
  8852. auto res = cli.Get("/");
  8853. ASSERT_TRUE(res);
  8854. ASSERT_FALSE(!res);
  8855. ASSERT_TRUE(res);
  8856. ASSERT_FALSE(res == nullptr);
  8857. ASSERT_TRUE(res != nullptr);
  8858. EXPECT_EQ(Error::Success, res.error());
  8859. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8860. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8861. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8862. cli.set_follow_location(true);
  8863. res = cli.Get("/");
  8864. ASSERT_TRUE(res);
  8865. EXPECT_EQ(Error::Success, res.error());
  8866. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8867. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8868. EXPECT_EQ(StatusCode::OK_200, res->status);
  8869. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8870. }
  8871. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8872. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8873. Client cli("https://cdnjs.cloudflare.com");
  8874. auto res =
  8875. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8876. ASSERT_TRUE(res);
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. EXPECT_EQ(287630U, res->body.size());
  8879. EXPECT_EQ("application/javascript; charset=utf-8",
  8880. res->get_header_value("Content-Type"));
  8881. }
  8882. #endif
  8883. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8884. #undef REDIR_HOST // Silence compiler warning
  8885. #define REDIR_HOST "https://httpbingo.org"
  8886. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8887. Client cli(REDIR_HOST);
  8888. cli.set_follow_location(true);
  8889. auto res =
  8890. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8891. ASSERT_TRUE(res);
  8892. EXPECT_EQ(StatusCode::OK_200, res->status);
  8893. }
  8894. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8895. Client cli(REDIR_HOST);
  8896. cli.set_follow_location(true);
  8897. Params params;
  8898. params.emplace("url", "http://example.com");
  8899. params.emplace("status_code", "302");
  8900. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8901. ASSERT_TRUE(res);
  8902. EXPECT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8905. Client cli(REDIR_HOST);
  8906. cli.set_follow_location(true);
  8907. Params params;
  8908. params.emplace("url", "http://example.com");
  8909. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8910. ASSERT_TRUE(res);
  8911. EXPECT_EQ(StatusCode::OK_200, res->status);
  8912. }
  8913. TEST(HttpToHttpsRedirectTest, CertFile) {
  8914. auto ssl_port = PORT + 1;
  8915. Server svr;
  8916. ASSERT_TRUE(svr.is_valid());
  8917. svr.Get("/index", [&](const Request &, Response &res) {
  8918. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  8919. "/index");
  8920. svr.stop();
  8921. });
  8922. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8923. ASSERT_TRUE(ssl_svr.is_valid());
  8924. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8925. res.set_content("test", "text/plain");
  8926. ssl_svr.stop();
  8927. });
  8928. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8929. thread t2 =
  8930. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  8931. auto se = detail::scope_exit([&] {
  8932. t2.join();
  8933. t.join();
  8934. ASSERT_FALSE(svr.is_running());
  8935. });
  8936. svr.wait_until_ready();
  8937. ssl_svr.wait_until_ready();
  8938. Client cli("127.0.0.1", PORT);
  8939. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8940. cli.enable_server_certificate_verification(true);
  8941. cli.set_follow_location(true);
  8942. cli.set_connection_timeout(30);
  8943. auto res = cli.Get("/index");
  8944. ASSERT_TRUE(res);
  8945. ASSERT_EQ(StatusCode::OK_200, res->status);
  8946. }
  8947. TEST(SSLClientRedirectTest, CertFile) {
  8948. auto ssl_port = PORT + 1;
  8949. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8950. ASSERT_TRUE(ssl_svr1.is_valid());
  8951. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8952. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  8953. "/index");
  8954. ssl_svr1.stop();
  8955. });
  8956. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8957. ASSERT_TRUE(ssl_svr2.is_valid());
  8958. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8959. res.set_content("test", "text/plain");
  8960. ssl_svr2.stop();
  8961. });
  8962. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8963. thread t2 =
  8964. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  8965. auto se = detail::scope_exit([&] {
  8966. t2.join();
  8967. t.join();
  8968. ASSERT_FALSE(ssl_svr1.is_running());
  8969. });
  8970. ssl_svr1.wait_until_ready();
  8971. ssl_svr2.wait_until_ready();
  8972. SSLClient cli("127.0.0.1", PORT);
  8973. std::string cert;
  8974. read_file(SERVER_CERT2_FILE, cert);
  8975. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8976. cli.enable_server_certificate_verification(true);
  8977. cli.set_follow_location(true);
  8978. cli.set_connection_timeout(30);
  8979. auto res = cli.Get("/index");
  8980. ASSERT_TRUE(res);
  8981. ASSERT_EQ(StatusCode::OK_200, res->status);
  8982. }
  8983. #endif
  8984. #ifdef CPPHTTPLIB_SSL_ENABLED
  8985. // Test that set_ca_cert_store() skips system certs (consistent with
  8986. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8987. // should be trusted - system certs should NOT be loaded.
  8988. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8989. // Load a specific cert that is NOT a system CA cert
  8990. std::string cert;
  8991. read_file(SERVER_CERT2_FILE, cert);
  8992. SSLClient cli("google.com");
  8993. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8994. cli.enable_server_certificate_verification(true);
  8995. // This should FAIL because:
  8996. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8997. // 2. System certs should NOT be loaded when custom store is set
  8998. // If system certs WERE loaded, this would succeed
  8999. auto res = cli.Get("/");
  9000. ASSERT_FALSE(res);
  9001. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9002. }
  9003. TEST(MultipartFormDataTest, LargeData) {
  9004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9005. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9006. const ContentReader &content_reader) {
  9007. if (req.is_multipart_form_data()) {
  9008. std::vector<FormData> items;
  9009. content_reader(
  9010. [&](const FormData &file) {
  9011. items.push_back(file);
  9012. return true;
  9013. },
  9014. [&](const char *data, size_t data_length) {
  9015. items.back().content.append(data, data_length);
  9016. return true;
  9017. });
  9018. EXPECT_TRUE(std::string(items[0].name) == "document");
  9019. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9020. EXPECT_TRUE(items[0].filename == "2MB_data");
  9021. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9022. EXPECT_TRUE(items[1].name == "hello");
  9023. EXPECT_TRUE(items[1].content == "world");
  9024. EXPECT_TRUE(items[1].filename == "");
  9025. EXPECT_TRUE(items[1].content_type == "");
  9026. } else {
  9027. std::string body;
  9028. content_reader([&](const char *data, size_t data_length) {
  9029. body.append(data, data_length);
  9030. return true;
  9031. });
  9032. }
  9033. });
  9034. auto port = svr.bind_to_any_port(HOST);
  9035. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9036. auto se = detail::scope_exit([&] {
  9037. svr.stop();
  9038. t.join();
  9039. ASSERT_FALSE(svr.is_running());
  9040. });
  9041. svr.wait_until_ready();
  9042. {
  9043. std::string data(1024 * 1024 * 2, '.');
  9044. std::stringstream buffer;
  9045. buffer << data;
  9046. SSLClient cli(HOST, port);
  9047. cli.enable_server_certificate_verification(false);
  9048. UploadFormDataItems items{
  9049. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9050. {"hello", "world", "", ""},
  9051. };
  9052. auto res = cli.Post("/post", items);
  9053. ASSERT_TRUE(res);
  9054. ASSERT_EQ(StatusCode::OK_200, res->status);
  9055. }
  9056. }
  9057. TEST(MultipartFormDataTest, DataProviderItems) {
  9058. std::random_device seed_gen;
  9059. std::mt19937 random(seed_gen());
  9060. std::string rand1;
  9061. rand1.resize(1000);
  9062. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9063. std::string rand2;
  9064. rand2.resize(3000);
  9065. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9067. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9068. const ContentReader &content_reader) {
  9069. ASSERT_FALSE(req.is_multipart_form_data());
  9070. std::string body;
  9071. content_reader([&](const char *data, size_t data_length) {
  9072. body.append(data, data_length);
  9073. return true;
  9074. });
  9075. EXPECT_EQ(body, "");
  9076. });
  9077. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9078. const ContentReader &content_reader) {
  9079. ASSERT_TRUE(req.is_multipart_form_data());
  9080. std::vector<FormData> items;
  9081. content_reader(
  9082. [&](const FormData &file) {
  9083. items.push_back(file);
  9084. return true;
  9085. },
  9086. [&](const char *data, size_t data_length) {
  9087. items.back().content.append(data, data_length);
  9088. return true;
  9089. });
  9090. ASSERT_TRUE(items.size() == 2);
  9091. EXPECT_EQ(std::string(items[0].name), "name1");
  9092. EXPECT_EQ(items[0].content, "Testing123");
  9093. EXPECT_EQ(items[0].filename, "filename1");
  9094. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9095. EXPECT_EQ(items[1].name, "name2");
  9096. EXPECT_EQ(items[1].content, "Testing456");
  9097. EXPECT_EQ(items[1].filename, "");
  9098. EXPECT_EQ(items[1].content_type, "");
  9099. });
  9100. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9101. const ContentReader &content_reader) {
  9102. ASSERT_TRUE(req.is_multipart_form_data());
  9103. std::vector<FormData> items;
  9104. content_reader(
  9105. [&](const FormData &file) {
  9106. items.push_back(file);
  9107. return true;
  9108. },
  9109. [&](const char *data, size_t data_length) {
  9110. items.back().content.append(data, data_length);
  9111. return true;
  9112. });
  9113. ASSERT_TRUE(items.size() == 2);
  9114. EXPECT_EQ(items[0].name, "name3");
  9115. EXPECT_EQ(items[0].content, rand1);
  9116. EXPECT_EQ(items[0].filename, "filename3");
  9117. EXPECT_EQ(items[0].content_type, "");
  9118. EXPECT_EQ(items[1].name, "name4");
  9119. EXPECT_EQ(items[1].content, rand2);
  9120. EXPECT_EQ(items[1].filename, "filename4");
  9121. EXPECT_EQ(items[1].content_type, "");
  9122. });
  9123. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9124. const ContentReader &content_reader) {
  9125. ASSERT_TRUE(req.is_multipart_form_data());
  9126. std::vector<FormData> items;
  9127. content_reader(
  9128. [&](const FormData &file) {
  9129. items.push_back(file);
  9130. return true;
  9131. },
  9132. [&](const char *data, size_t data_length) {
  9133. items.back().content.append(data, data_length);
  9134. return true;
  9135. });
  9136. ASSERT_TRUE(items.size() == 4);
  9137. EXPECT_EQ(std::string(items[0].name), "name1");
  9138. EXPECT_EQ(items[0].content, "Testing123");
  9139. EXPECT_EQ(items[0].filename, "filename1");
  9140. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9141. EXPECT_EQ(items[1].name, "name2");
  9142. EXPECT_EQ(items[1].content, "Testing456");
  9143. EXPECT_EQ(items[1].filename, "");
  9144. EXPECT_EQ(items[1].content_type, "");
  9145. EXPECT_EQ(items[2].name, "name3");
  9146. EXPECT_EQ(items[2].content, rand1);
  9147. EXPECT_EQ(items[2].filename, "filename3");
  9148. EXPECT_EQ(items[2].content_type, "");
  9149. EXPECT_EQ(items[3].name, "name4");
  9150. EXPECT_EQ(items[3].content, rand2);
  9151. EXPECT_EQ(items[3].filename, "filename4");
  9152. EXPECT_EQ(items[3].content_type, "");
  9153. });
  9154. auto port = svr.bind_to_any_port("localhost");
  9155. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9156. auto se = detail::scope_exit([&] {
  9157. svr.stop();
  9158. t.join();
  9159. ASSERT_FALSE(svr.is_running());
  9160. });
  9161. svr.wait_until_ready();
  9162. {
  9163. SSLClient cli("localhost", port);
  9164. cli.enable_server_certificate_verification(false);
  9165. UploadFormDataItems items{
  9166. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9167. {"name2", "Testing456", "", ""}, // not a file
  9168. };
  9169. {
  9170. auto res = cli.Post("/post-none", {}, {}, {});
  9171. ASSERT_TRUE(res);
  9172. ASSERT_EQ(StatusCode::OK_200, res->status);
  9173. }
  9174. FormDataProviderItems providers;
  9175. {
  9176. auto res =
  9177. cli.Post("/post-items", {}, items, providers); // empty providers
  9178. ASSERT_TRUE(res);
  9179. ASSERT_EQ(StatusCode::OK_200, res->status);
  9180. }
  9181. providers.push_back({"name3",
  9182. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9183. // test the offset is given correctly at each step
  9184. if (!offset)
  9185. sink.os.write(rand1.data(), 30);
  9186. else if (offset == 30)
  9187. sink.os.write(rand1.data() + 30, 300);
  9188. else if (offset == 330)
  9189. sink.os.write(rand1.data() + 330, 670);
  9190. else if (offset == rand1.size())
  9191. sink.done();
  9192. return true;
  9193. },
  9194. "filename3",
  9195. {}});
  9196. providers.push_back({"name4",
  9197. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9198. // test the offset is given correctly at each step
  9199. if (!offset)
  9200. sink.os.write(rand2.data(), 2000);
  9201. else if (offset == 2000)
  9202. sink.os.write(rand2.data() + 2000, 1);
  9203. else if (offset == 2001)
  9204. sink.os.write(rand2.data() + 2001, 999);
  9205. else if (offset == rand2.size())
  9206. sink.done();
  9207. return true;
  9208. },
  9209. "filename4",
  9210. {}});
  9211. {
  9212. auto res = cli.Post("/post-providers", {}, {}, providers);
  9213. ASSERT_TRUE(res);
  9214. ASSERT_EQ(StatusCode::OK_200, res->status);
  9215. }
  9216. {
  9217. auto res = cli.Post("/post-both", {}, items, providers);
  9218. ASSERT_TRUE(res);
  9219. ASSERT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. }
  9222. }
  9223. TEST(MultipartFormDataTest, BadHeader) {
  9224. Server svr;
  9225. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9226. res.set_content("ok", "text/plain");
  9227. });
  9228. thread t = thread([&] { svr.listen(HOST, PORT); });
  9229. auto se = detail::scope_exit([&] {
  9230. svr.stop();
  9231. t.join();
  9232. ASSERT_FALSE(svr.is_running());
  9233. });
  9234. svr.wait_until_ready();
  9235. const std::string body =
  9236. "This is the preamble. It is to be ignored, though it\r\n"
  9237. "is a handy place for composition agents to include an\r\n"
  9238. "explanatory note to non-MIME conformant readers.\r\n"
  9239. "\r\n"
  9240. "\r\n"
  9241. "--simple boundary\r\n"
  9242. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9243. ": BAD...\r\n"
  9244. "\r\n"
  9245. "value1\r\n"
  9246. "--simple boundary\r\n"
  9247. "Content-Disposition: form-data; name=\"field2\"; "
  9248. "filename=\"example.txt\"\r\n"
  9249. "\r\n"
  9250. "value2\r\n"
  9251. "--simple boundary--\r\n"
  9252. "This is the epilogue. It is also to be ignored.\r\n";
  9253. std::string content_type =
  9254. R"(multipart/form-data; boundary="simple boundary")";
  9255. Client cli(HOST, PORT);
  9256. auto res = cli.Post("/post", body, content_type.c_str());
  9257. ASSERT_TRUE(res);
  9258. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9259. }
  9260. TEST(MultipartFormDataTest, WithPreamble) {
  9261. Server svr;
  9262. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9263. res.set_content("ok", "text/plain");
  9264. });
  9265. thread t = thread([&] { svr.listen(HOST, PORT); });
  9266. auto se = detail::scope_exit([&] {
  9267. svr.stop();
  9268. t.join();
  9269. ASSERT_FALSE(svr.is_running());
  9270. });
  9271. svr.wait_until_ready();
  9272. const std::string body =
  9273. "This is the preamble. It is to be ignored, though it\r\n"
  9274. "is a handy place for composition agents to include an\r\n"
  9275. "explanatory note to non-MIME conformant readers.\r\n"
  9276. "\r\n"
  9277. "\r\n"
  9278. "--simple boundary\r\n"
  9279. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9280. "\r\n"
  9281. "value1\r\n"
  9282. "--simple boundary\r\n"
  9283. "Content-Disposition: form-data; name=\"field2\"; "
  9284. "filename=\"example.txt\"\r\n"
  9285. "\r\n"
  9286. "value2\r\n"
  9287. "--simple boundary--\r\n"
  9288. "This is the epilogue. It is also to be ignored.\r\n";
  9289. std::string content_type =
  9290. R"(multipart/form-data; boundary="simple boundary")";
  9291. Client cli(HOST, PORT);
  9292. auto res = cli.Post("/post", body, content_type.c_str());
  9293. ASSERT_TRUE(res);
  9294. EXPECT_EQ(StatusCode::OK_200, res->status);
  9295. }
  9296. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9297. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9298. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9299. const ContentReader &content_reader) {
  9300. if (req.is_multipart_form_data()) {
  9301. std::vector<FormData> items;
  9302. content_reader(
  9303. [&](const FormData &file) {
  9304. items.push_back(file);
  9305. return true;
  9306. },
  9307. [&](const char *data, size_t data_length) {
  9308. items.back().content.append(data, data_length);
  9309. return true;
  9310. });
  9311. EXPECT_TRUE(std::string(items[0].name) == "document");
  9312. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9313. EXPECT_TRUE(items[0].filename == "2MB_data");
  9314. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9315. EXPECT_TRUE(items[1].name == "hello");
  9316. EXPECT_TRUE(items[1].content == "world");
  9317. EXPECT_TRUE(items[1].filename == "");
  9318. EXPECT_TRUE(items[1].content_type == "");
  9319. } else {
  9320. std::string body;
  9321. content_reader([&](const char *data, size_t data_length) {
  9322. body.append(data, data_length);
  9323. return true;
  9324. });
  9325. }
  9326. });
  9327. auto port = svr.bind_to_any_port("localhost");
  9328. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9329. auto se = detail::scope_exit([&] {
  9330. svr.stop();
  9331. t.join();
  9332. ASSERT_FALSE(svr.is_running());
  9333. });
  9334. svr.wait_until_ready();
  9335. {
  9336. std::string data(1024 * 1024 * 2, '.');
  9337. std::stringstream buffer;
  9338. buffer << data;
  9339. SSLClient cli("localhost", port);
  9340. cli.enable_server_certificate_verification(false);
  9341. UploadFormDataItems items{
  9342. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9343. {"hello", "world", "", ""},
  9344. };
  9345. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9346. ASSERT_TRUE(res);
  9347. ASSERT_EQ(StatusCode::OK_200, res->status);
  9348. }
  9349. }
  9350. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9351. std::string data(1024 * 1024 * 2, '&');
  9352. std::stringstream buffer;
  9353. buffer << data;
  9354. Client cli("https://localhost:8080");
  9355. UploadFormDataItems items{
  9356. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9357. {"hello", "world", "", ""},
  9358. };
  9359. for (const char &c : " \t\r\n") {
  9360. auto res =
  9361. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9362. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9363. ASSERT_FALSE(res);
  9364. }
  9365. }
  9366. TEST(MultipartFormDataTest, PutFormData) {
  9367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9368. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9369. const ContentReader &content_reader) {
  9370. if (req.is_multipart_form_data()) {
  9371. std::vector<FormData> items;
  9372. content_reader(
  9373. [&](const FormData &file) {
  9374. items.push_back(file);
  9375. return true;
  9376. },
  9377. [&](const char *data, size_t data_length) {
  9378. items.back().content.append(data, data_length);
  9379. return true;
  9380. });
  9381. EXPECT_TRUE(std::string(items[0].name) == "document");
  9382. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9383. EXPECT_TRUE(items[0].filename == "2MB_data");
  9384. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9385. EXPECT_TRUE(items[1].name == "hello");
  9386. EXPECT_TRUE(items[1].content == "world");
  9387. EXPECT_TRUE(items[1].filename == "");
  9388. EXPECT_TRUE(items[1].content_type == "");
  9389. } else {
  9390. std::string body;
  9391. content_reader([&](const char *data, size_t data_length) {
  9392. body.append(data, data_length);
  9393. return true;
  9394. });
  9395. }
  9396. });
  9397. auto port = svr.bind_to_any_port("localhost");
  9398. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. t.join();
  9402. ASSERT_FALSE(svr.is_running());
  9403. });
  9404. svr.wait_until_ready();
  9405. {
  9406. std::string data(1024 * 1024 * 2, '&');
  9407. std::stringstream buffer;
  9408. buffer << data;
  9409. SSLClient cli("localhost", port);
  9410. cli.enable_server_certificate_verification(false);
  9411. UploadFormDataItems items{
  9412. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9413. {"hello", "world", "", ""},
  9414. };
  9415. auto res = cli.Put("/put", items);
  9416. ASSERT_TRUE(res);
  9417. ASSERT_EQ(StatusCode::OK_200, res->status);
  9418. }
  9419. }
  9420. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9422. svr.Put("/put_customboundary",
  9423. [&](const Request &req, const Response & /*res*/,
  9424. const ContentReader &content_reader) {
  9425. if (req.is_multipart_form_data()) {
  9426. std::vector<FormData> items;
  9427. content_reader(
  9428. [&](const FormData &file) {
  9429. items.push_back(file);
  9430. return true;
  9431. },
  9432. [&](const char *data, size_t data_length) {
  9433. items.back().content.append(data, data_length);
  9434. return true;
  9435. });
  9436. EXPECT_TRUE(std::string(items[0].name) == "document");
  9437. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9438. EXPECT_TRUE(items[0].filename == "2MB_data");
  9439. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9440. EXPECT_TRUE(items[1].name == "hello");
  9441. EXPECT_TRUE(items[1].content == "world");
  9442. EXPECT_TRUE(items[1].filename == "");
  9443. EXPECT_TRUE(items[1].content_type == "");
  9444. } else {
  9445. std::string body;
  9446. content_reader([&](const char *data, size_t data_length) {
  9447. body.append(data, data_length);
  9448. return true;
  9449. });
  9450. }
  9451. });
  9452. auto port = svr.bind_to_any_port("localhost");
  9453. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9454. auto se = detail::scope_exit([&] {
  9455. svr.stop();
  9456. t.join();
  9457. ASSERT_FALSE(svr.is_running());
  9458. });
  9459. svr.wait_until_ready();
  9460. {
  9461. std::string data(1024 * 1024 * 2, '&');
  9462. std::stringstream buffer;
  9463. buffer << data;
  9464. SSLClient cli("localhost", port);
  9465. cli.enable_server_certificate_verification(false);
  9466. UploadFormDataItems items{
  9467. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9468. {"hello", "world", "", ""},
  9469. };
  9470. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9471. ASSERT_TRUE(res);
  9472. ASSERT_EQ(StatusCode::OK_200, res->status);
  9473. }
  9474. }
  9475. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9476. std::string data(1024 * 1024 * 2, '&');
  9477. std::stringstream buffer;
  9478. buffer << data;
  9479. Client cli("https://localhost:8080");
  9480. cli.enable_server_certificate_verification(false);
  9481. UploadFormDataItems items{
  9482. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9483. {"hello", "world", "", ""},
  9484. };
  9485. for (const char &c : " \t\r\n") {
  9486. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9487. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9488. ASSERT_FALSE(res);
  9489. }
  9490. }
  9491. TEST(MultipartFormDataTest, AlternateFilename) {
  9492. auto handled = false;
  9493. Server svr;
  9494. svr.Post("/test", [&](const Request &req, Response &res) {
  9495. ASSERT_EQ(2u, req.form.files.size());
  9496. ASSERT_EQ(1u, req.form.fields.size());
  9497. // Test files
  9498. const auto &file1 = req.form.get_file("file1");
  9499. ASSERT_EQ("file1", file1.name);
  9500. ASSERT_EQ("A.txt", file1.filename);
  9501. ASSERT_EQ("text/plain", file1.content_type);
  9502. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9503. const auto &file2 = req.form.get_file("file2");
  9504. ASSERT_EQ("file2", file2.name);
  9505. ASSERT_EQ("a.html", file2.filename);
  9506. ASSERT_EQ("text/html", file2.content_type);
  9507. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9508. file2.content);
  9509. // Test text field
  9510. const auto &text = req.form.get_field("text");
  9511. ASSERT_EQ("text default", text);
  9512. res.set_content("ok", "text/plain");
  9513. handled = true;
  9514. });
  9515. thread t = thread([&] { svr.listen(HOST, PORT); });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. t.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. ASSERT_TRUE(handled);
  9521. });
  9522. svr.wait_until_ready();
  9523. auto req = "POST /test HTTP/1.1\r\n"
  9524. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9525. "Content-Length: 399\r\n"
  9526. "\r\n"
  9527. "----------\r\n"
  9528. "Content-Disposition: form-data; name=\"text\"\r\n"
  9529. "\r\n"
  9530. "text default\r\n"
  9531. "----------\r\n"
  9532. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9533. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9534. "Content-Type: text/plain\r\n"
  9535. "\r\n"
  9536. "Content of a.txt.\r\n"
  9537. "\r\n"
  9538. "----------\r\n"
  9539. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9540. "\"a.html\"\r\n"
  9541. "Content-Type: text/html\r\n"
  9542. "\r\n"
  9543. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9544. "\r\n"
  9545. "------------\r\n";
  9546. ASSERT_TRUE(send_request(1, req));
  9547. }
  9548. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9549. auto handled = false;
  9550. Server svr;
  9551. svr.Post("/test", [&](const Request &req, Response &) {
  9552. ASSERT_EQ(2u, req.form.fields.size());
  9553. const auto &text1 = req.form.get_field("text1");
  9554. ASSERT_EQ("text1", text1);
  9555. const auto &text2 = req.form.get_field("text2");
  9556. ASSERT_EQ("text2", text2);
  9557. handled = true;
  9558. });
  9559. thread t = thread([&] { svr.listen(HOST, PORT); });
  9560. auto se = detail::scope_exit([&] {
  9561. svr.stop();
  9562. t.join();
  9563. ASSERT_FALSE(svr.is_running());
  9564. ASSERT_TRUE(handled);
  9565. });
  9566. svr.wait_until_ready();
  9567. auto req = "POST /test HTTP/1.1\r\n"
  9568. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9569. "Content-Length: 146\r\n"
  9570. "\r\n----------\r\n"
  9571. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9572. "\r\n"
  9573. "text1"
  9574. "\r\n----------\r\n"
  9575. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9576. "\r\n"
  9577. "text2"
  9578. "\r\n------------";
  9579. std::string response;
  9580. ASSERT_TRUE(send_request(1, req, &response));
  9581. ASSERT_EQ("200", response.substr(9, 3));
  9582. }
  9583. TEST(MultipartFormDataTest, ContentLength) {
  9584. auto handled = false;
  9585. Server svr;
  9586. svr.Post("/test", [&](const Request &req, Response &) {
  9587. ASSERT_EQ(2u, req.form.fields.size());
  9588. const auto &text1 = req.form.get_field("text1");
  9589. ASSERT_EQ("text1", text1);
  9590. const auto &text2 = req.form.get_field("text2");
  9591. ASSERT_EQ("text2", text2);
  9592. handled = true;
  9593. });
  9594. thread t = thread([&] { svr.listen(HOST, PORT); });
  9595. auto se = detail::scope_exit([&] {
  9596. svr.stop();
  9597. t.join();
  9598. ASSERT_FALSE(svr.is_running());
  9599. ASSERT_TRUE(handled);
  9600. });
  9601. svr.wait_until_ready();
  9602. auto req = "POST /test HTTP/1.1\r\n"
  9603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9604. "Content-Length: 167\r\n"
  9605. "\r\n----------\r\n"
  9606. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9607. "Content-Length: 5\r\n"
  9608. "\r\n"
  9609. "text1"
  9610. "\r\n----------\r\n"
  9611. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9612. "\r\n"
  9613. "text2"
  9614. "\r\n------------\r\n";
  9615. std::string response;
  9616. ASSERT_TRUE(send_request(1, req, &response));
  9617. ASSERT_EQ("200", response.substr(9, 3));
  9618. }
  9619. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9620. auto handled = false;
  9621. Server svr;
  9622. svr.Post("/test", [&](const Request &req, Response &) {
  9623. ASSERT_EQ(2u, req.form.fields.size());
  9624. const auto &text1 = req.form.get_field("text1");
  9625. ASSERT_EQ("text1", text1);
  9626. // TODO: Add header access for text fields if needed
  9627. const auto &text2 = req.form.get_field("text2");
  9628. ASSERT_EQ("text2", text2);
  9629. // TODO: Header access for text fields needs to be implemented
  9630. // auto &headers = it->second.headers;
  9631. // ASSERT_EQ(3U, headers.size());
  9632. // auto custom_header = headers.find("x-whatever");
  9633. // ASSERT_TRUE(custom_header != headers.end());
  9634. // ASSERT_NE("customvalue", custom_header->second);
  9635. // ASSERT_EQ("CustomValue", custom_header->second);
  9636. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9637. handled = true;
  9638. });
  9639. thread t = thread([&] { svr.listen(HOST, PORT); });
  9640. auto se = detail::scope_exit([&] {
  9641. svr.stop();
  9642. t.join();
  9643. ASSERT_FALSE(svr.is_running());
  9644. ASSERT_TRUE(handled);
  9645. });
  9646. svr.wait_until_ready();
  9647. auto req = "POST /test HTTP/1.1\r\n"
  9648. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9649. "Content-Length: 232\r\n"
  9650. "\r\n----------\r\n"
  9651. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9652. "Content-Length: 5\r\n"
  9653. "X-Test: 1\r\n"
  9654. "\r\n"
  9655. "text1"
  9656. "\r\n----------\r\n"
  9657. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9658. "Content-Type: text/plain\r\n"
  9659. "X-Whatever: CustomValue\r\n"
  9660. "\r\n"
  9661. "text2"
  9662. "\r\n------------\r\n"
  9663. "That should be disregarded. Not even read";
  9664. std::string response;
  9665. ASSERT_TRUE(send_request(1, req, &response));
  9666. ASSERT_EQ("200", response.substr(9, 3));
  9667. }
  9668. TEST(MultipartFormDataTest, LargeHeader) {
  9669. auto handled = false;
  9670. Server svr;
  9671. svr.Post("/test", [&](const Request &req, Response &) {
  9672. ASSERT_EQ(1u, req.form.fields.size());
  9673. const auto &text = req.form.get_field("name1");
  9674. ASSERT_EQ("text1", text);
  9675. handled = true;
  9676. });
  9677. thread t = thread([&] { svr.listen(HOST, PORT); });
  9678. auto se = detail::scope_exit([&] {
  9679. svr.stop();
  9680. t.join();
  9681. ASSERT_FALSE(svr.is_running());
  9682. ASSERT_TRUE(handled);
  9683. });
  9684. svr.wait_until_ready();
  9685. auto boundary = std::string("cpp-httplib-multipart-data");
  9686. std::string content = "--" + boundary +
  9687. "\r\n"
  9688. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9689. "\r\n"
  9690. "text1\r\n"
  9691. "--" +
  9692. boundary + "--\r\n";
  9693. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9694. "Content-Type: multipart/form-data;boundary=" +
  9695. boundary +
  9696. "\r\n"
  9697. "Content-Length: " +
  9698. std::to_string(content.size()) +
  9699. "\r\n"
  9700. "Dummy-Header: ";
  9701. std::string header_suffix = "\r\n"
  9702. "\r\n";
  9703. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9704. size_t header_dummy_size =
  9705. read_buff_size -
  9706. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9707. auto header_dummy = std::string(header_dummy_size, '@');
  9708. auto req = header_prefix + header_dummy + header_suffix + content;
  9709. std::string response;
  9710. ASSERT_TRUE(send_request(1, req, &response));
  9711. ASSERT_EQ("200", response.substr(9, 3));
  9712. }
  9713. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9714. static constexpr unsigned int number_of_tasks{1000000};
  9715. std::atomic_uint count{0};
  9716. std::unique_ptr<TaskQueue> task_queue{
  9717. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9718. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9719. auto queued = task_queue->enqueue(
  9720. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9721. EXPECT_TRUE(queued);
  9722. }
  9723. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9724. task_queue->shutdown();
  9725. #else
  9726. EXPECT_NO_THROW(task_queue->shutdown());
  9727. #endif
  9728. EXPECT_EQ(number_of_tasks, count.load());
  9729. }
  9730. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9731. static constexpr unsigned int number_of_tasks{1000000};
  9732. static constexpr unsigned int qlimit{2};
  9733. unsigned int queued_count{0};
  9734. std::atomic_uint count{0};
  9735. std::unique_ptr<TaskQueue> task_queue{
  9736. new ThreadPool{/*num_threads=*/1, qlimit}};
  9737. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9738. if (task_queue->enqueue(
  9739. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9740. queued_count++;
  9741. }
  9742. }
  9743. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9744. task_queue->shutdown();
  9745. #else
  9746. EXPECT_NO_THROW(task_queue->shutdown());
  9747. #endif
  9748. EXPECT_EQ(queued_count, count.load());
  9749. EXPECT_TRUE(queued_count <= number_of_tasks);
  9750. EXPECT_TRUE(queued_count >= qlimit);
  9751. }
  9752. TEST(TaskQueueTest, MaxQueuedRequests) {
  9753. static constexpr unsigned int qlimit{3};
  9754. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9755. std::condition_variable sem_cv;
  9756. std::mutex sem_mtx;
  9757. int credits = 0;
  9758. bool queued;
  9759. /* Fill up the queue with tasks that will block until we give them credits to
  9760. * complete. */
  9761. for (unsigned int n = 0; n <= qlimit;) {
  9762. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9763. std::unique_lock<std::mutex> lock(sem_mtx);
  9764. while (credits <= 0) {
  9765. sem_cv.wait(lock);
  9766. }
  9767. /* Consume the credit and signal the test code if they are all gone. */
  9768. if (--credits == 0) { sem_cv.notify_one(); }
  9769. });
  9770. if (n < qlimit) {
  9771. /* The first qlimit enqueues must succeed. */
  9772. EXPECT_TRUE(queued);
  9773. } else {
  9774. /* The last one will succeed only when the worker thread
  9775. * starts and dequeues the first blocking task. Although
  9776. * not necessary for the correctness of this test, we sleep for
  9777. * a short while to avoid busy waiting. */
  9778. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9779. }
  9780. if (queued) { n++; }
  9781. }
  9782. /* Further enqueues must fail since the queue is full. */
  9783. for (auto i = 0; i < 4; i++) {
  9784. queued = task_queue->enqueue([] {});
  9785. EXPECT_FALSE(queued);
  9786. }
  9787. /* Give the credits to allow the previous tasks to complete. */
  9788. {
  9789. std::unique_lock<std::mutex> lock(sem_mtx);
  9790. credits += qlimit + 1;
  9791. }
  9792. sem_cv.notify_all();
  9793. /* Wait for all the credits to be consumed. */
  9794. {
  9795. std::unique_lock<std::mutex> lock(sem_mtx);
  9796. while (credits > 0) {
  9797. sem_cv.wait(lock);
  9798. }
  9799. }
  9800. /* Check that we are able again to enqueue at least qlimit tasks. */
  9801. for (unsigned int i = 0; i < qlimit; i++) {
  9802. queued = task_queue->enqueue([] {});
  9803. EXPECT_TRUE(queued);
  9804. }
  9805. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9806. task_queue->shutdown();
  9807. #else
  9808. EXPECT_NO_THROW(task_queue->shutdown());
  9809. #endif
  9810. }
  9811. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9812. Server svr;
  9813. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9814. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9815. });
  9816. svr.Get("/hello", [](const Request &req, Response &res) {
  9817. res.set_content(req.get_param_value("key"), "text/plain");
  9818. });
  9819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9820. auto se = detail::scope_exit([&] {
  9821. svr.stop();
  9822. thread.join();
  9823. ASSERT_FALSE(svr.is_running());
  9824. });
  9825. svr.wait_until_ready();
  9826. {
  9827. Client cli(HOST, PORT);
  9828. cli.set_follow_location(true);
  9829. auto res = cli.Get("/");
  9830. ASSERT_TRUE(res);
  9831. EXPECT_EQ(StatusCode::OK_200, res->status);
  9832. EXPECT_EQ("val&key2=val2", res->body);
  9833. }
  9834. }
  9835. #endif
  9836. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9837. Server svr;
  9838. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9839. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9840. });
  9841. svr.Get("/hello", [](const Request &req, Response &res) {
  9842. res.set_content(req.get_param_value("key"), "text/plain");
  9843. });
  9844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9845. auto se = detail::scope_exit([&] {
  9846. svr.stop();
  9847. thread.join();
  9848. ASSERT_FALSE(svr.is_running());
  9849. });
  9850. svr.wait_until_ready();
  9851. {
  9852. Client cli(HOST, PORT);
  9853. cli.set_follow_location(true);
  9854. auto res = cli.Get("/");
  9855. ASSERT_TRUE(res);
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9858. }
  9859. }
  9860. #ifdef CPPHTTPLIB_SSL_ENABLED
  9861. TEST(RedirectTest, Issue2185_Online) {
  9862. SSLClient client("github.com");
  9863. client.set_follow_location(true);
  9864. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9865. "Coollab-Windows.zip");
  9866. ASSERT_TRUE(res);
  9867. EXPECT_EQ(StatusCode::OK_200, res->status);
  9868. EXPECT_EQ(9920427U, res->body.size());
  9869. }
  9870. #endif
  9871. TEST(VulnerabilityTest, CRLFInjection) {
  9872. Server svr;
  9873. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9874. res.set_content("Hello 1", "text/plain");
  9875. });
  9876. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9877. res.set_content("Hello 2", "text/plain");
  9878. });
  9879. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9880. res.set_content("Hello 3", "text/plain");
  9881. });
  9882. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9883. res.set_content("Hello 4", "text/plain");
  9884. });
  9885. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9886. for (const auto &x : req.headers) {
  9887. auto key = x.first;
  9888. EXPECT_STRNE("evil", key.c_str());
  9889. }
  9890. });
  9891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. thread.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. {
  9899. Client cli(HOST, PORT);
  9900. cli.Post("/test1", "A=B",
  9901. "application/x-www-form-urlencoded\r\nevil: hello1");
  9902. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9903. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9904. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9905. }
  9906. }
  9907. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9908. auto server_thread = std::thread([] {
  9909. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9910. default_socket_options(srv);
  9911. sockaddr_in addr{};
  9912. addr.sin_family = AF_INET;
  9913. addr.sin_port = htons(PORT + 1);
  9914. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9915. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9916. ::listen(srv, 1);
  9917. sockaddr_in cli_addr{};
  9918. socklen_t cli_len = sizeof(cli_addr);
  9919. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9920. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9921. std::string buf_all;
  9922. char buf[2048];
  9923. ssize_t n;
  9924. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9925. buf_all.append(buf, static_cast<size_t>(n));
  9926. size_t pos;
  9927. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9928. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9929. auto e = request_block.find("\r\n");
  9930. if (e != std::string::npos) {
  9931. auto request_line = request_block.substr(0, e);
  9932. std::string msg =
  9933. "CRLF injection detected in request line: '" + request_line + "'";
  9934. EXPECT_FALSE(true) << msg;
  9935. }
  9936. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9937. ::send(cli,
  9938. #ifdef _WIN32
  9939. static_cast<const char *>(resp.c_str()),
  9940. static_cast<int>(resp.size()),
  9941. #else
  9942. resp.c_str(), resp.size(),
  9943. #endif
  9944. 0);
  9945. buf_all.erase(0, pos + 4);
  9946. }
  9947. }
  9948. detail::close_socket(cli);
  9949. detail::close_socket(srv);
  9950. });
  9951. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9952. auto cli = Client("127.0.0.1", PORT + 1);
  9953. auto headers = Headers{
  9954. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9955. {"Connection", "keep-alive"}};
  9956. auto res = cli.Get("/hi", headers);
  9957. EXPECT_FALSE(res);
  9958. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9959. server_thread.join();
  9960. }
  9961. TEST(PathParamsTest, StaticMatch) {
  9962. const auto pattern = "/users/all";
  9963. detail::PathParamsMatcher matcher(pattern);
  9964. Request request;
  9965. request.path = "/users/all";
  9966. ASSERT_TRUE(matcher.match(request));
  9967. std::unordered_map<std::string, std::string> expected_params = {};
  9968. EXPECT_EQ(request.path_params, expected_params);
  9969. }
  9970. TEST(PathParamsTest, StaticMismatch) {
  9971. const auto pattern = "/users/all";
  9972. detail::PathParamsMatcher matcher(pattern);
  9973. Request request;
  9974. request.path = "/users/1";
  9975. ASSERT_FALSE(matcher.match(request));
  9976. }
  9977. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9978. const auto pattern = "/users/:id/subscriptions";
  9979. detail::PathParamsMatcher matcher(pattern);
  9980. Request request;
  9981. request.path = "/users/42/subscriptions";
  9982. ASSERT_TRUE(matcher.match(request));
  9983. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9984. EXPECT_EQ(request.path_params, expected_params);
  9985. }
  9986. TEST(PathParamsTest, SingleParamInTheEnd) {
  9987. const auto pattern = "/users/:id";
  9988. detail::PathParamsMatcher matcher(pattern);
  9989. Request request;
  9990. request.path = "/users/24";
  9991. ASSERT_TRUE(matcher.match(request));
  9992. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9993. EXPECT_EQ(request.path_params, expected_params);
  9994. }
  9995. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9996. const auto pattern = "/users/:id/";
  9997. detail::PathParamsMatcher matcher(pattern);
  9998. Request request;
  9999. request.path = "/users/42/";
  10000. ASSERT_TRUE(matcher.match(request));
  10001. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10002. EXPECT_EQ(request.path_params, expected_params);
  10003. }
  10004. TEST(PathParamsTest, EmptyParam) {
  10005. const auto pattern = "/users/:id/";
  10006. detail::PathParamsMatcher matcher(pattern);
  10007. Request request;
  10008. request.path = "/users//";
  10009. ASSERT_TRUE(matcher.match(request));
  10010. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10011. EXPECT_EQ(request.path_params, expected_params);
  10012. }
  10013. TEST(PathParamsTest, FragmentMismatch) {
  10014. const auto pattern = "/users/:id/";
  10015. detail::PathParamsMatcher matcher(pattern);
  10016. Request request;
  10017. request.path = "/admins/24/";
  10018. ASSERT_FALSE(matcher.match(request));
  10019. }
  10020. TEST(PathParamsTest, ExtraFragments) {
  10021. const auto pattern = "/users/:id";
  10022. detail::PathParamsMatcher matcher(pattern);
  10023. Request request;
  10024. request.path = "/users/42/subscriptions";
  10025. ASSERT_FALSE(matcher.match(request));
  10026. }
  10027. TEST(PathParamsTest, MissingTrailingParam) {
  10028. const auto pattern = "/users/:id";
  10029. detail::PathParamsMatcher matcher(pattern);
  10030. Request request;
  10031. request.path = "/users";
  10032. ASSERT_FALSE(matcher.match(request));
  10033. }
  10034. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10035. const auto pattern = "/users/:id/subscriptions";
  10036. detail::PathParamsMatcher matcher(pattern);
  10037. Request request;
  10038. request.path = "/users/subscriptions";
  10039. ASSERT_FALSE(matcher.match(request));
  10040. }
  10041. TEST(PathParamsTest, MultipleParams) {
  10042. const auto pattern = "/users/:userid/subscriptions/:subid";
  10043. detail::PathParamsMatcher matcher(pattern);
  10044. Request request;
  10045. request.path = "/users/42/subscriptions/2";
  10046. ASSERT_TRUE(matcher.match(request));
  10047. std::unordered_map<std::string, std::string> expected_params = {
  10048. {"userid", "42"}, {"subid", "2"}};
  10049. EXPECT_EQ(request.path_params, expected_params);
  10050. }
  10051. TEST(PathParamsTest, SequenceOfParams) {
  10052. const auto pattern = "/values/:x/:y/:z";
  10053. detail::PathParamsMatcher matcher(pattern);
  10054. Request request;
  10055. request.path = "/values/1/2/3";
  10056. ASSERT_TRUE(matcher.match(request));
  10057. std::unordered_map<std::string, std::string> expected_params = {
  10058. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10059. EXPECT_EQ(request.path_params, expected_params);
  10060. }
  10061. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10062. const auto pattern = "/prefix:suffix";
  10063. detail::PathParamsMatcher matcher(pattern);
  10064. Request request;
  10065. request.path = "/prefix:suffix";
  10066. ASSERT_TRUE(matcher.match(request));
  10067. const std::unordered_map<std::string, std::string> expected_params = {};
  10068. EXPECT_EQ(request.path_params, expected_params);
  10069. }
  10070. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10071. // If ipv6 regex working, regex match codepath is taken.
  10072. // else port will default to 80 in Client impl
  10073. int clientImplMagicPort = 80;
  10074. int port = 4321;
  10075. // above ports must be different to avoid false negative
  10076. EXPECT_NE(clientImplMagicPort, port);
  10077. std::string ipV6TestURL = "http://[ff06::c3]";
  10078. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10079. CLIENT_PRIVATE_KEY_FILE);
  10080. EXPECT_EQ(cli.port(), port);
  10081. }
  10082. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10083. auto file_path = "./www/dir/index.html";
  10084. auto dir_path = "./www/dir";
  10085. detail::FileStat stat_file(file_path);
  10086. EXPECT_TRUE(stat_file.is_file());
  10087. EXPECT_FALSE(stat_file.is_dir());
  10088. detail::FileStat stat_dir(dir_path);
  10089. EXPECT_FALSE(stat_dir.is_file());
  10090. EXPECT_TRUE(stat_dir.is_dir());
  10091. }
  10092. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10093. // IPv4 with default HTTP port (80)
  10094. EXPECT_EQ("example.com",
  10095. detail::make_host_and_port_string("example.com", 80, false));
  10096. // IPv4 with default HTTPS port (443)
  10097. EXPECT_EQ("example.com",
  10098. detail::make_host_and_port_string("example.com", 443, true));
  10099. // IPv4 with non-default HTTP port
  10100. EXPECT_EQ("example.com:8080",
  10101. detail::make_host_and_port_string("example.com", 8080, false));
  10102. // IPv4 with non-default HTTPS port
  10103. EXPECT_EQ("example.com:8443",
  10104. detail::make_host_and_port_string("example.com", 8443, true));
  10105. // IPv6 with default HTTP port (80)
  10106. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10107. // IPv6 with default HTTPS port (443)
  10108. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10109. // IPv6 with non-default HTTP port
  10110. EXPECT_EQ("[::1]:8080",
  10111. detail::make_host_and_port_string("::1", 8080, false));
  10112. // IPv6 with non-default HTTPS port
  10113. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10114. // IPv6 full address with default port
  10115. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10116. detail::make_host_and_port_string(
  10117. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10118. // IPv6 full address with non-default port
  10119. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10120. detail::make_host_and_port_string(
  10121. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10122. // IPv6 localhost with non-default port
  10123. EXPECT_EQ("[::1]:3000",
  10124. detail::make_host_and_port_string("::1", 3000, false));
  10125. // IPv6 with zone ID (link-local address) with default port
  10126. EXPECT_EQ("[fe80::1%eth0]",
  10127. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10128. // IPv6 with zone ID (link-local address) with non-default port
  10129. EXPECT_EQ("[fe80::1%eth0]:8080",
  10130. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10131. // Edge case: Port 443 with is_ssl=false (should add port)
  10132. EXPECT_EQ("example.com:443",
  10133. detail::make_host_and_port_string("example.com", 443, false));
  10134. // Edge case: Port 80 with is_ssl=true (should add port)
  10135. EXPECT_EQ("example.com:80",
  10136. detail::make_host_and_port_string("example.com", 80, true));
  10137. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10138. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10139. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10140. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10141. // Security fix: Already bracketed IPv6 should not get double brackets
  10142. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10143. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10144. EXPECT_EQ("[::1]:8080",
  10145. detail::make_host_and_port_string("[::1]", 8080, false));
  10146. EXPECT_EQ("[2001:db8::1]:8080",
  10147. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10148. EXPECT_EQ("[fe80::1%eth0]",
  10149. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10150. EXPECT_EQ("[fe80::1%eth0]:8080",
  10151. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10152. // Edge case: Empty host (should return as-is)
  10153. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10154. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10155. // This is a known limitation but shouldn't crash
  10156. EXPECT_EQ("[host:name]",
  10157. detail::make_host_and_port_string("host:name", 80, false));
  10158. // Port number edge cases (no validation, but should not crash)
  10159. EXPECT_EQ("example.com:0",
  10160. detail::make_host_and_port_string("example.com", 0, false));
  10161. EXPECT_EQ("example.com:-1",
  10162. detail::make_host_and_port_string("example.com", -1, false));
  10163. EXPECT_EQ("example.com:65535",
  10164. detail::make_host_and_port_string("example.com", 65535, false));
  10165. EXPECT_EQ("example.com:65536",
  10166. detail::make_host_and_port_string("example.com", 65536, false));
  10167. }
  10168. #ifdef CPPHTTPLIB_SSL_ENABLED
  10169. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10170. httplib::SSLClient cli("roblox.com", 443);
  10171. cli.set_follow_location(true);
  10172. auto res = cli.Get("/");
  10173. ASSERT_TRUE(res);
  10174. EXPECT_EQ(StatusCode::OK_200, res->status);
  10175. }
  10176. #endif
  10177. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10178. Server svr;
  10179. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10180. EXPECT_EQ(res.status, 400);
  10181. });
  10182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10183. auto se = detail::scope_exit([&] {
  10184. svr.stop();
  10185. thread.join();
  10186. ASSERT_FALSE(svr.is_running());
  10187. });
  10188. svr.wait_until_ready();
  10189. Client cli(HOST, PORT);
  10190. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10191. }
  10192. TEST(InvalidHeaderCharsTest, is_field_name) {
  10193. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10194. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10195. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10196. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10197. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10198. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10199. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10200. EXPECT_FALSE(detail::fields::is_field_name(""));
  10201. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10202. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10203. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10204. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10205. }
  10206. TEST(InvalidHeaderCharsTest, is_field_value) {
  10207. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10208. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10209. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10210. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10211. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10212. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10213. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10214. EXPECT_TRUE(detail::fields::is_field_value(""));
  10215. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10216. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10217. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10218. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10219. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10220. }
  10221. TEST(InvalidHeaderCharsTest, OnServer) {
  10222. Server svr;
  10223. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10224. std::string header = "Not Set";
  10225. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10226. res.set_header(header, "value");
  10227. res.set_content("Page Content Page Content", "text/plain");
  10228. });
  10229. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10230. std::string header = "Not Set";
  10231. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10232. res.set_header("X-Test", header);
  10233. res.set_content("Page Content Page Content", "text/plain");
  10234. });
  10235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. thread.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. Client cli(HOST, PORT);
  10243. {
  10244. auto res = cli.Get(
  10245. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10246. ASSERT_TRUE(res);
  10247. EXPECT_EQ("Page Content Page Content", res->body);
  10248. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10249. }
  10250. {
  10251. auto res = cli.Get(
  10252. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10253. ASSERT_TRUE(res);
  10254. EXPECT_EQ("Page Content Page Content", res->body);
  10255. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10256. }
  10257. }
  10258. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10259. auto handled = false;
  10260. Server svr;
  10261. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10262. thread t = thread([&] { svr.listen(HOST, PORT); });
  10263. auto se = detail::scope_exit([&] {
  10264. svr.stop();
  10265. t.join();
  10266. ASSERT_FALSE(svr.is_running());
  10267. ASSERT_FALSE(handled);
  10268. });
  10269. svr.wait_until_ready();
  10270. auto req = "POST /test HTTP/1.1\r\n"
  10271. "Content-Length: x\r\n"
  10272. "\r\n";
  10273. std::string response;
  10274. ASSERT_TRUE(send_request(1, req, &response));
  10275. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10276. response.substr(0, response.find("\r\n")));
  10277. }
  10278. #ifndef _WIN32
  10279. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10280. static constexpr char reject[] = "Unauthorized";
  10281. static constexpr char accept[] = "Upload accepted";
  10282. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10283. Server svr;
  10284. svr.set_expect_100_continue_handler(
  10285. [](const Request & /*req*/, Response &res) {
  10286. res.status = StatusCode::Unauthorized_401;
  10287. res.set_content(reject, "text/plain");
  10288. return res.status;
  10289. });
  10290. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10291. res.set_content(accept, "text/plain");
  10292. });
  10293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10294. auto se = detail::scope_exit([&] {
  10295. svr.stop();
  10296. thread.join();
  10297. ASSERT_FALSE(svr.is_running());
  10298. });
  10299. svr.wait_until_ready();
  10300. {
  10301. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10302. curl_easy_init(), &curl_easy_cleanup};
  10303. ASSERT_NE(curl, nullptr);
  10304. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10305. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10306. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10307. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10308. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10309. &curl_slist_free_all};
  10310. ASSERT_NE(list, nullptr);
  10311. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10312. struct read_data {
  10313. size_t read_size;
  10314. size_t total_size;
  10315. } data = {0, total_size};
  10316. using read_callback_t =
  10317. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10318. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10319. void *userdata) -> size_t {
  10320. read_data *data = (read_data *)userdata;
  10321. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10322. std::fill_n(ptr, size * nmemb, 'A');
  10323. data->read_size += size * nmemb;
  10324. return size * nmemb;
  10325. };
  10326. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10327. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10328. std::vector<char> buffer;
  10329. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10330. using write_callback_t =
  10331. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10332. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10333. void *userdata) -> size_t {
  10334. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10335. buffer->reserve(buffer->size() + size * nmemb + 1);
  10336. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10337. return size * nmemb;
  10338. };
  10339. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10340. {
  10341. const auto res = curl_easy_perform(curl.get());
  10342. ASSERT_EQ(res, CURLE_OK);
  10343. }
  10344. {
  10345. auto response_code = long{};
  10346. const auto res =
  10347. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10348. ASSERT_EQ(res, CURLE_OK);
  10349. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10350. }
  10351. {
  10352. auto dl = curl_off_t{};
  10353. const auto res =
  10354. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10355. ASSERT_EQ(res, CURLE_OK);
  10356. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10357. }
  10358. {
  10359. buffer.push_back('\0');
  10360. ASSERT_STRCASEEQ(buffer.data(), reject);
  10361. }
  10362. }
  10363. }
  10364. #endif
  10365. template <typename S, typename C>
  10366. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10367. svr.Get("/stream", [&](const Request &, Response &res) {
  10368. auto data = new std::string("01234567890123456789");
  10369. res.set_content_provider(
  10370. data->size(), "text/plain",
  10371. [&, data](size_t offset, size_t length, DataSink &sink) {
  10372. const size_t DATA_CHUNK_SIZE = 4;
  10373. const auto &d = *data;
  10374. std::this_thread::sleep_for(std::chrono::seconds(1));
  10375. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10376. return true;
  10377. },
  10378. [data](bool success) {
  10379. EXPECT_FALSE(success);
  10380. delete data;
  10381. });
  10382. });
  10383. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10384. auto i = new size_t(0);
  10385. res.set_content_provider(
  10386. "text/plain",
  10387. [i](size_t, DataSink &sink) {
  10388. if (*i < 5) {
  10389. std::this_thread::sleep_for(std::chrono::seconds(1));
  10390. sink.write("abcd", 4);
  10391. (*i)++;
  10392. } else {
  10393. sink.done();
  10394. }
  10395. return true;
  10396. },
  10397. [i](bool success) {
  10398. EXPECT_FALSE(success);
  10399. delete i;
  10400. });
  10401. });
  10402. svr.Get("/chunked", [&](const Request &, Response &res) {
  10403. auto i = new size_t(0);
  10404. res.set_chunked_content_provider(
  10405. "text/plain",
  10406. [i](size_t, DataSink &sink) {
  10407. if (*i < 5) {
  10408. std::this_thread::sleep_for(std::chrono::seconds(1));
  10409. sink.os << "abcd";
  10410. (*i)++;
  10411. } else {
  10412. sink.done();
  10413. }
  10414. return true;
  10415. },
  10416. [i](bool success) {
  10417. EXPECT_FALSE(success);
  10418. delete i;
  10419. });
  10420. });
  10421. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10422. auto se = detail::scope_exit([&] {
  10423. svr.stop();
  10424. listen_thread.join();
  10425. ASSERT_FALSE(svr.is_running());
  10426. });
  10427. svr.wait_until_ready();
  10428. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10429. {
  10430. auto start = std::chrono::steady_clock::now();
  10431. auto res = cli.Get("/stream");
  10432. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10433. std::chrono::steady_clock::now() - start)
  10434. .count();
  10435. ASSERT_FALSE(res);
  10436. EXPECT_EQ(Error::Read, res.error());
  10437. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10438. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10439. }
  10440. {
  10441. auto start = std::chrono::steady_clock::now();
  10442. auto res = cli.Get("/stream_without_length");
  10443. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10444. std::chrono::steady_clock::now() - start)
  10445. .count();
  10446. ASSERT_FALSE(res);
  10447. EXPECT_EQ(Error::Read, res.error());
  10448. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10449. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10450. }
  10451. {
  10452. auto start = std::chrono::steady_clock::now();
  10453. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10454. EXPECT_EQ("abcd", string(data, data_length));
  10455. return true;
  10456. });
  10457. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10458. std::chrono::steady_clock::now() - start)
  10459. .count();
  10460. ASSERT_FALSE(res);
  10461. EXPECT_EQ(Error::Read, res.error());
  10462. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10463. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10464. }
  10465. }
  10466. TEST(MaxTimeoutTest, ContentStream) {
  10467. time_t timeout = 2000;
  10468. time_t threshold = 200;
  10469. Server svr;
  10470. Client cli("localhost", PORT);
  10471. max_timeout_test(svr, cli, timeout, threshold);
  10472. }
  10473. #ifdef CPPHTTPLIB_SSL_ENABLED
  10474. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10475. time_t timeout = 2000;
  10476. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10478. SSLClient cli("localhost", PORT);
  10479. cli.enable_server_certificate_verification(false);
  10480. max_timeout_test(svr, cli, timeout, threshold);
  10481. }
  10482. #endif
  10483. class EventDispatcher {
  10484. public:
  10485. EventDispatcher() {}
  10486. bool wait_event(DataSink *sink) {
  10487. unique_lock<mutex> lk(m_);
  10488. int id = id_;
  10489. // Wait with timeout to prevent hanging if client disconnects
  10490. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10491. [&] { return cid_ == id; })) {
  10492. return false; // Timeout occurred
  10493. }
  10494. sink->write(message_.data(), message_.size());
  10495. return true;
  10496. }
  10497. void send_event(const string &message) {
  10498. lock_guard<mutex> lk(m_);
  10499. cid_ = id_++;
  10500. message_ = message;
  10501. cv_.notify_all();
  10502. }
  10503. private:
  10504. mutex m_;
  10505. condition_variable cv_;
  10506. atomic_int id_{0};
  10507. atomic_int cid_{-1};
  10508. string message_;
  10509. };
  10510. TEST(ClientInThreadTest, Issue2068) {
  10511. EventDispatcher ed;
  10512. Server svr;
  10513. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10514. res.set_chunked_content_provider("text/event-stream",
  10515. [&](size_t /*offset*/, DataSink &sink) {
  10516. return ed.wait_event(&sink);
  10517. });
  10518. });
  10519. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10520. svr.wait_until_ready();
  10521. thread event_thread([&] {
  10522. int id = 0;
  10523. while (svr.is_running()) {
  10524. this_thread::sleep_for(chrono::milliseconds(500));
  10525. std::stringstream ss;
  10526. ss << "data: " << id << "\n\n";
  10527. ed.send_event(ss.str());
  10528. id++;
  10529. }
  10530. });
  10531. auto se = detail::scope_exit([&] {
  10532. svr.stop();
  10533. listen_thread.join();
  10534. event_thread.join();
  10535. ASSERT_FALSE(svr.is_running());
  10536. });
  10537. {
  10538. auto client = detail::make_unique<Client>(HOST, PORT);
  10539. client->set_read_timeout(std::chrono::minutes(10));
  10540. std::atomic<bool> stop{false};
  10541. std::thread t([&] {
  10542. client->Get("/event1",
  10543. [&](const char *, size_t) -> bool { return !stop; });
  10544. });
  10545. std::this_thread::sleep_for(std::chrono::seconds(2));
  10546. stop = true;
  10547. client->stop();
  10548. t.join();
  10549. // Reset client after thread has finished
  10550. client.reset();
  10551. }
  10552. }
  10553. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10554. Server svr;
  10555. svr.Get("/", [](const Request &req, Response &res) {
  10556. EXPECT_EQ(2U, req.trailers.size());
  10557. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10558. // Denied
  10559. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10560. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10561. // Accepted
  10562. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10563. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10564. EXPECT_TRUE(req.has_trailer("X-World"));
  10565. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10566. res.set_content("ok", "text/plain");
  10567. });
  10568. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10569. auto se = detail::scope_exit([&] {
  10570. svr.stop();
  10571. t.join();
  10572. ASSERT_FALSE(svr.is_running());
  10573. });
  10574. svr.wait_until_ready();
  10575. const std::string req = "GET / HTTP/1.1\r\n"
  10576. "Transfer-Encoding: chunked\r\n"
  10577. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10578. "\r\n"
  10579. "0\r\n"
  10580. "Content-Length: 10\r\n"
  10581. "Host: internal.local\r\n"
  10582. "Content-Type: malicious/content\r\n"
  10583. "Cookie: any\r\n"
  10584. "Set-Cookie: any\r\n"
  10585. "X-Forwarded-For: attacker.com\r\n"
  10586. "X-Real-Ip: 1.1.1.1\r\n"
  10587. "X-Hello: hello\r\n"
  10588. "X-World: world\r\n"
  10589. "\r\n";
  10590. std::string res;
  10591. ASSERT_TRUE(send_request(1, req, &res));
  10592. }
  10593. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10594. Server svr;
  10595. std::string observed_remote_addr;
  10596. std::string observed_xff;
  10597. svr.Get("/ip", [&](const Request &req, Response &res) {
  10598. observed_remote_addr = req.remote_addr;
  10599. observed_xff = req.get_header_value("X-Forwarded-For");
  10600. res.set_content("ok", "text/plain");
  10601. });
  10602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10603. auto se = detail::scope_exit([&] {
  10604. svr.stop();
  10605. t.join();
  10606. ASSERT_FALSE(svr.is_running());
  10607. });
  10608. svr.wait_until_ready();
  10609. Client cli(HOST, PORT);
  10610. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10611. ASSERT_TRUE(res);
  10612. EXPECT_EQ(StatusCode::OK_200, res->status);
  10613. EXPECT_EQ(observed_xff, "203.0.113.66");
  10614. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10615. observed_remote_addr == "127.0.0.1");
  10616. }
  10617. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10618. Server svr;
  10619. svr.set_trusted_proxies({"203.0.113.66"});
  10620. std::string observed_remote_addr;
  10621. std::string observed_xff;
  10622. svr.Get("/ip", [&](const Request &req, Response &res) {
  10623. observed_remote_addr = req.remote_addr;
  10624. observed_xff = req.get_header_value("X-Forwarded-For");
  10625. res.set_content("ok", "text/plain");
  10626. });
  10627. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10628. auto se = detail::scope_exit([&] {
  10629. svr.stop();
  10630. t.join();
  10631. ASSERT_FALSE(svr.is_running());
  10632. });
  10633. svr.wait_until_ready();
  10634. Client cli(HOST, PORT);
  10635. auto res = cli.Get("/ip");
  10636. ASSERT_TRUE(res);
  10637. EXPECT_EQ(StatusCode::OK_200, res->status);
  10638. EXPECT_EQ(observed_xff, "");
  10639. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10640. observed_remote_addr == "127.0.0.1");
  10641. }
  10642. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10643. Server svr;
  10644. svr.set_trusted_proxies({"203.0.113.66"});
  10645. std::string observed_remote_addr;
  10646. std::string observed_xff;
  10647. svr.Get("/ip", [&](const Request &req, Response &res) {
  10648. observed_remote_addr = req.remote_addr;
  10649. observed_xff = req.get_header_value("X-Forwarded-For");
  10650. res.set_content("ok", "text/plain");
  10651. });
  10652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10653. auto se = detail::scope_exit([&] {
  10654. svr.stop();
  10655. t.join();
  10656. ASSERT_FALSE(svr.is_running());
  10657. });
  10658. svr.wait_until_ready();
  10659. Client cli(HOST, PORT);
  10660. auto res =
  10661. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10662. ASSERT_TRUE(res);
  10663. EXPECT_EQ(StatusCode::OK_200, res->status);
  10664. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10665. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10666. }
  10667. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10668. Server svr;
  10669. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10670. std::string observed_remote_addr;
  10671. std::string observed_xff;
  10672. svr.Get("/ip", [&](const Request &req, Response &res) {
  10673. observed_remote_addr = req.remote_addr;
  10674. observed_xff = req.get_header_value("X-Forwarded-For");
  10675. res.set_content("ok", "text/plain");
  10676. });
  10677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. Client cli(HOST, PORT);
  10685. auto res = cli.Get(
  10686. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10687. ASSERT_TRUE(res);
  10688. EXPECT_EQ(StatusCode::OK_200, res->status);
  10689. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10690. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10691. }
  10692. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10693. Server svr;
  10694. svr.set_trusted_proxies({"192.0.2.45"});
  10695. std::string observed_remote_addr;
  10696. std::string observed_xff;
  10697. svr.Get("/ip", [&](const Request &req, Response &res) {
  10698. observed_remote_addr = req.remote_addr;
  10699. observed_xff = req.get_header_value("X-Forwarded-For");
  10700. res.set_content("ok", "text/plain");
  10701. });
  10702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10703. auto se = detail::scope_exit([&] {
  10704. svr.stop();
  10705. t.join();
  10706. ASSERT_FALSE(svr.is_running());
  10707. });
  10708. svr.wait_until_ready();
  10709. Client cli(HOST, PORT);
  10710. auto res =
  10711. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10712. ASSERT_TRUE(res);
  10713. EXPECT_EQ(StatusCode::OK_200, res->status);
  10714. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10715. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10716. }
  10717. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10718. Server svr;
  10719. svr.set_trusted_proxies({"192.0.2.45"});
  10720. std::string observed_remote_addr;
  10721. std::string observed_xff;
  10722. svr.Get("/ip", [&](const Request &req, Response &res) {
  10723. observed_remote_addr = req.remote_addr;
  10724. observed_xff = req.get_header_value("X-Forwarded-For");
  10725. res.set_content("ok", "text/plain");
  10726. });
  10727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, PORT);
  10735. auto res = cli.Get(
  10736. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10737. ASSERT_TRUE(res);
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10740. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10741. }
  10742. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10743. Server svr;
  10744. svr.set_trusted_proxies({"192.0.2.45"});
  10745. std::string observed_remote_addr;
  10746. std::string observed_xff;
  10747. svr.Get("/ip", [&](const Request &req, Response &res) {
  10748. observed_remote_addr = req.remote_addr;
  10749. observed_xff = req.get_header_value("X-Forwarded-For");
  10750. res.set_content("ok", "text/plain");
  10751. });
  10752. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10753. auto se = detail::scope_exit([&] {
  10754. svr.stop();
  10755. t.join();
  10756. ASSERT_FALSE(svr.is_running());
  10757. });
  10758. svr.wait_until_ready();
  10759. std::string raw_req =
  10760. "GET /ip HTTP/1.1\r\n"
  10761. "Host: localhost\r\n"
  10762. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10763. "Connection: close\r\n"
  10764. "\r\n";
  10765. std::string out;
  10766. ASSERT_TRUE(send_request(5, raw_req, &out));
  10767. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10768. // Header parser trims surrounding whitespace of the header value
  10769. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10770. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10771. }
  10772. #ifndef _WIN32
  10773. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10774. Server svr;
  10775. svr.Post("/post", [&](const Request &req, Response &res) {
  10776. res.set_content(req.body, "text/plain");
  10777. });
  10778. svr.Put("/put", [&](const Request &req, Response &res) {
  10779. res.set_content(req.body, "text/plain");
  10780. });
  10781. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10782. res.set_content(req.body, "text/plain");
  10783. });
  10784. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10785. res.set_content(req.body, "text/plain");
  10786. });
  10787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10788. auto se = detail::scope_exit([&] {
  10789. svr.stop();
  10790. t.join();
  10791. ASSERT_FALSE(svr.is_running());
  10792. });
  10793. svr.wait_until_ready();
  10794. std::string resp;
  10795. // POST without Content-Length
  10796. ASSERT_TRUE(send_request(5,
  10797. "POST /post HTTP/1.1\r\n"
  10798. "Host: localhost\r\n"
  10799. "Connection: close\r\n"
  10800. "\r\n",
  10801. &resp));
  10802. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10803. // PUT without Content-Length
  10804. resp.clear();
  10805. ASSERT_TRUE(send_request(5,
  10806. "PUT /put HTTP/1.1\r\n"
  10807. "Host: localhost\r\n"
  10808. "Connection: close\r\n"
  10809. "\r\n",
  10810. &resp));
  10811. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10812. // PATCH without Content-Length
  10813. resp.clear();
  10814. ASSERT_TRUE(send_request(5,
  10815. "PATCH /patch HTTP/1.1\r\n"
  10816. "Host: localhost\r\n"
  10817. "Connection: close\r\n"
  10818. "\r\n",
  10819. &resp));
  10820. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10821. // DELETE without Content-Length
  10822. resp.clear();
  10823. ASSERT_TRUE(send_request(5,
  10824. "DELETE /delete HTTP/1.1\r\n"
  10825. "Host: localhost\r\n"
  10826. "Connection: close\r\n"
  10827. "\r\n",
  10828. &resp));
  10829. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10830. }
  10831. #endif
  10832. //==============================================================================
  10833. // open_stream() Tests
  10834. //==============================================================================
  10835. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10836. std::string result;
  10837. char buf[8192];
  10838. ssize_t n;
  10839. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10840. result.append(buf, static_cast<size_t>(n));
  10841. }
  10842. return result;
  10843. }
  10844. // Mock stream for unit tests
  10845. class MockStream : public Stream {
  10846. public:
  10847. std::string data;
  10848. size_t pos = 0;
  10849. ssize_t error_after = -1; // -1 = no error
  10850. explicit MockStream(const std::string &d, ssize_t err = -1)
  10851. : data(d), error_after(err) {}
  10852. bool is_readable() const override { return true; }
  10853. bool wait_readable() const override { return true; }
  10854. bool wait_writable() const override { return true; }
  10855. ssize_t read(char *ptr, size_t size) override {
  10856. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10857. if (pos >= data.size()) return 0;
  10858. size_t limit =
  10859. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10860. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10861. std::memcpy(ptr, data.data() + pos, to_read);
  10862. pos += to_read;
  10863. return static_cast<ssize_t>(to_read);
  10864. }
  10865. ssize_t write(const char *, size_t) override { return -1; }
  10866. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10867. ip = "127.0.0.1";
  10868. port = 0;
  10869. }
  10870. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10871. ip = "127.0.0.1";
  10872. port = 0;
  10873. }
  10874. socket_t socket() const override { return INVALID_SOCKET; }
  10875. time_t duration() const override { return 0; }
  10876. };
  10877. TEST(StreamHandleTest, Basic) {
  10878. ClientImpl::StreamHandle handle;
  10879. EXPECT_FALSE(handle.is_valid());
  10880. handle.response = detail::make_unique<Response>();
  10881. handle.error = Error::Connection;
  10882. EXPECT_FALSE(handle.is_valid());
  10883. handle.error = Error::Success;
  10884. EXPECT_TRUE(handle.is_valid());
  10885. }
  10886. TEST(BodyReaderTest, Basic) {
  10887. MockStream stream("Hello, World!");
  10888. detail::BodyReader reader;
  10889. reader.stream = &stream;
  10890. reader.content_length = 13;
  10891. char buf[32];
  10892. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10893. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10894. EXPECT_TRUE(reader.eof);
  10895. }
  10896. TEST(BodyReaderTest, NoStream) {
  10897. detail::BodyReader reader;
  10898. char buf[32];
  10899. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10900. EXPECT_EQ(Error::Connection, reader.last_error);
  10901. }
  10902. TEST(BodyReaderTest, Error) {
  10903. MockStream stream("Hello, World!", 5);
  10904. detail::BodyReader reader;
  10905. reader.stream = &stream;
  10906. reader.content_length = 13;
  10907. char buf[32];
  10908. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10909. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10910. EXPECT_EQ(Error::Read, reader.last_error);
  10911. }
  10912. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10913. // Mock-based StreamHandle tests relying on private internals are removed.
  10914. class OpenStreamTest : public ::testing::Test {
  10915. protected:
  10916. void SetUp() override {
  10917. svr_.Get("/hello", [](const Request &, Response &res) {
  10918. res.set_content("Hello World!", "text/plain");
  10919. });
  10920. svr_.Get("/large", [](const Request &, Response &res) {
  10921. res.set_content(std::string(10000, 'X'), "text/plain");
  10922. });
  10923. svr_.Get("/chunked", [](const Request &, Response &res) {
  10924. res.set_chunked_content_provider("text/plain",
  10925. [](size_t offset, DataSink &sink) {
  10926. if (offset < 15) {
  10927. sink.write("chunk", 5);
  10928. return true;
  10929. }
  10930. sink.done();
  10931. return true;
  10932. });
  10933. });
  10934. svr_.Get("/compressible", [](const Request &, Response &res) {
  10935. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10936. DataSink &sink) {
  10937. if (offset < 100 * 1024) {
  10938. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10939. sink.write(chunk.data(), chunk.size());
  10940. return true;
  10941. }
  10942. sink.done();
  10943. return true;
  10944. });
  10945. });
  10946. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10947. [](const Request & /*req*/, Response &res) {
  10948. auto i = new int(0);
  10949. res.set_header("Trailer", "Content-Length, X-Allowed");
  10950. res.set_chunked_content_provider(
  10951. "text/plain",
  10952. [i](size_t /*offset*/, DataSink &sink) {
  10953. switch (*i) {
  10954. case 0: sink.os << "123"; break;
  10955. case 1: sink.os << "456"; break;
  10956. case 2: sink.os << "789"; break;
  10957. case 3: {
  10958. sink.done_with_trailer(
  10959. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10960. } break;
  10961. }
  10962. (*i)++;
  10963. return true;
  10964. },
  10965. [i](bool success) {
  10966. EXPECT_TRUE(success);
  10967. delete i;
  10968. });
  10969. });
  10970. // Echo headers endpoint for header-related tests
  10971. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10972. std::string body;
  10973. for (const auto &h : req.headers) {
  10974. body.append(h.first);
  10975. body.push_back(':');
  10976. body.append(h.second);
  10977. body.push_back('\n');
  10978. }
  10979. res.set_content(body, "text/plain");
  10980. });
  10981. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10982. std::string body;
  10983. for (const auto &h : req.headers) {
  10984. body.append(h.first);
  10985. body.push_back(':');
  10986. body.append(h.second);
  10987. body.push_back('\n');
  10988. }
  10989. res.set_content(body, "text/plain");
  10990. });
  10991. port_ = svr_.bind_to_any_port("127.0.0.1");
  10992. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  10993. svr_.wait_until_ready();
  10994. }
  10995. void TearDown() override {
  10996. svr_.stop();
  10997. if (thread_.joinable()) thread_.join();
  10998. }
  10999. Server svr_;
  11000. std::thread thread_;
  11001. int port_ = 0;
  11002. };
  11003. TEST_F(OpenStreamTest, Basic) {
  11004. Client cli("127.0.0.1", port_);
  11005. auto handle = cli.open_stream("GET", "/hello");
  11006. EXPECT_TRUE(handle.is_valid());
  11007. EXPECT_EQ("Hello World!", read_all(handle));
  11008. }
  11009. TEST_F(OpenStreamTest, SmallBuffer) {
  11010. Client cli("127.0.0.1", port_);
  11011. auto handle = cli.open_stream("GET", "/hello");
  11012. std::string result;
  11013. char buf[4];
  11014. ssize_t n;
  11015. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11016. result.append(buf, static_cast<size_t>(n));
  11017. EXPECT_EQ("Hello World!", result);
  11018. }
  11019. TEST_F(OpenStreamTest, DefaultHeaders) {
  11020. Client cli("127.0.0.1", port_);
  11021. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11022. {
  11023. auto handle = cli.open_stream("GET", "/echo-headers");
  11024. ASSERT_TRUE(handle.is_valid());
  11025. auto body = read_all(handle);
  11026. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11027. std::string::npos);
  11028. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11029. std::string::npos);
  11030. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11031. }
  11032. // open_stream POST with body and no explicit content_type should NOT add
  11033. // text/plain Content-Type (behavior differs from non-streaming path), but
  11034. // should include Content-Length
  11035. {
  11036. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11037. ASSERT_TRUE(handle.is_valid());
  11038. auto body = read_all(handle);
  11039. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11040. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11041. }
  11042. // open_stream POST with explicit Content-Type should preserve it
  11043. {
  11044. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11045. {{"Content-Type", "application/custom"}},
  11046. "{}", "application/custom");
  11047. ASSERT_TRUE(handle.is_valid());
  11048. auto body = read_all(handle);
  11049. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11050. }
  11051. // User-specified User-Agent must not be overwritten for stream API
  11052. {
  11053. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11054. {{"User-Agent", "MyAgent/1.2"}});
  11055. ASSERT_TRUE(handle.is_valid());
  11056. auto body = read_all(handle);
  11057. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11058. }
  11059. }
  11060. TEST_F(OpenStreamTest, Large) {
  11061. Client cli("127.0.0.1", port_);
  11062. auto handle = cli.open_stream("GET", "/large");
  11063. EXPECT_EQ(10000u, read_all(handle).size());
  11064. }
  11065. TEST_F(OpenStreamTest, ConnectionError) {
  11066. Client cli("127.0.0.1", 9999);
  11067. auto handle = cli.open_stream("GET", "/hello");
  11068. EXPECT_FALSE(handle.is_valid());
  11069. }
  11070. TEST_F(OpenStreamTest, Chunked) {
  11071. Client cli("127.0.0.1", port_);
  11072. auto handle = cli.open_stream("GET", "/chunked");
  11073. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11074. "Transfer-Encoding") == "chunked");
  11075. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11076. }
  11077. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11078. Client cli("127.0.0.1", port_);
  11079. auto handle =
  11080. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11081. ASSERT_TRUE(handle.is_valid());
  11082. // Consume body to allow trailers to be received/parsed
  11083. auto body = read_all(handle);
  11084. // Explicitly parse trailers (ensure trailers are available for assertion)
  11085. handle.parse_trailers_if_needed();
  11086. EXPECT_EQ(std::string("123456789"), body);
  11087. // The response should include a Trailer header declaring both names
  11088. ASSERT_TRUE(handle.response);
  11089. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11090. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11091. handle.response->get_header_value("Trailer"));
  11092. // Prohibited trailer must not be present
  11093. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11094. // Allowed trailer should be present
  11095. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11096. EXPECT_EQ(std::string("yes"),
  11097. handle.response->get_trailer_value("X-Allowed"));
  11098. // Verify trailers are NOT present as regular headers
  11099. EXPECT_EQ(std::string(""),
  11100. handle.response->get_header_value("Content-Length"));
  11101. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11102. }
  11103. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11104. TEST_F(OpenStreamTest, Gzip) {
  11105. Client cli("127.0.0.1", port_);
  11106. auto handle = cli.open_stream("GET", "/compressible", {},
  11107. {{"Accept-Encoding", "gzip"}});
  11108. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11109. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11110. }
  11111. #endif
  11112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11113. TEST_F(OpenStreamTest, Brotli) {
  11114. Client cli("127.0.0.1", port_);
  11115. auto handle =
  11116. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11117. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11118. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11119. }
  11120. #endif
  11121. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11122. TEST_F(OpenStreamTest, Zstd) {
  11123. Client cli("127.0.0.1", port_);
  11124. auto handle = cli.open_stream("GET", "/compressible", {},
  11125. {{"Accept-Encoding", "zstd"}});
  11126. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11127. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11128. }
  11129. #endif
  11130. #ifdef CPPHTTPLIB_SSL_ENABLED
  11131. class SSLOpenStreamTest : public ::testing::Test {
  11132. protected:
  11133. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11134. void SetUp() override {
  11135. svr_.Get("/hello", [](const Request &, Response &res) {
  11136. res.set_content("Hello SSL World!", "text/plain");
  11137. });
  11138. svr_.Get("/chunked", [](const Request &, Response &res) {
  11139. res.set_chunked_content_provider("text/plain",
  11140. [](size_t offset, DataSink &sink) {
  11141. if (offset < 15) {
  11142. sink.write("chunk", 5);
  11143. return true;
  11144. }
  11145. sink.done();
  11146. return true;
  11147. });
  11148. });
  11149. svr_.Post("/echo", [](const Request &req, Response &res) {
  11150. res.set_content(req.body, req.get_header_value("Content-Type"));
  11151. });
  11152. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11153. std::string body = req.body;
  11154. res.set_chunked_content_provider(
  11155. "text/plain", [body](size_t offset, DataSink &sink) {
  11156. if (offset < body.size()) {
  11157. sink.write(body.data() + offset, body.size() - offset);
  11158. }
  11159. sink.done();
  11160. return true;
  11161. });
  11162. });
  11163. port_ = svr_.bind_to_any_port("127.0.0.1");
  11164. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11165. svr_.wait_until_ready();
  11166. }
  11167. void TearDown() override {
  11168. svr_.stop();
  11169. if (thread_.joinable()) thread_.join();
  11170. }
  11171. SSLServer svr_;
  11172. std::thread thread_;
  11173. int port_ = 0;
  11174. };
  11175. TEST_F(SSLOpenStreamTest, Basic) {
  11176. SSLClient cli("127.0.0.1", port_);
  11177. cli.enable_server_certificate_verification(false);
  11178. auto handle = cli.open_stream("GET", "/hello");
  11179. ASSERT_TRUE(handle.is_valid());
  11180. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11181. }
  11182. TEST_F(SSLOpenStreamTest, Chunked) {
  11183. SSLClient cli("127.0.0.1", port_);
  11184. cli.enable_server_certificate_verification(false);
  11185. auto handle = cli.open_stream("GET", "/chunked");
  11186. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11187. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11188. "Transfer-Encoding") == "chunked");
  11189. auto body = read_all(handle);
  11190. EXPECT_EQ("chunkchunkchunk", body);
  11191. }
  11192. TEST_F(SSLOpenStreamTest, Post) {
  11193. SSLClient cli("127.0.0.1", port_);
  11194. cli.enable_server_certificate_verification(false);
  11195. auto handle =
  11196. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11197. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11198. EXPECT_EQ(200, handle.response->status);
  11199. auto body = read_all(handle);
  11200. EXPECT_EQ("Hello SSL POST", body);
  11201. }
  11202. TEST_F(SSLOpenStreamTest, PostChunked) {
  11203. SSLClient cli("127.0.0.1", port_);
  11204. cli.enable_server_certificate_verification(false);
  11205. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11206. "Chunked SSL Data", "text/plain");
  11207. ASSERT_TRUE(handle.is_valid());
  11208. EXPECT_EQ(200, handle.response->status);
  11209. auto body = read_all(handle);
  11210. EXPECT_EQ("Chunked SSL Data", body);
  11211. }
  11212. #endif // CPPHTTPLIB_SSL_ENABLED
  11213. //==============================================================================
  11214. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11215. // results for various scenarios.
  11216. //==============================================================================
  11217. TEST(ParityTest, GetVsOpenStream) {
  11218. Server svr;
  11219. const std::string path = "/parity";
  11220. const std::string content = "Parity test content: hello world";
  11221. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11222. res.set_content(content, "text/plain");
  11223. });
  11224. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11225. auto se = detail::scope_exit([&] {
  11226. svr.stop();
  11227. t.join();
  11228. ASSERT_FALSE(svr.is_running());
  11229. });
  11230. svr.wait_until_ready();
  11231. Client cli(HOST, PORT);
  11232. // Non-stream path
  11233. auto r1 = cli.Get(path);
  11234. ASSERT_TRUE(r1);
  11235. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11236. // Stream path
  11237. auto h = cli.open_stream("GET", path);
  11238. ASSERT_TRUE(h.is_valid());
  11239. EXPECT_EQ(r1->body, read_all(h));
  11240. }
  11241. // Helper to compress data with provided compressor type T
  11242. template <typename Compressor>
  11243. static std::string compress_payload_for_parity(const std::string &in) {
  11244. std::string out;
  11245. Compressor compressor;
  11246. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11247. [&](const char *data, size_t n) {
  11248. out.append(data, n);
  11249. return true;
  11250. });
  11251. EXPECT_TRUE(ok);
  11252. return out;
  11253. }
  11254. // Helper function for compression parity tests
  11255. template <typename Compressor>
  11256. static void test_compression_parity(const std::string &original,
  11257. const std::string &path,
  11258. const std::string &encoding) {
  11259. const std::string compressed =
  11260. compress_payload_for_parity<Compressor>(original);
  11261. Server svr;
  11262. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11263. res.set_content(compressed, "application/octet-stream");
  11264. res.set_header("Content-Encoding", encoding);
  11265. });
  11266. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. t.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. Client cli(HOST, PORT);
  11274. // Non-streaming
  11275. {
  11276. auto res = cli.Get(path);
  11277. ASSERT_TRUE(res);
  11278. EXPECT_EQ(StatusCode::OK_200, res->status);
  11279. EXPECT_EQ(original, res->body);
  11280. }
  11281. // Streaming
  11282. {
  11283. auto h = cli.open_stream("GET", path);
  11284. ASSERT_TRUE(h.is_valid());
  11285. EXPECT_EQ(original, read_all(h));
  11286. }
  11287. }
  11288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11289. TEST(ParityTest, Gzip) {
  11290. test_compression_parity<detail::gzip_compressor>(
  11291. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11292. }
  11293. #endif
  11294. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11295. TEST(ParityTest, Brotli) {
  11296. test_compression_parity<detail::brotli_compressor>(
  11297. "Hello, brotli parity test payload", "/parity-br", "br");
  11298. }
  11299. #endif
  11300. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11301. TEST(ParityTest, Zstd) {
  11302. test_compression_parity<detail::zstd_compressor>(
  11303. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11304. }
  11305. #endif
  11306. //==============================================================================
  11307. // New Stream API Tests
  11308. //==============================================================================
  11309. inline std::string read_body(httplib::stream::Result &result) {
  11310. std::string body;
  11311. while (result.next()) {
  11312. body.append(result.data(), result.size());
  11313. }
  11314. return body;
  11315. }
  11316. TEST(ClientConnectionTest, Basic) {
  11317. httplib::ClientConnection conn;
  11318. EXPECT_FALSE(conn.is_open());
  11319. conn.sock = 1;
  11320. EXPECT_TRUE(conn.is_open());
  11321. httplib::ClientConnection conn2(std::move(conn));
  11322. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11323. conn2.sock = INVALID_SOCKET;
  11324. }
  11325. // Unified test server for all stream::* tests
  11326. class StreamApiTest : public ::testing::Test {
  11327. protected:
  11328. void SetUp() override {
  11329. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11330. res.set_content("Hello World!", "text/plain");
  11331. });
  11332. svr_.Get("/echo-params",
  11333. [](const httplib::Request &req, httplib::Response &res) {
  11334. std::string r;
  11335. for (const auto &p : req.params) {
  11336. if (!r.empty()) r += "&";
  11337. r += p.first + "=" + p.second;
  11338. }
  11339. res.set_content(r, "text/plain");
  11340. });
  11341. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11342. res.set_content(req.body, req.get_header_value("Content-Type"));
  11343. });
  11344. svr_.Post("/echo-headers",
  11345. [](const httplib::Request &req, httplib::Response &res) {
  11346. std::string r;
  11347. for (const auto &h : req.headers)
  11348. r += h.first + ": " + h.second + "\n";
  11349. res.set_content(r, "text/plain");
  11350. });
  11351. svr_.Post("/echo-params",
  11352. [](const httplib::Request &req, httplib::Response &res) {
  11353. std::string r = "params:";
  11354. for (const auto &p : req.params)
  11355. r += p.first + "=" + p.second + ";";
  11356. res.set_content(r + " body:" + req.body, "text/plain");
  11357. });
  11358. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11359. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11360. });
  11361. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11362. res.set_content("PUT:" + req.body, "text/plain");
  11363. });
  11364. svr_.Patch("/echo",
  11365. [](const httplib::Request &req, httplib::Response &res) {
  11366. res.set_content("PATCH:" + req.body, "text/plain");
  11367. });
  11368. svr_.Delete(
  11369. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11370. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11371. "text/plain");
  11372. });
  11373. svr_.Get("/head-test",
  11374. [](const httplib::Request &, httplib::Response &res) {
  11375. res.set_content("body for HEAD", "text/plain");
  11376. });
  11377. svr_.Options("/options",
  11378. [](const httplib::Request &, httplib::Response &res) {
  11379. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11380. });
  11381. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11382. svr_.wait_until_ready();
  11383. }
  11384. void TearDown() override {
  11385. svr_.stop();
  11386. if (thread_.joinable()) thread_.join();
  11387. }
  11388. httplib::Server svr_;
  11389. std::thread thread_;
  11390. };
  11391. // stream::Get tests
  11392. TEST_F(StreamApiTest, GetBasic) {
  11393. httplib::Client cli(HOST, PORT);
  11394. auto result = httplib::stream::Get(cli, "/hello");
  11395. ASSERT_TRUE(result.is_valid());
  11396. EXPECT_EQ(200, result.status());
  11397. EXPECT_EQ("Hello World!", read_body(result));
  11398. }
  11399. TEST_F(StreamApiTest, GetWithParams) {
  11400. httplib::Client cli(HOST, PORT);
  11401. httplib::Params params{{"foo", "bar"}};
  11402. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11403. ASSERT_TRUE(result.is_valid());
  11404. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11405. }
  11406. TEST_F(StreamApiTest, GetConnectionError) {
  11407. httplib::Client cli(HOST, 9999);
  11408. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11409. }
  11410. TEST_F(StreamApiTest, Get404) {
  11411. httplib::Client cli(HOST, PORT);
  11412. auto result = httplib::stream::Get(cli, "/nonexistent");
  11413. EXPECT_TRUE(result.is_valid());
  11414. EXPECT_EQ(404, result.status());
  11415. }
  11416. // stream::Post tests
  11417. TEST_F(StreamApiTest, PostBasic) {
  11418. httplib::Client cli(HOST, PORT);
  11419. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11420. "application/json");
  11421. ASSERT_TRUE(result.is_valid());
  11422. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11423. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11424. }
  11425. TEST_F(StreamApiTest, PostWithHeaders) {
  11426. httplib::Client cli(HOST, PORT);
  11427. httplib::Headers headers{{"X-Custom", "value"}};
  11428. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11429. "text/plain");
  11430. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11431. }
  11432. TEST_F(StreamApiTest, PostWithParams) {
  11433. httplib::Client cli(HOST, PORT);
  11434. httplib::Params params{{"k", "v"}};
  11435. auto result =
  11436. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11437. auto body = read_body(result);
  11438. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11439. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11440. }
  11441. TEST_F(StreamApiTest, PostLarge) {
  11442. httplib::Client cli(HOST, PORT);
  11443. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11444. size_t total = 0;
  11445. while (result.next()) {
  11446. total += result.size();
  11447. }
  11448. EXPECT_EQ(100u * 1024u, total);
  11449. }
  11450. // stream::Put/Patch tests
  11451. TEST_F(StreamApiTest, PutAndPatch) {
  11452. httplib::Client cli(HOST, PORT);
  11453. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11454. EXPECT_EQ("PUT:test", read_body(put));
  11455. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11456. EXPECT_EQ("PATCH:test", read_body(patch));
  11457. }
  11458. // stream::Delete tests
  11459. TEST_F(StreamApiTest, Delete) {
  11460. httplib::Client cli(HOST, PORT);
  11461. auto del1 = httplib::stream::Delete(cli, "/resource");
  11462. EXPECT_EQ("Deleted", read_body(del1));
  11463. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11464. EXPECT_EQ("Deleted:data", read_body(del2));
  11465. }
  11466. // stream::Head/Options tests
  11467. TEST_F(StreamApiTest, HeadAndOptions) {
  11468. httplib::Client cli(HOST, PORT);
  11469. auto head = httplib::stream::Head(cli, "/head-test");
  11470. EXPECT_TRUE(head.is_valid());
  11471. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11472. auto opts = httplib::stream::Options(cli, "/options");
  11473. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11474. }
  11475. // SSL stream::* tests
  11476. #ifdef CPPHTTPLIB_SSL_ENABLED
  11477. class SSLStreamApiTest : public ::testing::Test {
  11478. protected:
  11479. void SetUp() override {
  11480. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11481. res.set_content("Hello SSL!", "text/plain");
  11482. });
  11483. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11484. res.set_content(req.body, "text/plain");
  11485. });
  11486. port_ = svr_.bind_to_any_port("127.0.0.1");
  11487. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11488. svr_.wait_until_ready();
  11489. }
  11490. void TearDown() override {
  11491. svr_.stop();
  11492. if (thread_.joinable()) thread_.join();
  11493. }
  11494. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11495. std::thread thread_;
  11496. int port_ = 0;
  11497. };
  11498. TEST_F(SSLStreamApiTest, GetAndPost) {
  11499. httplib::SSLClient cli("127.0.0.1", port_);
  11500. cli.enable_server_certificate_verification(false);
  11501. auto get = httplib::stream::Get(cli, "/hello");
  11502. EXPECT_EQ("Hello SSL!", read_body(get));
  11503. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11504. EXPECT_EQ("test", read_body(post));
  11505. }
  11506. #endif
  11507. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11508. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11509. // BodyReader
  11510. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11511. // Test that read timeout during streaming is detected
  11512. // Use a large content-length response where server delays mid-stream
  11513. Server svr;
  11514. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11515. // Send a large response with delay in the middle
  11516. res.set_content_provider(
  11517. 1000, // content_length
  11518. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11519. if (offset < 100) {
  11520. // Send first 100 bytes immediately
  11521. std::string data(100, 'A');
  11522. sink.write(data.c_str(), data.size());
  11523. return true;
  11524. }
  11525. // Then delay longer than client timeout
  11526. std::this_thread::sleep_for(std::chrono::seconds(3));
  11527. std::string data(900, 'B');
  11528. sink.write(data.c_str(), data.size());
  11529. return true;
  11530. });
  11531. });
  11532. auto port = 8091;
  11533. std::thread t([&]() { svr.listen("localhost", port); });
  11534. svr.wait_until_ready();
  11535. Client cli("localhost", port);
  11536. cli.set_read_timeout(1, 0); // 1 second timeout
  11537. auto handle = cli.open_stream("GET", "/slow-stream");
  11538. ASSERT_TRUE(handle.is_valid());
  11539. char buf[256];
  11540. ssize_t total = 0;
  11541. ssize_t n;
  11542. bool got_error = false;
  11543. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11544. total += n;
  11545. }
  11546. if (n < 0) {
  11547. got_error = true;
  11548. // Should be timeout or read error
  11549. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11550. handle.get_read_error() == Error::Read)
  11551. << "Actual error: " << to_string(handle.get_read_error());
  11552. }
  11553. // Either we got an error, or we got less data than expected
  11554. EXPECT_TRUE(got_error || total < 1000)
  11555. << "Expected timeout but got all " << total << " bytes";
  11556. svr.stop();
  11557. t.join();
  11558. }
  11559. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11560. // Test connection closed detection via BodyReader
  11561. Server svr;
  11562. std::atomic<bool> close_now{false};
  11563. svr.Get("/will-close", [&](const Request &, Response &res) {
  11564. res.set_content_provider(
  11565. 10000, // Large content_length that we won't fully send
  11566. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11567. if (offset < 100) {
  11568. std::string data(100, 'X');
  11569. sink.write(data.c_str(), data.size());
  11570. return true;
  11571. }
  11572. // Wait for signal then abort
  11573. while (!close_now) {
  11574. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11575. }
  11576. return false; // Abort - server will close connection
  11577. });
  11578. });
  11579. auto port = 8092;
  11580. std::thread t([&]() { svr.listen("localhost", port); });
  11581. svr.wait_until_ready();
  11582. Client cli("localhost", port);
  11583. auto handle = cli.open_stream("GET", "/will-close");
  11584. ASSERT_TRUE(handle.is_valid());
  11585. char buf[256];
  11586. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11587. EXPECT_GT(n, 0) << "First read should succeed";
  11588. // Signal server to close
  11589. close_now = true;
  11590. // Keep reading until error or EOF
  11591. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11592. // Keep reading
  11593. }
  11594. // Should get an error since content_length wasn't satisfied
  11595. if (n < 0) {
  11596. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11597. handle.get_read_error() == Error::Read)
  11598. << "Actual error: " << to_string(handle.get_read_error());
  11599. }
  11600. svr.stop();
  11601. t.join();
  11602. }
  11603. #ifdef CPPHTTPLIB_SSL_ENABLED
  11604. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11605. // Test that read timeout during SSL streaming is detected
  11606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11607. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11608. res.set_content_provider(
  11609. 1000, "text/plain",
  11610. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11611. if (offset < 100) {
  11612. std::string data(100, 'A');
  11613. sink.write(data.c_str(), data.size());
  11614. return true;
  11615. }
  11616. std::this_thread::sleep_for(std::chrono::seconds(3));
  11617. std::string data(900, 'B');
  11618. sink.write(data.c_str(), data.size());
  11619. return true;
  11620. });
  11621. });
  11622. auto port = 8093;
  11623. std::thread t([&]() { svr.listen("localhost", port); });
  11624. svr.wait_until_ready();
  11625. SSLClient cli("localhost", port);
  11626. cli.enable_server_certificate_verification(false);
  11627. cli.set_read_timeout(1, 0); // 1 second timeout
  11628. auto handle = cli.open_stream("GET", "/slow-stream");
  11629. ASSERT_TRUE(handle.is_valid());
  11630. char buf[256];
  11631. ssize_t total = 0;
  11632. ssize_t n;
  11633. bool got_error = false;
  11634. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11635. total += n;
  11636. }
  11637. if (n < 0) {
  11638. got_error = true;
  11639. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11640. handle.get_read_error() == Error::Read)
  11641. << "Actual error: " << to_string(handle.get_read_error());
  11642. }
  11643. EXPECT_TRUE(got_error || total < 1000)
  11644. << "Expected timeout but got all " << total << " bytes";
  11645. svr.stop();
  11646. t.join();
  11647. }
  11648. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11649. // Test SSL connection closed detection
  11650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11651. std::atomic<bool> close_now{false};
  11652. svr.Get("/will-close", [&](const Request &, Response &res) {
  11653. res.set_content_provider(
  11654. 10000, "text/plain",
  11655. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11656. if (offset < 100) {
  11657. std::string data(100, 'X');
  11658. sink.write(data.c_str(), data.size());
  11659. return true;
  11660. }
  11661. while (!close_now) {
  11662. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11663. }
  11664. return false;
  11665. });
  11666. });
  11667. auto port = 8094;
  11668. std::thread t([&]() { svr.listen("localhost", port); });
  11669. svr.wait_until_ready();
  11670. SSLClient cli("localhost", port);
  11671. cli.enable_server_certificate_verification(false);
  11672. auto handle = cli.open_stream("GET", "/will-close");
  11673. ASSERT_TRUE(handle.is_valid());
  11674. char buf[256];
  11675. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11676. EXPECT_GT(n, 0);
  11677. // Signal server to close
  11678. close_now = true;
  11679. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11680. // Keep reading
  11681. }
  11682. if (n < 0) {
  11683. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11684. handle.get_read_error() == Error::Read)
  11685. << "Actual error: " << to_string(handle.get_read_error());
  11686. }
  11687. svr.stop();
  11688. t.join();
  11689. }
  11690. #endif
  11691. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11692. using namespace httplib;
  11693. // Create a test file
  11694. const char *fname = "etag_testfile.txt";
  11695. const char *content = "etag-content";
  11696. {
  11697. std::ofstream ofs(fname);
  11698. ofs << content;
  11699. ASSERT_TRUE(ofs.good());
  11700. }
  11701. Server svr;
  11702. svr.set_mount_point("/static", ".");
  11703. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11704. svr.wait_until_ready();
  11705. Client cli(HOST, PORT);
  11706. // First request: should get 200 with ETag header
  11707. auto res1 = cli.Get("/static/etag_testfile.txt");
  11708. ASSERT_TRUE(res1);
  11709. ASSERT_EQ(200, res1->status);
  11710. ASSERT_TRUE(res1->has_header("ETag"));
  11711. std::string etag = res1->get_header_value("ETag");
  11712. EXPECT_FALSE(etag.empty());
  11713. // Verify ETag format: W/"hex-hex"
  11714. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11715. EXPECT_EQ('W', etag[0]);
  11716. EXPECT_EQ('/', etag[1]);
  11717. EXPECT_EQ('"', etag[2]);
  11718. EXPECT_EQ('"', etag.back());
  11719. // Exact match: expect 304 Not Modified
  11720. Headers h2 = {{"If-None-Match", etag}};
  11721. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11722. ASSERT_TRUE(res2);
  11723. EXPECT_EQ(304, res2->status);
  11724. // Wildcard match: expect 304 Not Modified
  11725. Headers h3 = {{"If-None-Match", "*"}};
  11726. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11727. ASSERT_TRUE(res3);
  11728. EXPECT_EQ(304, res3->status);
  11729. // Non-matching ETag: expect 200
  11730. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11731. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11732. ASSERT_TRUE(res4);
  11733. EXPECT_EQ(200, res4->status);
  11734. // Multiple ETags with one matching: expect 304
  11735. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11736. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11737. ASSERT_TRUE(res5);
  11738. EXPECT_EQ(304, res5->status);
  11739. svr.stop();
  11740. t.join();
  11741. std::remove(fname);
  11742. }
  11743. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11744. using namespace httplib;
  11745. Server svr;
  11746. svr.set_mount_point("/static", ".");
  11747. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11748. svr.wait_until_ready();
  11749. Client cli(HOST, PORT);
  11750. // Send If-None-Match: * to a non-existent file
  11751. Headers h = {{"If-None-Match", "*"}};
  11752. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11753. ASSERT_TRUE(res);
  11754. EXPECT_EQ(404, res->status);
  11755. svr.stop();
  11756. t.join();
  11757. }
  11758. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  11759. using namespace httplib;
  11760. // Create a test file
  11761. const char *fname = "etag_boundary_testfile.txt";
  11762. const char *content = "boundary-test";
  11763. {
  11764. std::ofstream ofs(fname);
  11765. ofs << content;
  11766. ASSERT_TRUE(ofs.good());
  11767. }
  11768. Server svr;
  11769. svr.set_mount_point("/static", ".");
  11770. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11771. svr.wait_until_ready();
  11772. Client cli(HOST, PORT);
  11773. // Get the actual ETag
  11774. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  11775. ASSERT_TRUE(res1);
  11776. ASSERT_EQ(200, res1->status);
  11777. ASSERT_TRUE(res1->has_header("ETag"));
  11778. std::string etag = res1->get_header_value("ETag");
  11779. // Test 1: Very long ETag value (longer than actual ETag)
  11780. // Should NOT match and return 200 (not trigger out-of-bounds read)
  11781. Headers h1 = {{"If-None-Match", "W/"
  11782. "\"very-long-etag-value-that-is-much-longer-"
  11783. "than-the-actual-etag-value\""}};
  11784. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  11785. ASSERT_TRUE(res2);
  11786. EXPECT_EQ(200, res2->status); // Should not match
  11787. // Test 2: Long string followed by wildcard
  11788. // Should match on "*" and return 304 (without out-of-bounds read on the long
  11789. // string)
  11790. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  11791. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  11792. ASSERT_TRUE(res3);
  11793. EXPECT_EQ(304, res3->status); // Should match on "*"
  11794. // Test 3: Wildcard followed by long string
  11795. // Should match on "*" immediately and return 304
  11796. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  11797. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  11798. ASSERT_TRUE(res4);
  11799. EXPECT_EQ(304, res4->status); // Should match on "*"
  11800. // Test 4: Multiple long non-matching values
  11801. // Should NOT match and return 200 (test that all comparisons are safe)
  11802. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  11803. "W/\"second-long-non-matching-value\", "
  11804. "W/\"third-long-non-matching-value\""}};
  11805. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  11806. ASSERT_TRUE(res5);
  11807. EXPECT_EQ(200, res5->status); // Should not match
  11808. // Test 5: Single character that is not "*" (edge case)
  11809. Headers h5 = {{"If-None-Match", "X"}};
  11810. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  11811. ASSERT_TRUE(res6);
  11812. EXPECT_EQ(200, res6->status); // Should not match
  11813. svr.stop();
  11814. t.join();
  11815. std::remove(fname);
  11816. }
  11817. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11818. using namespace httplib;
  11819. // Create a test file
  11820. const char *fname = "ims_testfile.txt";
  11821. const char *content = "if-modified-since-test";
  11822. {
  11823. std::ofstream ofs(fname);
  11824. ofs << content;
  11825. ASSERT_TRUE(ofs.good());
  11826. }
  11827. Server svr;
  11828. svr.set_mount_point("/static", ".");
  11829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11830. svr.wait_until_ready();
  11831. Client cli(HOST, PORT);
  11832. // First request: should get 200 with Last-Modified header
  11833. auto res1 = cli.Get("/static/ims_testfile.txt");
  11834. ASSERT_TRUE(res1);
  11835. ASSERT_EQ(200, res1->status);
  11836. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11837. std::string last_modified = res1->get_header_value("Last-Modified");
  11838. EXPECT_FALSE(last_modified.empty());
  11839. // If-Modified-Since with same time: expect 304
  11840. Headers h2 = {{"If-Modified-Since", last_modified}};
  11841. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11842. ASSERT_TRUE(res2);
  11843. EXPECT_EQ(304, res2->status);
  11844. // If-Modified-Since with future time: expect 304
  11845. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11846. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11847. ASSERT_TRUE(res3);
  11848. EXPECT_EQ(304, res3->status);
  11849. // If-Modified-Since with past time: expect 200
  11850. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11851. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11852. ASSERT_TRUE(res4);
  11853. EXPECT_EQ(200, res4->status);
  11854. // If-None-Match takes precedence over If-Modified-Since
  11855. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11856. ASSERT_TRUE(res1->has_header("ETag"));
  11857. std::string etag = res1->get_header_value("ETag");
  11858. Headers h5 = {{"If-None-Match", etag},
  11859. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11860. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11861. ASSERT_TRUE(res5);
  11862. EXPECT_EQ(304, res5->status);
  11863. svr.stop();
  11864. t.join();
  11865. std::remove(fname);
  11866. }
  11867. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11868. using namespace httplib;
  11869. Server svr;
  11870. // Endpoint that returns compressible content
  11871. svr.Get("/compressible", [](const Request &, Response &res) {
  11872. // Return a large enough body to trigger compression
  11873. std::string body(1000, 'a');
  11874. res.set_content(body, "text/plain");
  11875. });
  11876. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11877. svr.wait_until_ready();
  11878. Client cli(HOST, PORT);
  11879. // Request with gzip support: should get Vary header when compressed
  11880. cli.set_compress(true);
  11881. auto res1 = cli.Get("/compressible");
  11882. ASSERT_TRUE(res1);
  11883. EXPECT_EQ(200, res1->status);
  11884. // If Content-Encoding is set, Vary should also be set
  11885. if (res1->has_header("Content-Encoding")) {
  11886. EXPECT_TRUE(res1->has_header("Vary"));
  11887. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11888. }
  11889. // Request without Accept-Encoding header: should not have compression
  11890. Headers h_no_compress;
  11891. auto res2 = cli.Get("/compressible", h_no_compress);
  11892. ASSERT_TRUE(res2);
  11893. EXPECT_EQ(200, res2->status);
  11894. // Verify Vary header is present when compression is applied
  11895. // (the exact behavior depends on server configuration)
  11896. svr.stop();
  11897. t.join();
  11898. }
  11899. TEST(ETagTest, IfRangeWithETag) {
  11900. using namespace httplib;
  11901. // Create a test file with known content
  11902. const char *fname = "if_range_testfile.txt";
  11903. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11904. {
  11905. std::ofstream ofs(fname);
  11906. ofs << content;
  11907. ASSERT_TRUE(ofs.good());
  11908. }
  11909. Server svr;
  11910. svr.set_mount_point("/static", ".");
  11911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11912. svr.wait_until_ready();
  11913. Client cli(HOST, PORT);
  11914. // First request: get ETag
  11915. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11916. ASSERT_TRUE(res1);
  11917. ASSERT_EQ(200, res1->status);
  11918. ASSERT_TRUE(res1->has_header("ETag"));
  11919. std::string etag = res1->get_header_value("ETag");
  11920. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11921. // Since our server generates weak ETags (W/"..."), If-Range with our
  11922. // ETag should NOT result in partial content - it should return full content.
  11923. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11924. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11925. ASSERT_TRUE(res2);
  11926. // Weak ETag in If-Range -> full content (200), not partial (206)
  11927. EXPECT_EQ(200, res2->status);
  11928. EXPECT_EQ(content, res2->body);
  11929. EXPECT_FALSE(res2->has_header("Content-Range"));
  11930. // Range request with non-matching If-Range (ETag): should get 200 (full
  11931. // content)
  11932. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11933. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11934. ASSERT_TRUE(res3);
  11935. EXPECT_EQ(200, res3->status);
  11936. EXPECT_EQ(content, res3->body);
  11937. EXPECT_FALSE(res3->has_header("Content-Range"));
  11938. // Range request with strong ETag (hypothetical - our server doesn't generate
  11939. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11940. // should return full content)
  11941. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11942. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11943. ASSERT_TRUE(res4);
  11944. EXPECT_EQ(200, res4->status);
  11945. EXPECT_EQ(content, res4->body);
  11946. EXPECT_FALSE(res4->has_header("Content-Range"));
  11947. svr.stop();
  11948. t.join();
  11949. std::remove(fname);
  11950. }
  11951. TEST(ETagTest, IfRangeWithDate) {
  11952. using namespace httplib;
  11953. // Create a test file
  11954. const char *fname = "if_range_date_testfile.txt";
  11955. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11956. {
  11957. std::ofstream ofs(fname);
  11958. ofs << content;
  11959. ASSERT_TRUE(ofs.good());
  11960. }
  11961. Server svr;
  11962. svr.set_mount_point("/static", ".");
  11963. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11964. svr.wait_until_ready();
  11965. Client cli(HOST, PORT);
  11966. // First request: get Last-Modified
  11967. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11968. ASSERT_TRUE(res1);
  11969. ASSERT_EQ(200, res1->status);
  11970. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11971. std::string last_modified = res1->get_header_value("Last-Modified");
  11972. // Range request with matching If-Range (date): should get 206
  11973. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11974. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11975. ASSERT_TRUE(res2);
  11976. EXPECT_EQ(206, res2->status);
  11977. EXPECT_EQ("FGHIJ", res2->body);
  11978. // Range request with old If-Range date: should get 200 (full content)
  11979. Headers h3 = {{"Range", "bytes=5-9"},
  11980. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11981. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11982. ASSERT_TRUE(res3);
  11983. EXPECT_EQ(200, res3->status);
  11984. EXPECT_EQ(content, res3->body);
  11985. // Range request with future If-Range date: should get 206
  11986. Headers h4 = {{"Range", "bytes=0-4"},
  11987. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11988. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11989. ASSERT_TRUE(res4);
  11990. EXPECT_EQ(206, res4->status);
  11991. EXPECT_EQ("ABCDE", res4->body);
  11992. svr.stop();
  11993. t.join();
  11994. std::remove(fname);
  11995. }
  11996. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11997. using namespace httplib;
  11998. const char *fname = "etag_malformed.txt";
  11999. const char *content = "malformed-etag";
  12000. {
  12001. std::ofstream ofs(fname);
  12002. ofs << content;
  12003. ASSERT_TRUE(ofs.good());
  12004. }
  12005. Server svr;
  12006. svr.set_mount_point("/static", ".");
  12007. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12008. svr.wait_until_ready();
  12009. Client cli(HOST, PORT);
  12010. // baseline: should get 200 and an ETag
  12011. auto res1 = cli.Get("/static/etag_malformed.txt");
  12012. ASSERT_TRUE(res1);
  12013. ASSERT_EQ(200, res1->status);
  12014. ASSERT_TRUE(res1->has_header("ETag"));
  12015. // Malformed ETag value (missing quotes) should be treated as non-matching
  12016. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12017. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12018. ASSERT_TRUE(res_bad);
  12019. EXPECT_EQ(200, res_bad->status);
  12020. // Whitespace-only header value should be considered invalid / non-matching
  12021. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12022. "Host: localhost\r\n"
  12023. "If-None-Match: \r\n"
  12024. "Connection: close\r\n"
  12025. "\r\n";
  12026. std::string out;
  12027. ASSERT_TRUE(send_request(5, raw_req, &out));
  12028. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12029. svr.stop();
  12030. t.join();
  12031. std::remove(fname);
  12032. }
  12033. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12034. using namespace httplib;
  12035. const char *fname = "ims_invalid_format.txt";
  12036. const char *content = "ims-bad-format";
  12037. {
  12038. std::ofstream ofs(fname);
  12039. ofs << content;
  12040. ASSERT_TRUE(ofs.good());
  12041. }
  12042. Server svr;
  12043. svr.set_mount_point("/static", ".");
  12044. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12045. svr.wait_until_ready();
  12046. Client cli(HOST, PORT);
  12047. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12048. ASSERT_TRUE(res1);
  12049. ASSERT_EQ(200, res1->status);
  12050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12051. // If-Modified-Since with invalid format should not result in 304
  12052. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12053. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12054. ASSERT_TRUE(res_bad);
  12055. EXPECT_EQ(200, res_bad->status);
  12056. // If-Range with invalid date format should be treated as mismatch -> full
  12057. // content (200)
  12058. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12059. {"If-Range", "invalid-date"}};
  12060. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12061. ASSERT_TRUE(res_ifrange);
  12062. EXPECT_EQ(200, res_ifrange->status);
  12063. svr.stop();
  12064. t.join();
  12065. std::remove(fname);
  12066. }
  12067. TEST(ETagTest, IfRangeWithMalformedETag) {
  12068. using namespace httplib;
  12069. const char *fname = "ifrange_malformed.txt";
  12070. const std::string content = "0123456789";
  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. // First request: get ETag
  12082. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12083. ASSERT_TRUE(res1);
  12084. ASSERT_EQ(200, res1->status);
  12085. ASSERT_TRUE(res1->has_header("ETag"));
  12086. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12087. // full content (200)
  12088. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12089. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12090. ASSERT_TRUE(res2);
  12091. EXPECT_EQ(200, res2->status);
  12092. EXPECT_EQ(content, res2->body);
  12093. svr.stop();
  12094. t.join();
  12095. std::remove(fname);
  12096. }
  12097. TEST(ETagTest, ExtremeLargeDateValues) {
  12098. using namespace httplib;
  12099. const char *fname = "ims_extreme_date.txt";
  12100. const char *content = "ims-extreme-date";
  12101. {
  12102. std::ofstream ofs(fname);
  12103. ofs << content;
  12104. ASSERT_TRUE(ofs.good());
  12105. }
  12106. Server svr;
  12107. svr.set_mount_point("/static", ".");
  12108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12109. svr.wait_until_ready();
  12110. Client cli(HOST, PORT);
  12111. auto res1 = cli.Get(std::string("/static/") + fname);
  12112. ASSERT_TRUE(res1);
  12113. ASSERT_EQ(200, res1->status);
  12114. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12115. // Extremely large year that may overflow date parsing routines.
  12116. Headers h_large_date = {
  12117. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12118. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12119. ASSERT_TRUE(res_bad);
  12120. // Expect server to treat this as invalid/mismatch and return full content
  12121. EXPECT_EQ(200, res_bad->status);
  12122. // If-Range with extremely large date should be treated as mismatch -> full
  12123. // content (200)
  12124. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12125. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12126. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12127. ASSERT_TRUE(res_ifrange);
  12128. EXPECT_EQ(200, res_ifrange->status);
  12129. svr.stop();
  12130. t.join();
  12131. std::remove(fname);
  12132. }
  12133. TEST(ETagTest, NegativeFileModificationTime) {
  12134. using namespace httplib;
  12135. const char *fname = "ims_negative_mtime.txt";
  12136. const std::string content = "negative-mtime";
  12137. {
  12138. std::ofstream ofs(fname);
  12139. ofs << content;
  12140. ASSERT_TRUE(ofs.good());
  12141. }
  12142. // Try to set file mtime to a negative value. This may fail on some
  12143. // platforms/filesystems; if it fails, the test will still verify server
  12144. // behaves safely by performing a regular conditional request.
  12145. #if defined(__APPLE__) || defined(__linux__)
  12146. bool set_negative = false;
  12147. do {
  12148. struct timeval times[2];
  12149. // access time: now
  12150. times[0].tv_sec = time(nullptr);
  12151. times[0].tv_usec = 0;
  12152. // modification time: negative (e.g., -1)
  12153. times[1].tv_sec = -1;
  12154. times[1].tv_usec = 0;
  12155. if (utimes(fname, times) == 0) { set_negative = true; }
  12156. } while (0);
  12157. #else
  12158. bool set_negative = false;
  12159. #endif
  12160. Server svr;
  12161. svr.set_mount_point("/static", ".");
  12162. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12163. svr.wait_until_ready();
  12164. Client cli(HOST, PORT);
  12165. auto res1 = cli.Get(std::string("/static/") + fname);
  12166. ASSERT_TRUE(res1);
  12167. ASSERT_EQ(200, res1->status);
  12168. bool has_last_modified = res1->has_header("Last-Modified");
  12169. std::string last_modified;
  12170. if (has_last_modified) {
  12171. last_modified = res1->get_header_value("Last-Modified");
  12172. }
  12173. if (set_negative) {
  12174. // If we successfully set a negative mtime, ensure server returns a
  12175. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12176. // with an old date and ensure server handles it without crash.
  12177. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12178. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12179. ASSERT_TRUE(res2);
  12180. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12181. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12182. } else {
  12183. // Could not set negative mtime on this platform; fall back to verifying
  12184. // that normal invalid/malformed dates are treated safely (non-304).
  12185. Headers h_bad_date = {
  12186. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12187. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12188. ASSERT_TRUE(res_bad);
  12189. EXPECT_EQ(200, res_bad->status);
  12190. }
  12191. svr.stop();
  12192. t.join();
  12193. std::remove(fname);
  12194. }
  12195. //==============================================================================
  12196. // SSE Parsing Tests
  12197. //==============================================================================
  12198. class SSEParsingTest : public ::testing::Test {
  12199. protected:
  12200. // Test helper that mimics SSE parsing behavior
  12201. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12202. int &retry_ms) {
  12203. // Blank line signals end of event
  12204. if (line.empty() || line == "\r") { return true; }
  12205. // Lines starting with ':' are comments (ignored)
  12206. if (!line.empty() && line[0] == ':') { return false; }
  12207. // Find the colon separator
  12208. auto colon_pos = line.find(':');
  12209. if (colon_pos == std::string::npos) {
  12210. // Line with no colon is treated as field name with empty value
  12211. return false;
  12212. }
  12213. std::string field = line.substr(0, colon_pos);
  12214. std::string value;
  12215. // Value starts after colon, skip optional single space
  12216. if (colon_pos + 1 < line.size()) {
  12217. size_t value_start = colon_pos + 1;
  12218. if (line[value_start] == ' ') { value_start++; }
  12219. value = line.substr(value_start);
  12220. // Remove trailing \r if present
  12221. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12222. }
  12223. // Handle known fields
  12224. if (field == "event") {
  12225. msg.event = value;
  12226. } else if (field == "data") {
  12227. // Multiple data lines are concatenated with newlines
  12228. if (!msg.data.empty()) { msg.data += "\n"; }
  12229. msg.data += value;
  12230. } else if (field == "id") {
  12231. // Empty id is valid (clears the last event ID)
  12232. msg.id = value;
  12233. } else if (field == "retry") {
  12234. // Parse retry interval in milliseconds
  12235. {
  12236. int v = 0;
  12237. auto res =
  12238. detail::from_chars(value.data(), value.data() + value.size(), v);
  12239. if (res.ec == std::errc{}) { retry_ms = v; }
  12240. }
  12241. }
  12242. // Unknown fields are ignored per SSE spec
  12243. return false;
  12244. }
  12245. };
  12246. // Test: Single-line data
  12247. TEST_F(SSEParsingTest, SingleLineData) {
  12248. sse::SSEMessage msg;
  12249. int retry_ms = 3000;
  12250. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12251. EXPECT_EQ(msg.data, "hello");
  12252. EXPECT_EQ(msg.event, "message");
  12253. // Blank line ends event
  12254. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12255. }
  12256. // Test: Multi-line data
  12257. TEST_F(SSEParsingTest, MultiLineData) {
  12258. sse::SSEMessage msg;
  12259. int retry_ms = 3000;
  12260. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12261. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12262. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12263. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12264. }
  12265. // Test: Custom event types
  12266. TEST_F(SSEParsingTest, CustomEventType) {
  12267. sse::SSEMessage msg;
  12268. int retry_ms = 3000;
  12269. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12270. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12271. EXPECT_EQ(msg.event, "update");
  12272. EXPECT_EQ(msg.data, "payload");
  12273. }
  12274. // Test: Event ID handling
  12275. TEST_F(SSEParsingTest, EventIdHandling) {
  12276. sse::SSEMessage msg;
  12277. int retry_ms = 3000;
  12278. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12279. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12280. EXPECT_EQ(msg.id, "12345");
  12281. }
  12282. // Test: Empty event ID (clears last event ID)
  12283. TEST_F(SSEParsingTest, EmptyEventId) {
  12284. sse::SSEMessage msg;
  12285. msg.id = "previous";
  12286. int retry_ms = 3000;
  12287. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12288. EXPECT_EQ(msg.id, "");
  12289. }
  12290. // Test: Retry field parsing
  12291. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12292. sse::SSEMessage msg;
  12293. int retry_ms = 3000;
  12294. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12295. EXPECT_EQ(retry_ms, 5000);
  12296. }
  12297. // Test: Invalid retry value
  12298. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12299. sse::SSEMessage msg;
  12300. int retry_ms = 3000;
  12301. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12302. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12303. }
  12304. // Test: Comments (lines starting with :)
  12305. TEST_F(SSEParsingTest, CommentsIgnored) {
  12306. sse::SSEMessage msg;
  12307. int retry_ms = 3000;
  12308. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12309. EXPECT_EQ(msg.data, "");
  12310. EXPECT_EQ(msg.event, "message");
  12311. }
  12312. // Test: Colon in value
  12313. TEST_F(SSEParsingTest, ColonInValue) {
  12314. sse::SSEMessage msg;
  12315. int retry_ms = 3000;
  12316. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12317. EXPECT_EQ(msg.data, "hello:world:test");
  12318. }
  12319. // Test: Line with no colon (field name only)
  12320. TEST_F(SSEParsingTest, FieldNameOnly) {
  12321. sse::SSEMessage msg;
  12322. int retry_ms = 3000;
  12323. // According to SSE spec, this is treated as field name with empty value
  12324. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12325. // Since we don't recognize "data" without colon, data should be empty
  12326. EXPECT_EQ(msg.data, "");
  12327. }
  12328. // Test: Trailing \r handling
  12329. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12330. sse::SSEMessage msg;
  12331. int retry_ms = 3000;
  12332. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12333. EXPECT_EQ(msg.data, "hello");
  12334. }
  12335. // Test: Unknown fields ignored
  12336. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12337. sse::SSEMessage msg;
  12338. int retry_ms = 3000;
  12339. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12340. EXPECT_EQ(msg.data, "");
  12341. EXPECT_EQ(msg.event, "message");
  12342. }
  12343. // Test: Space after colon is optional
  12344. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12345. sse::SSEMessage msg1, msg2;
  12346. int retry_ms = 3000;
  12347. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12348. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12349. EXPECT_EQ(msg1.data, "hello");
  12350. EXPECT_EQ(msg2.data, "hello");
  12351. }
  12352. // Test: SSEMessage clear
  12353. TEST_F(SSEParsingTest, MessageClear) {
  12354. sse::SSEMessage msg;
  12355. msg.event = "custom";
  12356. msg.data = "some data";
  12357. msg.id = "123";
  12358. msg.clear();
  12359. EXPECT_EQ(msg.event, "message");
  12360. EXPECT_EQ(msg.data, "");
  12361. EXPECT_EQ(msg.id, "");
  12362. }
  12363. // Test: Complete event parsing
  12364. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12365. sse::SSEMessage msg;
  12366. int retry_ms = 3000;
  12367. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12368. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12369. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12370. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12371. // Blank line ends event
  12372. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12373. EXPECT_EQ(msg.event, "notification");
  12374. EXPECT_EQ(msg.id, "evt-42");
  12375. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12376. EXPECT_EQ(retry_ms, 1000);
  12377. }
  12378. //==============================================================================
  12379. // Integration Tests with Server
  12380. //==============================================================================
  12381. class SSEIntegrationTest : public ::testing::Test {
  12382. protected:
  12383. void SetUp() override {
  12384. stop_server_.store(false);
  12385. events_.clear();
  12386. server_ = httplib::detail::make_unique<Server>();
  12387. setup_server();
  12388. start_server();
  12389. }
  12390. void TearDown() override {
  12391. stop_server_.store(true);
  12392. event_cv_.notify_all();
  12393. server_->stop();
  12394. if (server_thread_.joinable()) { server_thread_.join(); }
  12395. }
  12396. void setup_server() {
  12397. // Simple SSE endpoint
  12398. server_->Get("/events", [this](const Request &req, Response &res) {
  12399. auto last_id = req.get_header_value("Last-Event-ID");
  12400. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12401. res.set_chunked_content_provider(
  12402. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12403. std::unique_lock<std::mutex> lock(event_mutex_);
  12404. if (event_cv_.wait_for(
  12405. lock, std::chrono::milliseconds(200), [this] {
  12406. return !events_.empty() || stop_server_.load();
  12407. })) {
  12408. if (stop_server_.load()) { return false; }
  12409. if (!events_.empty()) {
  12410. std::string event = events_.front();
  12411. events_.erase(events_.begin());
  12412. sink.write(event.data(), event.size());
  12413. return true;
  12414. }
  12415. }
  12416. return !stop_server_.load();
  12417. });
  12418. });
  12419. // Endpoint that returns error
  12420. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12421. res.status = 500;
  12422. res.set_content("Internal Server Error", "text/plain");
  12423. });
  12424. // Endpoint for custom event types
  12425. server_->Get("/custom-events", [](const Request &, Response &res) {
  12426. res.set_chunked_content_provider(
  12427. "text/event-stream", [](size_t offset, DataSink &sink) {
  12428. if (offset == 0) {
  12429. std::string event = "event: update\ndata: updated\n\n"
  12430. "event: delete\ndata: deleted\n\n";
  12431. sink.write(event.data(), event.size());
  12432. }
  12433. return false; // End stream after sending
  12434. });
  12435. });
  12436. }
  12437. void start_server() {
  12438. port_ = server_->bind_to_any_port(HOST);
  12439. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12440. // Wait for server to start
  12441. while (!server_->is_running()) {
  12442. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12443. }
  12444. }
  12445. int get_port() const { return port_; }
  12446. void send_event(const std::string &event) {
  12447. std::lock_guard<std::mutex> lock(event_mutex_);
  12448. events_.push_back(event);
  12449. event_cv_.notify_all();
  12450. }
  12451. std::unique_ptr<Server> server_;
  12452. std::thread server_thread_;
  12453. std::mutex event_mutex_;
  12454. std::condition_variable event_cv_;
  12455. std::vector<std::string> events_;
  12456. std::atomic<bool> stop_server_{false};
  12457. std::string last_received_event_id_;
  12458. int port_ = 0;
  12459. };
  12460. // Test: Successful connection and on_open callback
  12461. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12462. // Add a simple endpoint that sends one event and closes
  12463. server_->Get("/simple-event", [](const Request &, Response &res) {
  12464. res.set_chunked_content_provider(
  12465. "text/event-stream", [](size_t offset, DataSink &sink) {
  12466. if (offset == 0) {
  12467. std::string event = "data: hello\n\n";
  12468. sink.write(event.data(), event.size());
  12469. }
  12470. return false; // Close stream after sending
  12471. });
  12472. });
  12473. Client client("localhost", get_port());
  12474. sse::SSEClient sse(client, "/simple-event");
  12475. std::atomic<bool> open_called{false};
  12476. std::atomic<bool> message_received{false};
  12477. sse.on_open([&open_called]() { open_called.store(true); });
  12478. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12479. if (msg.data == "hello") { message_received.store(true); }
  12480. });
  12481. sse.set_reconnect_interval(100);
  12482. sse.set_max_reconnect_attempts(1);
  12483. // Start async
  12484. sse.start_async();
  12485. // Wait for message to be processed
  12486. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12487. sse.stop();
  12488. EXPECT_TRUE(open_called.load());
  12489. EXPECT_TRUE(message_received.load());
  12490. }
  12491. // Test: on_message callback
  12492. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12493. // Endpoint that sends multiple events then closes
  12494. server_->Get("/multi-event", [](const Request &, Response &res) {
  12495. res.set_chunked_content_provider(
  12496. "text/event-stream", [](size_t offset, DataSink &sink) {
  12497. if (offset == 0) {
  12498. std::string events = "data: message1\n\ndata: message2\n\n";
  12499. sink.write(events.data(), events.size());
  12500. }
  12501. return false;
  12502. });
  12503. });
  12504. Client client("localhost", get_port());
  12505. sse::SSEClient sse(client, "/multi-event");
  12506. std::vector<std::string> received_messages;
  12507. std::mutex messages_mutex;
  12508. sse.on_message([&](const sse::SSEMessage &msg) {
  12509. std::lock_guard<std::mutex> lock(messages_mutex);
  12510. received_messages.push_back(msg.data);
  12511. });
  12512. sse.set_reconnect_interval(100);
  12513. sse.set_max_reconnect_attempts(1);
  12514. sse.start_async();
  12515. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12516. sse.stop();
  12517. std::lock_guard<std::mutex> lock(messages_mutex);
  12518. EXPECT_GE(received_messages.size(), 2u);
  12519. if (received_messages.size() >= 2) {
  12520. EXPECT_EQ(received_messages[0], "message1");
  12521. EXPECT_EQ(received_messages[1], "message2");
  12522. }
  12523. }
  12524. // Test: on_event for specific types
  12525. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12526. Client client("localhost", get_port());
  12527. sse::SSEClient sse(client, "/custom-events");
  12528. std::atomic<bool> update_received{false};
  12529. std::atomic<bool> delete_received{false};
  12530. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12531. if (msg.data == "updated") { update_received.store(true); }
  12532. });
  12533. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12534. if (msg.data == "deleted") { delete_received.store(true); }
  12535. });
  12536. sse.set_max_reconnect_attempts(1);
  12537. sse.start_async();
  12538. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12539. sse.stop();
  12540. EXPECT_TRUE(update_received.load());
  12541. EXPECT_TRUE(delete_received.load());
  12542. }
  12543. // Test: on_error callback on connection failure
  12544. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12545. // Connect to a non-existent port
  12546. Client client("localhost", 59999);
  12547. sse::SSEClient sse(client, "/events");
  12548. std::atomic<bool> error_called{false};
  12549. Error received_error = Error::Success;
  12550. sse.on_error([&](Error err) {
  12551. error_called.store(true);
  12552. received_error = err;
  12553. });
  12554. sse.set_reconnect_interval(50);
  12555. sse.set_max_reconnect_attempts(1);
  12556. sse.start_async();
  12557. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12558. sse.stop();
  12559. EXPECT_TRUE(error_called.load());
  12560. EXPECT_NE(received_error, Error::Success);
  12561. }
  12562. // Test: Last-Event-ID header sent on reconnect
  12563. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12564. // Endpoint that sends event with ID
  12565. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12566. res.set_chunked_content_provider(
  12567. "text/event-stream", [](size_t offset, DataSink &sink) {
  12568. if (offset == 0) {
  12569. std::string event = "id: evt-123\ndata: test\n\n";
  12570. sink.write(event.data(), event.size());
  12571. }
  12572. return false;
  12573. });
  12574. });
  12575. Client client("localhost", get_port());
  12576. sse::SSEClient sse(client, "/event-with-id");
  12577. std::atomic<bool> id_received{false};
  12578. sse.on_message([&](const sse::SSEMessage &msg) {
  12579. if (!msg.id.empty()) { id_received.store(true); }
  12580. });
  12581. sse.set_reconnect_interval(100);
  12582. sse.set_max_reconnect_attempts(1);
  12583. sse.start_async();
  12584. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12585. sse.stop();
  12586. EXPECT_TRUE(id_received.load());
  12587. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12588. }
  12589. // Test: Manual stop
  12590. TEST_F(SSEIntegrationTest, ManualStop) {
  12591. // Endpoint that sends one event and stays open briefly
  12592. std::atomic<bool> handler_running{true};
  12593. server_->Get("/stay-open", [&handler_running](const Request &,
  12594. Response &res) {
  12595. res.set_chunked_content_provider(
  12596. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12597. if (offset == 0) {
  12598. std::string event = "data: connected\n\n";
  12599. sink.write(event.data(), event.size());
  12600. }
  12601. // Keep connection open while handler_running is true
  12602. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12603. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12604. }
  12605. return false;
  12606. });
  12607. });
  12608. Client client("localhost", get_port());
  12609. sse::SSEClient sse(client, "/stay-open");
  12610. std::atomic<bool> connected{false};
  12611. sse.on_open([&connected]() { connected.store(true); });
  12612. sse.set_reconnect_interval(100);
  12613. sse.set_max_reconnect_attempts(1);
  12614. sse.start_async();
  12615. // Wait for connection to establish
  12616. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12617. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12618. }
  12619. EXPECT_TRUE(connected.load());
  12620. EXPECT_TRUE(sse.is_connected());
  12621. // Signal handler to stop
  12622. handler_running.store(false);
  12623. // Stop SSE client
  12624. sse.stop();
  12625. EXPECT_FALSE(sse.is_connected());
  12626. }
  12627. // Test: SSEClient with custom headers
  12628. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12629. // Setup a server endpoint that checks for custom header
  12630. std::atomic<bool> header_received{false};
  12631. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12632. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12633. header_received.store(true);
  12634. }
  12635. res.set_chunked_content_provider("text/event-stream",
  12636. [](size_t, DataSink &) { return false; });
  12637. });
  12638. Client client("localhost", get_port());
  12639. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12640. sse::SSEClient sse(client, "/header-check", headers);
  12641. sse.set_max_reconnect_attempts(1);
  12642. sse.start_async();
  12643. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12644. sse.stop();
  12645. EXPECT_TRUE(header_received.load());
  12646. }
  12647. // Test: Reconnect interval configuration
  12648. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12649. Client client("localhost", get_port());
  12650. sse::SSEClient sse(client, "/events");
  12651. auto &result = sse.set_reconnect_interval(500);
  12652. // Builder pattern should return reference to self
  12653. EXPECT_EQ(&result, &sse);
  12654. }
  12655. // Test: Max reconnect attempts
  12656. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12657. // Connect to non-existent port to force reconnects
  12658. Client client("localhost", 59998);
  12659. sse::SSEClient sse(client, "/events");
  12660. std::atomic<int> error_count{0};
  12661. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12662. sse.set_reconnect_interval(50);
  12663. sse.set_max_reconnect_attempts(2);
  12664. auto start = std::chrono::steady_clock::now();
  12665. sse.start(); // Blocking call
  12666. auto end = std::chrono::steady_clock::now();
  12667. // Should have stopped after 2 failed attempts
  12668. EXPECT_GE(error_count.load(), 2);
  12669. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12670. auto duration =
  12671. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12672. #ifdef _WIN32
  12673. // Windows is much slower for socket connection failures
  12674. EXPECT_LT(duration.count(), 7000);
  12675. #else
  12676. EXPECT_LT(duration.count(), 1000);
  12677. #endif
  12678. }
  12679. // Test: Multi-line data in integration
  12680. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12681. // Endpoint with multi-line data
  12682. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12683. res.set_chunked_content_provider(
  12684. "text/event-stream", [](size_t offset, DataSink &sink) {
  12685. if (offset == 0) {
  12686. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12687. sink.write(event.data(), event.size());
  12688. }
  12689. return false;
  12690. });
  12691. });
  12692. Client client("localhost", get_port());
  12693. sse::SSEClient sse(client, "/multiline-data");
  12694. std::string received_data;
  12695. std::mutex data_mutex;
  12696. sse.on_message([&](const sse::SSEMessage &msg) {
  12697. std::lock_guard<std::mutex> lock(data_mutex);
  12698. received_data = msg.data;
  12699. });
  12700. sse.set_reconnect_interval(100);
  12701. sse.set_max_reconnect_attempts(1);
  12702. sse.start_async();
  12703. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12704. sse.stop();
  12705. std::lock_guard<std::mutex> lock(data_mutex);
  12706. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12707. }
  12708. // Test: Auto-reconnect after server disconnection
  12709. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12710. std::atomic<int> connection_count{0};
  12711. std::atomic<int> message_count{0};
  12712. // Endpoint that sends one event and closes, forcing reconnect
  12713. server_->Get("/reconnect-test",
  12714. [&connection_count](const Request &, Response &res) {
  12715. connection_count.fetch_add(1);
  12716. res.set_chunked_content_provider(
  12717. "text/event-stream", [](size_t offset, DataSink &sink) {
  12718. if (offset == 0) {
  12719. std::string event = "data: hello\n\n";
  12720. sink.write(event.data(), event.size());
  12721. }
  12722. return false; // Close connection after sending
  12723. });
  12724. });
  12725. Client client("localhost", get_port());
  12726. sse::SSEClient sse(client, "/reconnect-test");
  12727. sse.on_message([&message_count](const sse::SSEMessage &) {
  12728. message_count.fetch_add(1);
  12729. });
  12730. sse.set_reconnect_interval(100);
  12731. sse.set_max_reconnect_attempts(3);
  12732. sse.start_async();
  12733. // Wait long enough for multiple reconnects
  12734. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12735. sse.stop();
  12736. // Should have connected multiple times (initial + reconnects)
  12737. EXPECT_GE(connection_count.load(), 2);
  12738. // Should have received messages from multiple connections
  12739. EXPECT_GE(message_count.load(), 2);
  12740. }
  12741. // Test: Last-Event-ID sent on reconnect
  12742. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12743. std::atomic<int> connection_count{0};
  12744. std::vector<std::string> received_last_event_ids;
  12745. std::mutex id_mutex;
  12746. // Endpoint that checks Last-Event-ID header and sends event with ID
  12747. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12748. int conn = connection_count.fetch_add(1);
  12749. // Capture the Last-Event-ID header from each connection
  12750. {
  12751. std::lock_guard<std::mutex> lock(id_mutex);
  12752. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12753. }
  12754. res.set_chunked_content_provider(
  12755. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12756. if (offset == 0) {
  12757. std::string event =
  12758. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12759. sink.write(event.data(), event.size());
  12760. }
  12761. return false;
  12762. });
  12763. });
  12764. Client client("localhost", get_port());
  12765. sse::SSEClient sse(client, "/reconnect-with-id");
  12766. sse.set_reconnect_interval(100);
  12767. sse.set_max_reconnect_attempts(3);
  12768. sse.start_async();
  12769. // Wait for at least 2 connections
  12770. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12771. sse.stop();
  12772. // Verify behavior
  12773. std::lock_guard<std::mutex> lock(id_mutex);
  12774. EXPECT_GE(received_last_event_ids.size(), 2u);
  12775. // First connection should have no Last-Event-ID
  12776. if (!received_last_event_ids.empty()) {
  12777. EXPECT_EQ(received_last_event_ids[0], "");
  12778. }
  12779. // Second connection should have Last-Event-ID from first connection
  12780. if (received_last_event_ids.size() >= 2) {
  12781. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12782. }
  12783. }
  12784. TEST(Issue2318Test, EmptyHostString) {
  12785. {
  12786. httplib::Client cli_empty("", PORT);
  12787. auto res = cli_empty.Get("/");
  12788. ASSERT_FALSE(res);
  12789. EXPECT_EQ(httplib::Error::Connection, res.error());
  12790. }
  12791. {
  12792. httplib::Client cli(" ", PORT);
  12793. auto res = cli.Get("/");
  12794. ASSERT_FALSE(res);
  12795. EXPECT_EQ(httplib::Error::Connection, res.error());
  12796. }
  12797. }
  12798. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12799. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12800. Server svr;
  12801. // Set a small payload limit (1KB)
  12802. svr.set_payload_max_length(1024);
  12803. svr.Post("/test", [&](const Request &req, Response &res) {
  12804. res.set_content("Body size: " + std::to_string(req.body.size()),
  12805. "text/plain");
  12806. });
  12807. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12808. auto se = detail::scope_exit([&] {
  12809. svr.stop();
  12810. listen_thread.join();
  12811. });
  12812. svr.wait_until_ready();
  12813. // Create data that compresses well but exceeds limit when decompressed
  12814. // 8KB of repeated null bytes compresses to a very small size
  12815. std::string original_data(8 * 1024, '\0');
  12816. // Compress the data using gzip
  12817. std::string compressed_data;
  12818. detail::gzip_compressor compressor;
  12819. compressor.compress(original_data.data(), original_data.size(), true,
  12820. [&](const char *data, size_t size) {
  12821. compressed_data.append(data, size);
  12822. return true;
  12823. });
  12824. // Verify compression worked (compressed should be much smaller)
  12825. ASSERT_LT(compressed_data.size(), original_data.size());
  12826. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12827. // Send compressed data with Content-Encoding: gzip
  12828. Client cli(HOST, PORT);
  12829. Headers headers = {{"Content-Encoding", "gzip"}};
  12830. auto res =
  12831. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12832. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12833. ASSERT_TRUE(res);
  12834. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12835. }
  12836. #endif
  12837. // ============================================================================
  12838. // OpenSSL-Specific Tests
  12839. // ============================================================================
  12840. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12841. X509 *readCertificate(const std::string &strFileName) {
  12842. std::ifstream inStream(strFileName);
  12843. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12844. std::istreambuf_iterator<char>());
  12845. if (strCertPEM.empty()) return (nullptr);
  12846. BIO *pbCert = BIO_new(BIO_s_mem());
  12847. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12848. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12849. BIO_free(pbCert);
  12850. return (pCert);
  12851. }
  12852. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12853. std::ifstream inStream(strFileName);
  12854. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12855. std::istreambuf_iterator<char>());
  12856. if (strPrivateKeyPEM.empty()) return (nullptr);
  12857. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12858. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12859. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12860. BIO_free(pbPrivKey);
  12861. return (pPrivateKey);
  12862. }
  12863. TEST(BindServerTest, UpdateCerts) {
  12864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12865. int port = svr.bind_to_any_port("0.0.0.0");
  12866. ASSERT_TRUE(svr.is_valid());
  12867. ASSERT_TRUE(port > 0);
  12868. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12869. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12870. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12871. ASSERT_TRUE(cert != nullptr);
  12872. ASSERT_TRUE(ca_cert != nullptr);
  12873. ASSERT_TRUE(key != nullptr);
  12874. X509_STORE *cert_store = X509_STORE_new();
  12875. X509_STORE_add_cert(cert_store, ca_cert);
  12876. // svr.update_certs(cert, key, cert_store); // deprecated
  12877. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12878. CLIENT_CA_CERT_FILE);
  12879. ASSERT_TRUE(svr.is_valid());
  12880. svr.stop();
  12881. X509_STORE_free(cert_store);
  12882. X509_free(cert);
  12883. X509_free(ca_cert);
  12884. EVP_PKEY_free(key);
  12885. }
  12886. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12887. // client CA list correctly for TLS handshake
  12888. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12889. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12890. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12891. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12892. ASSERT_TRUE(cert != nullptr);
  12893. ASSERT_TRUE(ca_cert != nullptr);
  12894. ASSERT_TRUE(key != nullptr);
  12895. X509_STORE *cert_store = X509_STORE_new();
  12896. X509_STORE_add_cert(cert_store, ca_cert);
  12897. // Use X509-based constructor (deprecated but should still work correctly)
  12898. #pragma GCC diagnostic push
  12899. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12900. SSLServer svr(cert, key, cert_store);
  12901. #pragma GCC diagnostic pop
  12902. ASSERT_TRUE(svr.is_valid());
  12903. // Verify that client CA list is set in SSL_CTX
  12904. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12905. ASSERT_TRUE(ssl_ctx != nullptr);
  12906. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12907. ASSERT_TRUE(ca_list != nullptr);
  12908. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12909. X509_free(cert);
  12910. X509_free(ca_cert);
  12911. EVP_PKEY_free(key);
  12912. }
  12913. // Test that update_certs() updates client CA list correctly
  12914. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12915. // Start with file-based constructor
  12916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12917. ASSERT_TRUE(svr.is_valid());
  12918. // Initially no client CA list should be set
  12919. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12920. ASSERT_TRUE(ssl_ctx != nullptr);
  12921. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12922. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12923. EXPECT_EQ(0, count_before);
  12924. // Now update with client CA (PEM string)
  12925. std::string cert_pem, key_pem, ca_pem;
  12926. read_file(SERVER_CERT_FILE, cert_pem);
  12927. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12928. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12929. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12930. ASSERT_TRUE(svr.is_valid());
  12931. // Now client CA list should be set
  12932. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12933. ASSERT_TRUE(ca_list_after != nullptr);
  12934. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12935. }
  12936. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12937. // Test that the file-path SSLServer constructor properly sets the client CA
  12938. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12940. ASSERT_TRUE(svr.is_valid());
  12941. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12942. ASSERT_TRUE(ssl_ctx != nullptr);
  12943. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12944. ASSERT_TRUE(ca_list != nullptr);
  12945. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12946. }
  12947. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12948. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12949. // prepare large data
  12950. std::random_device seed_gen;
  12951. std::mt19937 random(seed_gen());
  12952. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12953. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12954. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12955. // server
  12956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12957. ASSERT_TRUE(svr.is_valid());
  12958. svr.Post("/binary", [&](const Request &req, Response &res) {
  12959. EXPECT_EQ(large_size_byte, req.body.size());
  12960. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12961. res.set_content(req.body, "application/octet-stream");
  12962. });
  12963. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12964. auto se = detail::scope_exit([&] {
  12965. svr.stop();
  12966. listen_thread.join();
  12967. ASSERT_FALSE(svr.is_running());
  12968. });
  12969. svr.wait_until_ready();
  12970. // client POST
  12971. SSLClient cli("localhost", PORT);
  12972. cli.enable_server_certificate_verification(false);
  12973. cli.set_read_timeout(std::chrono::seconds(100));
  12974. cli.set_write_timeout(std::chrono::seconds(100));
  12975. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12976. large_size_byte, "application/octet-stream");
  12977. // compare
  12978. EXPECT_EQ(StatusCode::OK_200, res->status);
  12979. EXPECT_EQ(large_size_byte, res->body.size());
  12980. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12981. }
  12982. #endif
  12983. // ============================================================================
  12984. // MbedTLS-Specific Tests
  12985. // ============================================================================
  12986. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12987. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12988. using namespace httplib::tls;
  12989. // Track if callback was invoked
  12990. bool callback_invoked = false;
  12991. // The callback receives void* ctx which is actually MbedTlsContext*
  12992. // We can access the mbedtls_ssl_config via the context
  12993. auto setup_callback = [&callback_invoked](void *ctx) {
  12994. callback_invoked = true;
  12995. // Cast to MbedTlsContext* to access the ssl config
  12996. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12997. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12998. // Use static variables to hold certificate data (simplified for test)
  12999. static mbedtls_x509_crt own_cert;
  13000. static mbedtls_pk_context own_key;
  13001. static mbedtls_x509_crt ca_chain;
  13002. static bool initialized = false;
  13003. if (!initialized) {
  13004. mbedtls_x509_crt_init(&own_cert);
  13005. mbedtls_pk_init(&own_key);
  13006. mbedtls_x509_crt_init(&ca_chain);
  13007. // Load server certificate
  13008. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13009. return false;
  13010. }
  13011. // Load server private key
  13012. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13013. #if MBEDTLS_VERSION_MAJOR >= 3
  13014. ,
  13015. mbedtls_ctr_drbg_random, nullptr
  13016. #endif
  13017. ) != 0) {
  13018. return false;
  13019. }
  13020. // Load CA chain for client verification
  13021. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13022. return false;
  13023. }
  13024. initialized = true;
  13025. }
  13026. // Configure the SSL config
  13027. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13028. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13029. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13030. // Set minimum TLS version using mbedTLS native API
  13031. #if MBEDTLS_VERSION_MAJOR >= 3
  13032. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13033. #else
  13034. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13035. MBEDTLS_SSL_MINOR_VERSION_3);
  13036. #endif
  13037. return true;
  13038. };
  13039. SSLServer svr(setup_callback);
  13040. ASSERT_TRUE(svr.is_valid());
  13041. ASSERT_TRUE(callback_invoked);
  13042. svr.Get("/test", [&](const Request &req, Response &res) {
  13043. res.set_content("test", "text/plain");
  13044. auto cert = req.peer_cert();
  13045. ASSERT_TRUE(static_cast<bool>(cert));
  13046. auto common_name = cert.subject_cn();
  13047. EXPECT_EQ("Common Name", common_name);
  13048. });
  13049. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13050. auto se = detail::scope_exit([&] {
  13051. svr.stop();
  13052. t.join();
  13053. ASSERT_FALSE(svr.is_running());
  13054. });
  13055. svr.wait_until_ready();
  13056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13057. cli.enable_server_certificate_verification(false);
  13058. cli.set_connection_timeout(30);
  13059. auto res = cli.Get("/test");
  13060. ASSERT_TRUE(res);
  13061. ASSERT_EQ(StatusCode::OK_200, res->status);
  13062. }
  13063. #endif