test.cc 407 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224
  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. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. auto port = 1234;
  74. Server svr;
  75. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  76. res.set_content("Benchmark Response", "text/plain");
  77. });
  78. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  79. auto se = detail::scope_exit([&] {
  80. svr.stop();
  81. listen_thread.join();
  82. ASSERT_FALSE(svr.is_running());
  83. });
  84. svr.wait_until_ready();
  85. Client cli(host, port);
  86. // Warm-up request to establish connection and resolve DNS
  87. auto warmup_res = cli.Get("/benchmark");
  88. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  89. // Run multiple trials and collect timings
  90. const int num_trials = 20;
  91. std::vector<int64_t> timings;
  92. timings.reserve(num_trials);
  93. for (int i = 0; i < num_trials; i++) {
  94. auto start = std::chrono::high_resolution_clock::now();
  95. auto res = cli.Get("/benchmark");
  96. auto end = std::chrono::high_resolution_clock::now();
  97. auto elapsed =
  98. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  99. .count();
  100. // Assertions after timing measurement to avoid overhead
  101. ASSERT_TRUE(res);
  102. EXPECT_EQ(StatusCode::OK_200, res->status);
  103. timings.push_back(elapsed);
  104. }
  105. // Calculate 25th percentile (lower quartile)
  106. std::sort(timings.begin(), timings.end());
  107. auto p25 = timings[num_trials / 4];
  108. // Format timings for output
  109. std::ostringstream timings_str;
  110. timings_str << "[";
  111. for (size_t i = 0; i < timings.size(); i++) {
  112. if (i > 0) timings_str << ", ";
  113. timings_str << timings[i];
  114. }
  115. timings_str << "]";
  116. // Localhost HTTP GET should be fast even in CI environments
  117. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  118. << "ms (Issue #1777). Timings: " << timings_str.str();
  119. }
  120. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  121. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. const std::string pathname_{"./httplib-server.sock"};
  136. const std::string pattern_{"/hi"};
  137. const std::string content_{"Hello World!"};
  138. };
  139. TEST_F(UnixSocketTest, pathname) {
  140. httplib::Server svr;
  141. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  142. res.set_content(content_, "text/plain");
  143. });
  144. std::thread t{[&] {
  145. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  146. }};
  147. auto se = detail::scope_exit([&] {
  148. svr.stop();
  149. t.join();
  150. ASSERT_FALSE(svr.is_running());
  151. });
  152. svr.wait_until_ready();
  153. ASSERT_TRUE(svr.is_running());
  154. client_GET(pathname_);
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 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(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.wait_writable());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(PORT + 1);
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  263. ASSERT_EQ(0, listen(s, 1));
  264. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  268. std::thread cli{[&] {
  269. const int s = socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_LE(0, s);
  271. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. cli.join();
  275. svr.join();
  276. ASSERT_NE(disconnected_svr_sock, -1);
  277. const auto asSocketStream = [&](socket_t fd,
  278. std::function<bool(Stream &)> func) {
  279. return detail::process_client_socket(
  280. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  281. };
  282. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  283. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  284. EXPECT_FALSE(ss.wait_writable());
  285. return true;
  286. });
  287. ASSERT_EQ(0, close(disconnected_svr_sock));
  288. }
  289. #endif // #ifndef _WIN32
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. u8"descrip=Gastos áéíóúñÑ 6");
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  319. string unescapedCharacters = "-_.!~*'()";
  320. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  321. }
  322. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  323. string reservedCharacters = ";,/?:@&=+$";
  324. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  325. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  326. }
  327. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  328. string chineseCharacters = u8"中国語";
  329. string russianCharacters = u8"дом";
  330. string brazilianCharacters = u8"óculos";
  331. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  332. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  333. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  334. "%D0%B4%D0%BE%D0%BC");
  335. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  336. }
  337. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  347. string chineseCharacters = u8"中国語";
  348. string russianCharacters = u8"дом";
  349. string brazilianCharacters = u8"óculos";
  350. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  351. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  352. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  353. "%D0%B4%D0%BE%D0%BC");
  354. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  355. }
  356. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  357. // Issue #2082 use case: encoding path component with ampersand
  358. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  359. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  360. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  361. }
  362. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  363. string unescapedCharacters = "-_.!~*'()";
  364. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  365. }
  366. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  367. string reservedCharacters = ";,/?:@&=+$#";
  368. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  369. }
  370. TEST(EncodeUriTest, TestUTF8Characters) {
  371. string chineseCharacters = u8"中国語";
  372. string russianCharacters = u8"дом";
  373. string brazilianCharacters = u8"óculos";
  374. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  375. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  376. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  377. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  378. }
  379. TEST(EncodeUriTest, TestCompleteUri) {
  380. string uri =
  381. "https://example.com/path/to/resource?query=value&param=test#fragment";
  382. EXPECT_EQ(
  383. httplib::encode_uri(uri),
  384. "https://example.com/path/to/resource?query=value&param=test#fragment");
  385. }
  386. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  387. string uri =
  388. "https://example.com/path with spaces/file name.html?q=hello world";
  389. EXPECT_EQ(httplib::encode_uri(uri),
  390. "https://example.com/path%20with%20spaces/"
  391. "file%20name.html?q=hello%20world");
  392. }
  393. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  394. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  395. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  396. }
  397. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  398. string unescapedCharacters = "-_.!~*'()";
  399. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  400. }
  401. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  402. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  403. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  404. string encodedBrazilian = "%C3%B3culos";
  405. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  406. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  407. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  408. }
  409. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  410. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  411. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  412. "Piri Tommy Villiers - on & on");
  413. }
  414. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  415. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  416. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  417. }
  418. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  419. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  420. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  421. }
  422. TEST(DecodeUriTest, TestUTF8Characters) {
  423. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  424. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  425. string encodedBrazilian = "%C3%B3culos";
  426. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  427. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  428. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  429. }
  430. TEST(DecodeUriTest, TestCompleteUri) {
  431. string encodedUri = "https://example.com/path%20with%20spaces/"
  432. "file%20name.html?q=hello%20world";
  433. EXPECT_EQ(
  434. httplib::decode_uri(encodedUri),
  435. "https://example.com/path with spaces/file name.html?q=hello world");
  436. }
  437. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  438. string original =
  439. "https://example.com/path with spaces/file name.html?q=hello world";
  440. string encoded = httplib::encode_uri(original);
  441. string decoded = httplib::decode_uri(encoded);
  442. EXPECT_EQ(decoded, original);
  443. }
  444. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  445. string original = "Piri Tommy Villiers - on & on";
  446. string encoded = httplib::encode_uri_component(original);
  447. string decoded = httplib::decode_uri_component(encoded);
  448. EXPECT_EQ(decoded, original);
  449. }
  450. TEST(TrimTests, TrimStringTests) {
  451. EXPECT_EQ("abc", detail::trim_copy("abc"));
  452. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  453. EXPECT_TRUE(detail::trim_copy("").empty());
  454. }
  455. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  456. // Simple case without quality values
  457. std::vector<std::string> result1;
  458. EXPECT_TRUE(detail::parse_accept_header(
  459. "text/html,application/json,text/plain", result1));
  460. EXPECT_EQ(result1.size(), 3U);
  461. EXPECT_EQ(result1[0], "text/html");
  462. EXPECT_EQ(result1[1], "application/json");
  463. EXPECT_EQ(result1[2], "text/plain");
  464. // With quality values
  465. std::vector<std::string> result2;
  466. EXPECT_TRUE(detail::parse_accept_header(
  467. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  468. EXPECT_EQ(result2.size(), 3U);
  469. EXPECT_EQ(result2[0], "application/json"); // highest q value
  470. EXPECT_EQ(result2[1], "text/html");
  471. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  472. }
  473. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  474. // Mixed with and without quality values
  475. std::vector<std::string> result;
  476. EXPECT_TRUE(detail::parse_accept_header(
  477. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  478. EXPECT_EQ(result.size(), 3U);
  479. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  480. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  481. EXPECT_EQ(result[2], "application/json"); // q=0.5
  482. }
  483. TEST(ParseAcceptHeaderTest, EdgeCases) {
  484. // Empty header
  485. std::vector<std::string> empty_result;
  486. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  487. EXPECT_TRUE(empty_result.empty());
  488. // Single type
  489. std::vector<std::string> single_result;
  490. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  491. EXPECT_EQ(single_result.size(), 1U);
  492. EXPECT_EQ(single_result[0], "application/json");
  493. // Wildcard types
  494. std::vector<std::string> wildcard_result;
  495. EXPECT_TRUE(detail::parse_accept_header(
  496. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  497. EXPECT_EQ(wildcard_result.size(), 3U);
  498. EXPECT_EQ(wildcard_result[0], "application/json");
  499. EXPECT_EQ(wildcard_result[1], "text/*");
  500. EXPECT_EQ(wildcard_result[2], "*/*");
  501. }
  502. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  503. // Common browser Accept header
  504. std::vector<std::string> browser_result;
  505. EXPECT_TRUE(
  506. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  507. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  508. browser_result));
  509. EXPECT_EQ(browser_result.size(), 6U);
  510. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  513. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  514. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  515. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  516. // API client header
  517. std::vector<std::string> api_result;
  518. EXPECT_TRUE(detail::parse_accept_header(
  519. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  520. api_result));
  521. EXPECT_EQ(api_result.size(), 3U);
  522. EXPECT_EQ(api_result[0], "application/json");
  523. EXPECT_EQ(api_result[1], "application/xml");
  524. EXPECT_EQ(api_result[2], "text/plain");
  525. }
  526. TEST(ParseAcceptHeaderTest, SpecialCases) {
  527. // Quality value with 3 decimal places
  528. std::vector<std::string> decimal_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  531. EXPECT_EQ(decimal_result.size(), 2U);
  532. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  533. EXPECT_EQ(decimal_result[1], "text/html");
  534. // Zero quality (should still be included but with lowest priority)
  535. std::vector<std::string> zero_q_result;
  536. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  537. zero_q_result));
  538. EXPECT_EQ(zero_q_result.size(), 2U);
  539. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  540. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  541. // No spaces around commas
  542. std::vector<std::string> no_space_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  545. no_space_result));
  546. EXPECT_EQ(no_space_result.size(), 3U);
  547. EXPECT_EQ(no_space_result[0], "text/html");
  548. EXPECT_EQ(no_space_result[1], "application/json");
  549. EXPECT_EQ(no_space_result[2], "text/plain");
  550. }
  551. TEST(ParseAcceptHeaderTest, InvalidCases) {
  552. std::vector<std::string> result;
  553. // Invalid quality value (> 1.0)
  554. EXPECT_FALSE(
  555. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  556. // Invalid quality value (< 0.0)
  557. EXPECT_FALSE(
  558. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  559. // Invalid quality value (not a number)
  560. EXPECT_FALSE(detail::parse_accept_header(
  561. "text/html;q=invalid,application/json", result));
  562. // Empty quality value
  563. EXPECT_FALSE(
  564. detail::parse_accept_header("text/html;q=,application/json", result));
  565. // Invalid media type format (no slash and not wildcard)
  566. EXPECT_FALSE(
  567. detail::parse_accept_header("invalidtype,application/json", result));
  568. // Empty media type
  569. result.clear();
  570. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  571. // Only commas
  572. result.clear();
  573. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  574. // Valid cases should still work
  575. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  576. EXPECT_EQ(result.size(), 1U);
  577. EXPECT_EQ(result[0], "*/*");
  578. EXPECT_TRUE(detail::parse_accept_header("*", result));
  579. EXPECT_EQ(result.size(), 1U);
  580. EXPECT_EQ(result[0], "*");
  581. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  582. EXPECT_EQ(result.size(), 1U);
  583. EXPECT_EQ(result[0], "text/*");
  584. }
  585. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  586. Server svr;
  587. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  588. EXPECT_EQ(req.accept_content_types.size(), 3U);
  589. EXPECT_EQ(req.accept_content_types[0], "application/json");
  590. EXPECT_EQ(req.accept_content_types[1], "text/html");
  591. EXPECT_EQ(req.accept_content_types[2], "*/*");
  592. res.set_content("ok", "text/plain");
  593. });
  594. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  595. EXPECT_TRUE(false);
  596. res.set_content("bad request", "text/plain");
  597. });
  598. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  599. auto se = detail::scope_exit([&] {
  600. svr.stop();
  601. listen_thread.join();
  602. ASSERT_FALSE(svr.is_running());
  603. });
  604. svr.wait_until_ready();
  605. Client cli("localhost", PORT);
  606. {
  607. auto res =
  608. cli.Get("/accept_ok",
  609. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  610. ASSERT_TRUE(res);
  611. EXPECT_EQ(StatusCode::OK_200, res->status);
  612. }
  613. {
  614. auto res = cli.Get("/accept_bad_request",
  615. {{"Accept", "text/html;q=abc,application/json"}});
  616. ASSERT_TRUE(res);
  617. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  618. }
  619. }
  620. TEST(DivideTest, DivideStringTests) {
  621. auto divide = [](const std::string &str, char d) {
  622. std::string lhs;
  623. std::string rhs;
  624. detail::divide(str, d,
  625. [&](const char *lhs_data, std::size_t lhs_size,
  626. const char *rhs_data, std::size_t rhs_size) {
  627. lhs.assign(lhs_data, lhs_size);
  628. rhs.assign(rhs_data, rhs_size);
  629. });
  630. return std::make_pair(std::move(lhs), std::move(rhs));
  631. };
  632. {
  633. const auto res = divide("", '=');
  634. EXPECT_EQ(res.first, "");
  635. EXPECT_EQ(res.second, "");
  636. }
  637. {
  638. const auto res = divide("=", '=');
  639. EXPECT_EQ(res.first, "");
  640. EXPECT_EQ(res.second, "");
  641. }
  642. {
  643. const auto res = divide(" ", '=');
  644. EXPECT_EQ(res.first, " ");
  645. EXPECT_EQ(res.second, "");
  646. }
  647. {
  648. const auto res = divide("a", '=');
  649. EXPECT_EQ(res.first, "a");
  650. EXPECT_EQ(res.second, "");
  651. }
  652. {
  653. const auto res = divide("a=", '=');
  654. EXPECT_EQ(res.first, "a");
  655. EXPECT_EQ(res.second, "");
  656. }
  657. {
  658. const auto res = divide("=b", '=');
  659. EXPECT_EQ(res.first, "");
  660. EXPECT_EQ(res.second, "b");
  661. }
  662. {
  663. const auto res = divide("a=b", '=');
  664. EXPECT_EQ(res.first, "a");
  665. EXPECT_EQ(res.second, "b");
  666. }
  667. {
  668. const auto res = divide("a=b=", '=');
  669. EXPECT_EQ(res.first, "a");
  670. EXPECT_EQ(res.second, "b=");
  671. }
  672. {
  673. const auto res = divide("a=b=c", '=');
  674. EXPECT_EQ(res.first, "a");
  675. EXPECT_EQ(res.second, "b=c");
  676. }
  677. }
  678. TEST(SplitTest, ParseQueryString) {
  679. string s = "key1=val1&key2=val2&key3=val3";
  680. Params dic;
  681. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  682. [&](const char *b, const char *e) {
  683. string key, val;
  684. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  685. if (key.empty()) {
  686. key.assign(b2, e2);
  687. } else {
  688. val.assign(b2, e2);
  689. }
  690. });
  691. dic.emplace(key, val);
  692. });
  693. EXPECT_EQ("val1", dic.find("key1")->second);
  694. EXPECT_EQ("val2", dic.find("key2")->second);
  695. EXPECT_EQ("val3", dic.find("key3")->second);
  696. }
  697. TEST(SplitTest, ParseInvalidQueryTests) {
  698. {
  699. string s = " ";
  700. Params dict;
  701. detail::parse_query_text(s, dict);
  702. EXPECT_TRUE(dict.empty());
  703. }
  704. {
  705. string s = " = =";
  706. Params dict;
  707. detail::parse_query_text(s, dict);
  708. EXPECT_TRUE(dict.empty());
  709. }
  710. }
  711. TEST(ParseQueryTest, ParseQueryString) {
  712. {
  713. std::string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::parse_query_text(s, dic);
  716. EXPECT_EQ("val1", dic.find("key1")->second);
  717. EXPECT_EQ("val2", dic.find("key2")->second);
  718. EXPECT_EQ("val3", dic.find("key3")->second);
  719. }
  720. {
  721. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  722. Params dic;
  723. detail::parse_query_text(s, dic);
  724. EXPECT_EQ("", dic.find("key1")->second);
  725. EXPECT_EQ("val1", dic.find("key2")->second);
  726. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  727. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  728. }
  729. }
  730. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  731. Params dic;
  732. EXPECT_EQ(detail::params_to_query_str(dic), "");
  733. dic.emplace("key1", "val1");
  734. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  735. dic.emplace("key2", "val2");
  736. dic.emplace("key3", "val3");
  737. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  738. }
  739. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  740. string content_type = "multipart/form-data; boundary=something";
  741. string boundary;
  742. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  743. EXPECT_TRUE(ret);
  744. EXPECT_EQ(boundary, "something");
  745. }
  746. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  747. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  748. string boundary;
  749. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  750. EXPECT_TRUE(ret);
  751. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  752. }
  753. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  754. string content_type =
  755. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  756. string boundary;
  757. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  758. EXPECT_TRUE(ret);
  759. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  760. }
  761. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  762. string content_type =
  763. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  764. string boundary;
  765. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  766. EXPECT_TRUE(ret);
  767. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  768. }
  769. TEST(GetHeaderValueTest, DefaultValue) {
  770. Headers headers = {{"Dummy", "Dummy"}};
  771. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  772. EXPECT_STREQ("text/plain", val);
  773. }
  774. TEST(GetHeaderValueTest, DefaultValueInt) {
  775. Headers headers = {{"Dummy", "Dummy"}};
  776. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  777. EXPECT_EQ(100ull, val);
  778. }
  779. TEST(GetHeaderValueTest, RegularValue) {
  780. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  781. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  782. EXPECT_STREQ("text/html", val);
  783. }
  784. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  785. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  786. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  787. EXPECT_STREQ("text/html", val);
  788. }
  789. TEST(GetHeaderValueTest, SetContent) {
  790. Response res;
  791. res.set_content("html", "text/html");
  792. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  793. res.set_content("text", "text/plain");
  794. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  795. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  796. }
  797. TEST(GetHeaderValueTest, RegularValueInt) {
  798. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  799. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  800. EXPECT_EQ(100ull, val);
  801. }
  802. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  803. Headers headers = {{"Content-Length", "x"}};
  804. auto is_invalid_value = false;
  805. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  806. is_invalid_value);
  807. EXPECT_EQ(0ull, val);
  808. EXPECT_TRUE(is_invalid_value);
  809. }
  810. TEST(GetHeaderValueTest, Range) {
  811. {
  812. Headers headers = {make_range_header({{1, -1}})};
  813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  814. EXPECT_STREQ("bytes=1-", val);
  815. }
  816. {
  817. Headers headers = {make_range_header({{-1, 1}})};
  818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  819. EXPECT_STREQ("bytes=-1", val);
  820. }
  821. {
  822. Headers headers = {make_range_header({{1, 10}})};
  823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  824. EXPECT_STREQ("bytes=1-10", val);
  825. }
  826. {
  827. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  829. EXPECT_STREQ("bytes=1-10, 100-", val);
  830. }
  831. {
  832. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  834. EXPECT_STREQ("bytes=1-10, 100-200", val);
  835. }
  836. {
  837. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  838. auto val = detail::get_header_value(headers, "Range", 0, 0);
  839. EXPECT_STREQ("bytes=0-0, -1", val);
  840. }
  841. }
  842. TEST(ParseHeaderValueTest, Range) {
  843. {
  844. Ranges ranges;
  845. auto ret = detail::parse_range_header("bytes=1-", ranges);
  846. EXPECT_TRUE(ret);
  847. EXPECT_EQ(1u, ranges.size());
  848. EXPECT_EQ(1u, ranges[0].first);
  849. EXPECT_EQ(-1, ranges[0].second);
  850. }
  851. {
  852. Ranges ranges;
  853. auto ret = detail::parse_range_header("bytes=-1", ranges);
  854. EXPECT_TRUE(ret);
  855. EXPECT_EQ(1u, ranges.size());
  856. EXPECT_EQ(-1, ranges[0].first);
  857. EXPECT_EQ(1u, ranges[0].second);
  858. }
  859. {
  860. Ranges ranges;
  861. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  862. EXPECT_TRUE(ret);
  863. EXPECT_EQ(1u, ranges.size());
  864. EXPECT_EQ(1u, ranges[0].first);
  865. EXPECT_EQ(10u, ranges[0].second);
  866. }
  867. {
  868. Ranges ranges;
  869. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  870. EXPECT_FALSE(ret);
  871. }
  872. {
  873. Ranges ranges;
  874. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  875. EXPECT_TRUE(ret);
  876. EXPECT_EQ(2u, ranges.size());
  877. EXPECT_EQ(1u, ranges[0].first);
  878. EXPECT_EQ(10u, ranges[0].second);
  879. EXPECT_EQ(100u, ranges[1].first);
  880. EXPECT_EQ(-1, ranges[1].second);
  881. }
  882. {
  883. Ranges ranges;
  884. auto ret =
  885. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  886. EXPECT_TRUE(ret);
  887. EXPECT_EQ(3u, ranges.size());
  888. EXPECT_EQ(1u, ranges[0].first);
  889. EXPECT_EQ(10u, ranges[0].second);
  890. EXPECT_EQ(100u, ranges[1].first);
  891. EXPECT_EQ(200u, ranges[1].second);
  892. EXPECT_EQ(300u, ranges[2].first);
  893. EXPECT_EQ(400u, ranges[2].second);
  894. }
  895. {
  896. Ranges ranges;
  897. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  908. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  909. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  910. EXPECT_TRUE(ranges.empty());
  911. }
  912. }
  913. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  914. Request req;
  915. req.set_header("Accept-Encoding", "gzip");
  916. Response res;
  917. res.set_header("Content-Type", "text/plain");
  918. auto ret = detail::encoding_type(req, res);
  919. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  920. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  921. #else
  922. EXPECT_TRUE(ret == detail::EncodingType::None);
  923. #endif
  924. }
  925. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  926. Request req;
  927. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  928. Response res;
  929. res.set_header("Content-Type", "text/plain");
  930. auto ret = detail::encoding_type(req, res);
  931. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  933. #elif CPPHTTPLIB_ZLIB_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  935. #elif CPPHTTPLIB_ZSTD_SUPPORT
  936. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  937. #else
  938. EXPECT_TRUE(ret == detail::EncodingType::None);
  939. #endif
  940. }
  941. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  942. Request req;
  943. req.set_header("Accept-Encoding",
  944. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  945. Response res;
  946. res.set_header("Content-Type", "text/plain");
  947. auto ret = detail::encoding_type(req, res);
  948. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  950. #elif CPPHTTPLIB_ZLIB_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  952. #elif CPPHTTPLIB_ZSTD_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(BufferStreamTest, read) {
  959. detail::BufferStream strm1;
  960. Stream &strm = strm1;
  961. EXPECT_EQ(5, strm.write("hello"));
  962. char buf[512];
  963. EXPECT_EQ(2, strm.read(buf, 2));
  964. EXPECT_EQ('h', buf[0]);
  965. EXPECT_EQ('e', buf[1]);
  966. EXPECT_EQ(2, strm.read(buf, 2));
  967. EXPECT_EQ('l', buf[0]);
  968. EXPECT_EQ('l', buf[1]);
  969. EXPECT_EQ(1, strm.read(buf, 1));
  970. EXPECT_EQ('o', buf[0]);
  971. EXPECT_EQ(0, strm.read(buf, 1));
  972. }
  973. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  974. auto host = "www.httpwatch.com";
  975. auto ip = hosted_at(host);
  976. EXPECT_EQ("23.96.13.243", ip);
  977. std::vector<std::string> addrs;
  978. hosted_at(host, addrs);
  979. EXPECT_EQ(1u, addrs.size());
  980. }
  981. #if 0 // It depends on each test environment...
  982. TEST(HostnameToIPConversionTest, YouTube_Online) {
  983. auto host = "www.youtube.com";
  984. std::vector<std::string> addrs;
  985. hosted_at(host, addrs);
  986. EXPECT_EQ(20u, addrs.size());
  987. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  988. EXPECT_TRUE(it != addrs.end());
  989. }
  990. #endif
  991. class ChunkedEncodingTest : public ::testing::Test {
  992. protected:
  993. ChunkedEncodingTest()
  994. : cli_(HOST, PORT)
  995. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  996. ,
  997. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  998. #endif
  999. {
  1000. cli_.set_connection_timeout(2);
  1001. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1002. cli_.enable_server_certificate_verification(false);
  1003. #endif
  1004. }
  1005. virtual void SetUp() {
  1006. read_file("./image.jpg", image_data_);
  1007. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1008. res.set_content("Hello World!", "text/plain");
  1009. });
  1010. svr_.Get(
  1011. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1012. res.set_chunked_content_provider(
  1013. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1014. size_t remaining = image_data_.size() - offset;
  1015. if (remaining == 0) {
  1016. sink.done();
  1017. } else {
  1018. constexpr size_t CHUNK_SIZE = 1024;
  1019. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1020. sink.write(&image_data_[offset], send_size);
  1021. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1022. }
  1023. return true;
  1024. });
  1025. });
  1026. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1027. svr_.wait_until_ready();
  1028. }
  1029. virtual void TearDown() {
  1030. svr_.stop();
  1031. if (!request_threads_.empty()) {
  1032. std::this_thread::sleep_for(std::chrono::seconds(1));
  1033. for (auto &t : request_threads_) {
  1034. t.join();
  1035. }
  1036. }
  1037. t_.join();
  1038. }
  1039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1040. SSLClient cli_;
  1041. SSLServer svr_;
  1042. #else
  1043. Client cli_;
  1044. Server svr_;
  1045. #endif
  1046. thread t_;
  1047. std::vector<thread> request_threads_;
  1048. std::string image_data_;
  1049. };
  1050. TEST_F(ChunkedEncodingTest, NormalGet) {
  1051. auto res = cli_.Get("/chunked");
  1052. ASSERT_TRUE(res);
  1053. std::string out;
  1054. read_file("./image.jpg", out);
  1055. EXPECT_EQ(StatusCode::OK_200, res->status);
  1056. EXPECT_EQ(out, res->body);
  1057. }
  1058. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1059. std::string body;
  1060. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1061. body.append(data, data_length);
  1062. return true;
  1063. });
  1064. ASSERT_TRUE(res);
  1065. std::string out;
  1066. read_file("./image.jpg", out);
  1067. EXPECT_EQ(StatusCode::OK_200, res->status);
  1068. EXPECT_EQ(out, body);
  1069. }
  1070. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1071. std::string body;
  1072. auto res = cli_.Get(
  1073. "/chunked",
  1074. [&](const Response &response) {
  1075. EXPECT_EQ(StatusCode::OK_200, response.status);
  1076. return true;
  1077. },
  1078. [&](const char *data, size_t data_length) {
  1079. body.append(data, data_length);
  1080. return true;
  1081. });
  1082. ASSERT_TRUE(res);
  1083. std::string out;
  1084. read_file("./image.jpg", out);
  1085. EXPECT_EQ(StatusCode::OK_200, res->status);
  1086. EXPECT_EQ(out, body);
  1087. }
  1088. TEST(RangeTest, FromHTTPBin_Online) {
  1089. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1090. auto host = "httpbin.org";
  1091. auto path = std::string{"/range/32"};
  1092. #else
  1093. auto host = "nghttp2.org";
  1094. auto path = std::string{"/httpbin/range/32"};
  1095. #endif
  1096. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1097. auto port = 443;
  1098. SSLClient cli(host, port);
  1099. #else
  1100. auto port = 80;
  1101. Client cli(host, port);
  1102. #endif
  1103. cli.set_connection_timeout(5);
  1104. {
  1105. auto res = cli.Get(path);
  1106. ASSERT_TRUE(res);
  1107. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1108. EXPECT_EQ(StatusCode::OK_200, res->status);
  1109. }
  1110. {
  1111. Headers headers = {make_range_header({{1, -1}})};
  1112. auto res = cli.Get(path, headers);
  1113. ASSERT_TRUE(res);
  1114. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1115. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1116. }
  1117. {
  1118. Headers headers = {make_range_header({{1, 10}})};
  1119. auto res = cli.Get(path, headers);
  1120. ASSERT_TRUE(res);
  1121. EXPECT_EQ("bcdefghijk", res->body);
  1122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1123. }
  1124. {
  1125. Headers headers = {make_range_header({{0, 31}})};
  1126. auto res = cli.Get(path, headers);
  1127. ASSERT_TRUE(res);
  1128. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1129. EXPECT_EQ(StatusCode::OK_200, res->status);
  1130. }
  1131. {
  1132. Headers headers = {make_range_header({{0, -1}})};
  1133. auto res = cli.Get(path, headers);
  1134. ASSERT_TRUE(res);
  1135. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. }
  1138. {
  1139. Headers headers = {make_range_header({{0, 32}})};
  1140. auto res = cli.Get(path, headers);
  1141. ASSERT_TRUE(res);
  1142. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1143. }
  1144. }
  1145. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1146. auto host = "unresolvableaddress.local";
  1147. auto path = std::string{"/"};
  1148. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1149. auto port = 443;
  1150. SSLClient cli(host, port);
  1151. #else
  1152. auto port = 80;
  1153. Client cli(host, port);
  1154. #endif
  1155. cli.set_connection_timeout(1);
  1156. {
  1157. auto res = cli.Get(path);
  1158. ASSERT_FALSE(res);
  1159. }
  1160. std::this_thread::sleep_for(std::chrono::seconds(8));
  1161. }
  1162. TEST(ConnectionErrorTest, InvalidHost) {
  1163. auto host = "-abcde.com";
  1164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1165. auto port = 443;
  1166. SSLClient cli(host, port);
  1167. #else
  1168. auto port = 80;
  1169. Client cli(host, port);
  1170. #endif
  1171. cli.set_connection_timeout(std::chrono::seconds(2));
  1172. auto res = cli.Get("/");
  1173. ASSERT_TRUE(!res);
  1174. EXPECT_EQ(Error::Connection, res.error());
  1175. }
  1176. TEST(ConnectionErrorTest, InvalidHost2) {
  1177. auto host = "httpbin.org/";
  1178. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1179. SSLClient cli(host);
  1180. #else
  1181. Client cli(host);
  1182. #endif
  1183. cli.set_connection_timeout(std::chrono::seconds(2));
  1184. auto res = cli.Get("/");
  1185. ASSERT_TRUE(!res);
  1186. EXPECT_EQ(Error::Connection, res.error());
  1187. }
  1188. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1189. auto host = "httpbin.org/";
  1190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1191. SSLClient cli(host);
  1192. #else
  1193. Client cli(host);
  1194. #endif
  1195. cli.set_connection_timeout(std::chrono::seconds(2));
  1196. auto res = cli.Get("/");
  1197. ASSERT_TRUE(!res);
  1198. stringstream s;
  1199. s << "error code: " << res.error();
  1200. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1201. }
  1202. TEST(ConnectionErrorTest, InvalidPort) {
  1203. auto host = "localhost";
  1204. auto port = 44380;
  1205. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1206. SSLClient cli(host, port);
  1207. #else
  1208. Client cli(host, port);
  1209. #endif
  1210. cli.set_connection_timeout(std::chrono::seconds(2));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_TRUE(Error::Connection == res.error() ||
  1214. Error::ConnectionTimeout == res.error());
  1215. }
  1216. TEST(ConnectionErrorTest, Timeout_Online) {
  1217. auto host = "google.com";
  1218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1219. auto port = 44380;
  1220. SSLClient cli(host, port);
  1221. #else
  1222. auto port = 8080;
  1223. Client cli(host, port);
  1224. #endif
  1225. cli.set_connection_timeout(std::chrono::seconds(2));
  1226. // only probe one address type so that the error reason
  1227. // correlates to the timed-out IPv4, not the unsupported
  1228. // IPv6 connection attempt
  1229. cli.set_address_family(AF_INET);
  1230. auto res = cli.Get("/");
  1231. ASSERT_TRUE(!res);
  1232. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1233. }
  1234. TEST(CancelTest, NoCancel_Online) {
  1235. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1236. auto host = "httpbin.org";
  1237. auto path = std::string{"/range/32"};
  1238. #else
  1239. auto host = "nghttp2.org";
  1240. auto path = std::string{"/httpbin/range/32"};
  1241. #endif
  1242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1243. auto port = 443;
  1244. SSLClient cli(host, port);
  1245. #else
  1246. auto port = 80;
  1247. Client cli(host, port);
  1248. #endif
  1249. cli.set_connection_timeout(std::chrono::seconds(5));
  1250. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1251. ASSERT_TRUE(res);
  1252. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1253. EXPECT_EQ(StatusCode::OK_200, res->status);
  1254. }
  1255. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1256. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1257. auto host = "httpbin.org";
  1258. auto path = std::string{"/range/32"};
  1259. #else
  1260. auto host = "nghttp2.org";
  1261. auto path = std::string{"/httpbin/range/32"};
  1262. #endif
  1263. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1264. auto port = 443;
  1265. SSLClient cli(host, port);
  1266. #else
  1267. auto port = 80;
  1268. Client cli(host, port);
  1269. #endif
  1270. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1271. cli.set_connection_timeout(std::chrono::seconds(5));
  1272. ASSERT_TRUE(!res);
  1273. EXPECT_EQ(Error::Canceled, res.error());
  1274. }
  1275. TEST(CancelTest, WithCancelLargePayload_Online) {
  1276. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1277. auto host = "httpbin.org";
  1278. auto path = std::string{"/range/65536"};
  1279. #else
  1280. auto host = "nghttp2.org";
  1281. auto path = std::string{"/httpbin/range/65536"};
  1282. #endif
  1283. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1284. auto port = 443;
  1285. SSLClient cli(host, port);
  1286. #else
  1287. auto port = 80;
  1288. Client cli(host, port);
  1289. #endif
  1290. cli.set_connection_timeout(std::chrono::seconds(5));
  1291. uint32_t count = 0;
  1292. auto res =
  1293. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1294. ASSERT_TRUE(!res);
  1295. EXPECT_EQ(Error::Canceled, res.error());
  1296. }
  1297. TEST(CancelTest, NoCancelPost) {
  1298. Server svr;
  1299. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1300. res.set_content("Hello World!", "text/plain");
  1301. });
  1302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1303. auto se = detail::scope_exit([&] {
  1304. svr.stop();
  1305. thread.join();
  1306. ASSERT_FALSE(svr.is_running());
  1307. });
  1308. svr.wait_until_ready();
  1309. Client cli(HOST, PORT);
  1310. cli.set_connection_timeout(std::chrono::seconds(5));
  1311. auto res =
  1312. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1313. "application/json", [](uint64_t, uint64_t) { return true; });
  1314. ASSERT_TRUE(res);
  1315. EXPECT_EQ("Hello World!", res->body);
  1316. EXPECT_EQ(StatusCode::OK_200, res->status);
  1317. }
  1318. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1319. Server svr;
  1320. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1321. res.set_content("Hello World!", "text/plain");
  1322. });
  1323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1324. auto se = detail::scope_exit([&] {
  1325. svr.stop();
  1326. thread.join();
  1327. ASSERT_FALSE(svr.is_running());
  1328. });
  1329. svr.wait_until_ready();
  1330. Client cli(HOST, PORT);
  1331. cli.set_connection_timeout(std::chrono::seconds(5));
  1332. auto res =
  1333. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1334. "application/json", [](uint64_t, uint64_t) { return false; });
  1335. ASSERT_TRUE(!res);
  1336. EXPECT_EQ(Error::Canceled, res.error());
  1337. }
  1338. TEST(CancelTest, WithCancelLargePayloadPost) {
  1339. Server svr;
  1340. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1341. res.set_content(LARGE_DATA, "text/plain");
  1342. });
  1343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. thread.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, PORT);
  1351. cli.set_connection_timeout(std::chrono::seconds(5));
  1352. auto res =
  1353. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1354. "application/json", [](uint64_t, uint64_t) { return false; });
  1355. ASSERT_TRUE(!res);
  1356. EXPECT_EQ(Error::Canceled, res.error());
  1357. }
  1358. TEST(CancelTest, NoCancelPut) {
  1359. Server svr;
  1360. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1361. res.set_content("Hello World!", "text/plain");
  1362. });
  1363. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1364. auto se = detail::scope_exit([&] {
  1365. svr.stop();
  1366. thread.join();
  1367. ASSERT_FALSE(svr.is_running());
  1368. });
  1369. svr.wait_until_ready();
  1370. Client cli(HOST, PORT);
  1371. cli.set_connection_timeout(std::chrono::seconds(5));
  1372. auto res =
  1373. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1374. "application/json", [](uint64_t, uint64_t) { return true; });
  1375. ASSERT_TRUE(res);
  1376. EXPECT_EQ("Hello World!", res->body);
  1377. EXPECT_EQ(StatusCode::OK_200, res->status);
  1378. }
  1379. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1380. Server svr;
  1381. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1382. res.set_content("Hello World!", "text/plain");
  1383. });
  1384. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1385. auto se = detail::scope_exit([&] {
  1386. svr.stop();
  1387. thread.join();
  1388. ASSERT_FALSE(svr.is_running());
  1389. });
  1390. svr.wait_until_ready();
  1391. Client cli(HOST, PORT);
  1392. cli.set_connection_timeout(std::chrono::seconds(5));
  1393. auto res =
  1394. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1395. "application/json", [](uint64_t, uint64_t) { return false; });
  1396. ASSERT_TRUE(!res);
  1397. EXPECT_EQ(Error::Canceled, res.error());
  1398. }
  1399. TEST(CancelTest, WithCancelLargePayloadPut) {
  1400. Server svr;
  1401. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1402. res.set_content(LARGE_DATA, "text/plain");
  1403. });
  1404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. thread.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. Client cli(HOST, PORT);
  1412. cli.set_connection_timeout(std::chrono::seconds(5));
  1413. auto res =
  1414. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1415. "application/json", [](uint64_t, uint64_t) { return false; });
  1416. ASSERT_TRUE(!res);
  1417. EXPECT_EQ(Error::Canceled, res.error());
  1418. }
  1419. TEST(CancelTest, NoCancelPatch) {
  1420. Server svr;
  1421. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1422. res.set_content("Hello World!", "text/plain");
  1423. });
  1424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1425. auto se = detail::scope_exit([&] {
  1426. svr.stop();
  1427. thread.join();
  1428. ASSERT_FALSE(svr.is_running());
  1429. });
  1430. svr.wait_until_ready();
  1431. Client cli(HOST, PORT);
  1432. cli.set_connection_timeout(std::chrono::seconds(5));
  1433. auto res =
  1434. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1435. "application/json", [](uint64_t, uint64_t) { return true; });
  1436. ASSERT_TRUE(res);
  1437. EXPECT_EQ("Hello World!", res->body);
  1438. EXPECT_EQ(StatusCode::OK_200, res->status);
  1439. }
  1440. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1441. Server svr;
  1442. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1443. res.set_content("Hello World!", "text/plain");
  1444. });
  1445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1446. auto se = detail::scope_exit([&] {
  1447. svr.stop();
  1448. thread.join();
  1449. ASSERT_FALSE(svr.is_running());
  1450. });
  1451. svr.wait_until_ready();
  1452. Client cli(HOST, PORT);
  1453. cli.set_connection_timeout(std::chrono::seconds(5));
  1454. auto res =
  1455. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1456. "application/json", [](uint64_t, uint64_t) { return false; });
  1457. ASSERT_TRUE(!res);
  1458. EXPECT_EQ(Error::Canceled, res.error());
  1459. }
  1460. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1461. Server svr;
  1462. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1463. res.set_content(LARGE_DATA, "text/plain");
  1464. });
  1465. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1466. auto se = detail::scope_exit([&] {
  1467. svr.stop();
  1468. thread.join();
  1469. ASSERT_FALSE(svr.is_running());
  1470. });
  1471. svr.wait_until_ready();
  1472. Client cli(HOST, PORT);
  1473. cli.set_connection_timeout(std::chrono::seconds(5));
  1474. auto res =
  1475. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1476. "application/json", [](uint64_t, uint64_t) { return false; });
  1477. ASSERT_TRUE(!res);
  1478. EXPECT_EQ(Error::Canceled, res.error());
  1479. }
  1480. TEST(CancelTest, NoCancelDelete) {
  1481. Server svr;
  1482. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1483. res.set_content("Hello World!", "text/plain");
  1484. });
  1485. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1486. auto se = detail::scope_exit([&] {
  1487. svr.stop();
  1488. thread.join();
  1489. ASSERT_FALSE(svr.is_running());
  1490. });
  1491. svr.wait_until_ready();
  1492. Client cli(HOST, PORT);
  1493. cli.set_connection_timeout(std::chrono::seconds(5));
  1494. auto res =
  1495. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1496. "application/json", [](uint64_t, uint64_t) { return true; });
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("Hello World!", res->body);
  1499. EXPECT_EQ(StatusCode::OK_200, res->status);
  1500. }
  1501. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1502. Server svr;
  1503. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1504. res.set_content("Hello World!", "text/plain");
  1505. });
  1506. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1507. auto se = detail::scope_exit([&] {
  1508. svr.stop();
  1509. thread.join();
  1510. ASSERT_FALSE(svr.is_running());
  1511. });
  1512. svr.wait_until_ready();
  1513. Client cli(HOST, PORT);
  1514. cli.set_connection_timeout(std::chrono::seconds(5));
  1515. auto res =
  1516. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1517. "application/json", [](uint64_t, uint64_t) { return false; });
  1518. ASSERT_TRUE(!res);
  1519. EXPECT_EQ(Error::Canceled, res.error());
  1520. }
  1521. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1522. Server svr;
  1523. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1524. res.set_content(LARGE_DATA, "text/plain");
  1525. });
  1526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. thread.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. Client cli(HOST, PORT);
  1534. cli.set_connection_timeout(std::chrono::seconds(5));
  1535. auto res =
  1536. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1537. "application/json", [](uint64_t, uint64_t) { return false; });
  1538. ASSERT_TRUE(!res);
  1539. EXPECT_EQ(Error::Canceled, res.error());
  1540. }
  1541. static std::string remove_whitespace(const std::string &input) {
  1542. std::string output;
  1543. output.reserve(input.size());
  1544. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1545. [](unsigned char c) { return !std::isspace(c); });
  1546. return output;
  1547. }
  1548. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1549. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1550. auto host = "httpbin.org";
  1551. auto path = std::string{"/basic-auth/hello/world"};
  1552. #else
  1553. auto host = "nghttp2.org";
  1554. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1555. #endif
  1556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1557. auto port = 443;
  1558. SSLClient cli(host, port);
  1559. #else
  1560. auto port = 80;
  1561. Client cli(host, port);
  1562. #endif
  1563. {
  1564. auto res = cli.Get(path);
  1565. ASSERT_TRUE(res);
  1566. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1567. }
  1568. {
  1569. auto res =
  1570. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1571. ASSERT_TRUE(res);
  1572. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1573. remove_whitespace(res->body));
  1574. EXPECT_EQ(StatusCode::OK_200, res->status);
  1575. }
  1576. {
  1577. cli.set_basic_auth("hello", "world");
  1578. auto res = cli.Get(path);
  1579. ASSERT_TRUE(res);
  1580. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1581. remove_whitespace(res->body));
  1582. EXPECT_EQ(StatusCode::OK_200, res->status);
  1583. }
  1584. {
  1585. cli.set_basic_auth("hello", "bad");
  1586. auto res = cli.Get(path);
  1587. ASSERT_TRUE(res);
  1588. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1589. }
  1590. {
  1591. cli.set_basic_auth("bad", "world");
  1592. auto res = cli.Get(path);
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1595. }
  1596. }
  1597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1598. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1599. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1600. auto host = "httpbin.org";
  1601. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1602. auto paths = std::vector<std::string>{
  1603. "/digest-auth/auth/hello/world/MD5",
  1604. "/digest-auth/auth/hello/world/SHA-256",
  1605. "/digest-auth/auth/hello/world/SHA-512",
  1606. "/digest-auth/auth-int/hello/world/MD5",
  1607. };
  1608. #else
  1609. auto host = "nghttp2.org";
  1610. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1611. auto paths = std::vector<std::string>{
  1612. "/httpbin/digest-auth/auth/hello/world/MD5",
  1613. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1614. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1615. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1616. };
  1617. #endif
  1618. auto port = 443;
  1619. SSLClient cli(host, port);
  1620. {
  1621. auto res = cli.Get(unauth_path);
  1622. ASSERT_TRUE(res);
  1623. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1624. }
  1625. {
  1626. cli.set_digest_auth("hello", "world");
  1627. for (const auto &path : paths) {
  1628. auto res = cli.Get(path.c_str());
  1629. ASSERT_TRUE(res);
  1630. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1631. remove_whitespace(res->body));
  1632. EXPECT_EQ(StatusCode::OK_200, res->status);
  1633. }
  1634. cli.set_digest_auth("hello", "bad");
  1635. for (const auto &path : paths) {
  1636. auto res = cli.Get(path.c_str());
  1637. ASSERT_TRUE(res);
  1638. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1639. }
  1640. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1641. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1642. // cli.set_digest_auth("bad", "world");
  1643. // for (const auto& path : paths) {
  1644. // auto res = cli.Get(path.c_str());
  1645. // ASSERT_TRUE(res);
  1646. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1647. // }
  1648. }
  1649. }
  1650. #endif
  1651. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1652. auto host = "google.com";
  1653. auto another_host = "example.com";
  1654. auto wrong_ip = "0.0.0.0";
  1655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1656. SSLClient cli(host);
  1657. #else
  1658. Client cli(host);
  1659. #endif
  1660. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1661. auto res = cli.Get("/");
  1662. ASSERT_TRUE(res);
  1663. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1664. }
  1665. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1666. auto host = "google.com";
  1667. auto wrong_ip = "0.0.0.0";
  1668. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1669. SSLClient cli(host);
  1670. #else
  1671. Client cli(host);
  1672. #endif
  1673. cli.set_hostname_addr_map({{host, wrong_ip}});
  1674. auto res = cli.Get("/");
  1675. ASSERT_TRUE(!res);
  1676. EXPECT_EQ(Error::Connection, res.error());
  1677. }
  1678. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1679. auto host = "nghttp2.org";
  1680. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1681. SSLClient cli(host);
  1682. #else
  1683. Client cli(host);
  1684. #endif
  1685. cli.set_follow_location(true);
  1686. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1687. ASSERT_TRUE(res);
  1688. EXPECT_EQ(StatusCode::OK_200, res->status);
  1689. }
  1690. TEST(RedirectTest, Redirect_Online) {
  1691. auto host = "nghttp2.org";
  1692. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1693. SSLClient cli(host);
  1694. #else
  1695. Client cli(host);
  1696. #endif
  1697. cli.set_follow_location(true);
  1698. auto res = cli.Get("/httpbin/redirect/3");
  1699. ASSERT_TRUE(res);
  1700. EXPECT_EQ(StatusCode::OK_200, res->status);
  1701. }
  1702. TEST(RelativeRedirectTest, Redirect_Online) {
  1703. auto host = "nghttp2.org";
  1704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1705. SSLClient cli(host);
  1706. #else
  1707. Client cli(host);
  1708. #endif
  1709. cli.set_follow_location(true);
  1710. auto res = cli.Get("/httpbin/relative-redirect/3");
  1711. ASSERT_TRUE(res);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. TEST(TooManyRedirectTest, Redirect_Online) {
  1715. auto host = "nghttp2.org";
  1716. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1717. SSLClient cli(host);
  1718. #else
  1719. Client cli(host);
  1720. #endif
  1721. cli.set_follow_location(true);
  1722. auto res = cli.Get("/httpbin/redirect/21");
  1723. ASSERT_TRUE(!res);
  1724. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1725. }
  1726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1727. TEST(YahooRedirectTest, Redirect_Online) {
  1728. Client cli("yahoo.com");
  1729. auto res = cli.Get("/");
  1730. ASSERT_TRUE(res);
  1731. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1732. cli.set_follow_location(true);
  1733. res = cli.Get("/");
  1734. ASSERT_TRUE(res);
  1735. EXPECT_EQ(StatusCode::OK_200, res->status);
  1736. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1737. }
  1738. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1739. #define REDIR_HOST "httpbingo.org"
  1740. #define REDIR_PATH "/redirect-to"
  1741. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1742. SSLClient cli(REDIR_HOST);
  1743. cli.set_follow_location(true);
  1744. auto res =
  1745. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1746. ASSERT_TRUE(res);
  1747. EXPECT_EQ(StatusCode::OK_200, res->status);
  1748. }
  1749. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1750. SSLClient cli(REDIR_HOST);
  1751. cli.set_follow_location(true);
  1752. Params params;
  1753. params.emplace("url", "http://example.com");
  1754. params.emplace("status_code", "302");
  1755. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::OK_200, res->status);
  1758. }
  1759. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1760. SSLClient cli(REDIR_HOST);
  1761. cli.set_follow_location(true);
  1762. Params params;
  1763. params.emplace("url", "http://example.com");
  1764. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1765. ASSERT_TRUE(res);
  1766. EXPECT_EQ(StatusCode::OK_200, res->status);
  1767. }
  1768. TEST(UrlWithSpace, Redirect_Online) {
  1769. SSLClient cli("edge.forgecdn.net");
  1770. cli.set_follow_location(true);
  1771. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1775. }
  1776. #endif
  1777. #if !defined(_WIN32) && !defined(_WIN64)
  1778. TEST(ReceiveSignals, Signal) {
  1779. auto setupSignalHandlers = []() {
  1780. struct sigaction act;
  1781. sigemptyset(&act.sa_mask);
  1782. act.sa_flags = SA_SIGINFO;
  1783. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1784. switch (sig) {
  1785. case SIGINT:
  1786. default: break;
  1787. }
  1788. };
  1789. ::sigaction(SIGINT, &act, nullptr);
  1790. };
  1791. Server svr;
  1792. int port = 0;
  1793. auto thread = std::thread([&]() {
  1794. setupSignalHandlers();
  1795. port = svr.bind_to_any_port("localhost");
  1796. svr.listen_after_bind();
  1797. });
  1798. auto se = detail::scope_exit([&] {
  1799. svr.stop();
  1800. thread.join();
  1801. ASSERT_FALSE(svr.is_running());
  1802. });
  1803. svr.wait_until_ready();
  1804. ASSERT_TRUE(svr.is_running());
  1805. pthread_kill(thread.native_handle(), SIGINT);
  1806. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1807. ASSERT_TRUE(svr.is_running());
  1808. }
  1809. #endif
  1810. TEST(RedirectToDifferentPort, Redirect) {
  1811. Server svr1;
  1812. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1813. res.set_content("Hello World!", "text/plain");
  1814. });
  1815. int svr1_port = 0;
  1816. auto thread1 = std::thread([&]() {
  1817. svr1_port = svr1.bind_to_any_port("localhost");
  1818. svr1.listen_after_bind();
  1819. });
  1820. Server svr2;
  1821. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1822. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1823. });
  1824. int svr2_port = 0;
  1825. auto thread2 = std::thread([&]() {
  1826. svr2_port = svr2.bind_to_any_port("localhost");
  1827. svr2.listen_after_bind();
  1828. });
  1829. auto se = detail::scope_exit([&] {
  1830. svr2.stop();
  1831. thread2.join();
  1832. svr1.stop();
  1833. thread1.join();
  1834. ASSERT_FALSE(svr2.is_running());
  1835. ASSERT_FALSE(svr1.is_running());
  1836. });
  1837. svr1.wait_until_ready();
  1838. svr2.wait_until_ready();
  1839. Client cli("localhost", svr2_port);
  1840. cli.set_follow_location(true);
  1841. auto res = cli.Get("/2");
  1842. ASSERT_TRUE(res);
  1843. EXPECT_EQ(StatusCode::OK_200, res->status);
  1844. EXPECT_EQ("Hello World!", res->body);
  1845. }
  1846. TEST(RedirectFromPageWithContent, Redirect) {
  1847. Server svr;
  1848. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1849. res.set_content("___", "text/plain");
  1850. res.set_redirect("/2");
  1851. });
  1852. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1853. res.set_content("Hello World!", "text/plain");
  1854. });
  1855. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1856. auto se = detail::scope_exit([&] {
  1857. svr.stop();
  1858. th.join();
  1859. ASSERT_FALSE(svr.is_running());
  1860. });
  1861. svr.wait_until_ready();
  1862. {
  1863. Client cli("localhost", PORT);
  1864. cli.set_follow_location(true);
  1865. std::string body;
  1866. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1867. body.append(data, data_length);
  1868. return true;
  1869. });
  1870. ASSERT_TRUE(res);
  1871. EXPECT_EQ(StatusCode::OK_200, res->status);
  1872. EXPECT_EQ("Hello World!", body);
  1873. }
  1874. {
  1875. Client cli("localhost", PORT);
  1876. std::string body;
  1877. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1878. body.append(data, data_length);
  1879. return true;
  1880. });
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(StatusCode::Found_302, res->status);
  1883. EXPECT_EQ("___", body);
  1884. }
  1885. }
  1886. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1887. Server svr;
  1888. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("___", "text/plain");
  1890. // res.set_redirect("/2");
  1891. res.set_redirect("http://[::1]:1234/2");
  1892. });
  1893. svr.Get("/2", [&](const Request &req, Response &res) {
  1894. auto host_header = req.headers.find("Host");
  1895. ASSERT_TRUE(host_header != req.headers.end());
  1896. EXPECT_EQ("[::1]:1234", host_header->second);
  1897. res.set_content("Hello World!", "text/plain");
  1898. });
  1899. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1900. auto se = detail::scope_exit([&] {
  1901. svr.stop();
  1902. th.join();
  1903. ASSERT_FALSE(svr.is_running());
  1904. });
  1905. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1906. // actually starts anything, so the condition !svr.is_running() will
  1907. // always remain true, and the loop never stops.
  1908. // This basically counts how many milliseconds have passed since the
  1909. // call to svr.listen(), and if after 5 seconds nothing started yet
  1910. // aborts the test.
  1911. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1912. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1913. ASSERT_LT(milliseconds, 5000U);
  1914. }
  1915. {
  1916. Client cli("http://[::1]:1234");
  1917. cli.set_follow_location(true);
  1918. std::string body;
  1919. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1920. body.append(data, data_length);
  1921. return true;
  1922. });
  1923. ASSERT_TRUE(res);
  1924. EXPECT_EQ(StatusCode::OK_200, res->status);
  1925. EXPECT_EQ("Hello World!", body);
  1926. }
  1927. {
  1928. Client cli("http://[::1]:1234");
  1929. std::string body;
  1930. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1931. body.append(data, data_length);
  1932. return true;
  1933. });
  1934. ASSERT_TRUE(res);
  1935. EXPECT_EQ(StatusCode::Found_302, res->status);
  1936. EXPECT_EQ("___", body);
  1937. }
  1938. }
  1939. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1940. Server svr;
  1941. svr.Get("/foo", [](const Request &req, Response &res) {
  1942. auto a = req.params.find("a");
  1943. if (a != req.params.end()) {
  1944. res.set_content((*a).second, "text/plain");
  1945. res.status = StatusCode::OK_200;
  1946. } else {
  1947. res.status = StatusCode::BadRequest_400;
  1948. }
  1949. });
  1950. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1951. auto se = detail::scope_exit([&] {
  1952. svr.stop();
  1953. thread.join();
  1954. ASSERT_FALSE(svr.is_running());
  1955. });
  1956. svr.wait_until_ready();
  1957. {
  1958. Client cli(HOST, PORT);
  1959. cli.set_path_encode(false);
  1960. auto res = cli.Get("/foo?a=explicitly+encoded");
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. // This expects it back with a space, as the `+` won't have been
  1964. // url-encoded, and server-side the params get decoded turning `+`
  1965. // into spaces.
  1966. EXPECT_EQ("explicitly encoded", res->body);
  1967. }
  1968. }
  1969. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1970. Server svr;
  1971. svr.Get("/", [](const Request &req, Response &) {
  1972. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1973. });
  1974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1975. auto se = detail::scope_exit([&] {
  1976. svr.stop();
  1977. thread.join();
  1978. ASSERT_FALSE(svr.is_running());
  1979. });
  1980. svr.wait_until_ready();
  1981. {
  1982. Client cli(HOST, PORT);
  1983. cli.set_path_encode(false);
  1984. auto res = cli.Get("/?something=%0A");
  1985. ASSERT_TRUE(res);
  1986. EXPECT_EQ(StatusCode::OK_200, res->status);
  1987. }
  1988. }
  1989. TEST(BindServerTest, DISABLED_BindDualStack) {
  1990. Server svr;
  1991. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1992. res.set_content("Hello World!", "text/plain");
  1993. });
  1994. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1995. auto se = detail::scope_exit([&] {
  1996. svr.stop();
  1997. thread.join();
  1998. ASSERT_FALSE(svr.is_running());
  1999. });
  2000. svr.wait_until_ready();
  2001. {
  2002. Client cli("127.0.0.1", PORT);
  2003. auto res = cli.Get("/1");
  2004. ASSERT_TRUE(res);
  2005. EXPECT_EQ(StatusCode::OK_200, res->status);
  2006. EXPECT_EQ("Hello World!", res->body);
  2007. }
  2008. {
  2009. Client cli("::1", PORT);
  2010. auto res = cli.Get("/1");
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. EXPECT_EQ("Hello World!", res->body);
  2014. }
  2015. }
  2016. TEST(BindServerTest, BindAndListenSeparately) {
  2017. Server svr;
  2018. int port = svr.bind_to_any_port("0.0.0.0");
  2019. ASSERT_TRUE(svr.is_valid());
  2020. ASSERT_TRUE(port > 0);
  2021. svr.stop();
  2022. }
  2023. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2024. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2026. CLIENT_CA_CERT_DIR);
  2027. int port = svr.bind_to_any_port("0.0.0.0");
  2028. ASSERT_TRUE(svr.is_valid());
  2029. ASSERT_TRUE(port > 0);
  2030. svr.stop();
  2031. }
  2032. #endif
  2033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2034. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2035. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2036. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2037. int port = svr.bind_to_any_port("0.0.0.0");
  2038. ASSERT_TRUE(svr.is_valid());
  2039. ASSERT_TRUE(port > 0);
  2040. svr.stop();
  2041. }
  2042. #endif
  2043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2044. X509 *readCertificate(const std::string &strFileName) {
  2045. std::ifstream inStream(strFileName);
  2046. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2047. std::istreambuf_iterator<char>());
  2048. if (strCertPEM.empty()) return (nullptr);
  2049. BIO *pbCert = BIO_new(BIO_s_mem());
  2050. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2051. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2052. BIO_free(pbCert);
  2053. return (pCert);
  2054. }
  2055. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2056. std::ifstream inStream(strFileName);
  2057. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2058. std::istreambuf_iterator<char>());
  2059. if (strPrivateKeyPEM.empty()) return (nullptr);
  2060. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2061. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2062. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2063. BIO_free(pbPrivKey);
  2064. return (pPrivateKey);
  2065. }
  2066. TEST(BindServerTest, UpdateCerts) {
  2067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2068. int port = svr.bind_to_any_port("0.0.0.0");
  2069. ASSERT_TRUE(svr.is_valid());
  2070. ASSERT_TRUE(port > 0);
  2071. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2072. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2073. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2074. ASSERT_TRUE(cert != nullptr);
  2075. ASSERT_TRUE(ca_cert != nullptr);
  2076. ASSERT_TRUE(key != nullptr);
  2077. X509_STORE *cert_store = X509_STORE_new();
  2078. X509_STORE_add_cert(cert_store, ca_cert);
  2079. svr.update_certs(cert, key, cert_store);
  2080. ASSERT_TRUE(svr.is_valid());
  2081. svr.stop();
  2082. X509_free(cert);
  2083. X509_free(ca_cert);
  2084. EVP_PKEY_free(key);
  2085. }
  2086. #endif
  2087. TEST(ErrorHandlerTest, ContentLength) {
  2088. Server svr;
  2089. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2090. res.status = StatusCode::OK_200;
  2091. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2092. "text/html"); // <= Content-Length still 13
  2093. });
  2094. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2095. res.set_content("Hello World!\n", "text/plain");
  2096. res.status = 524;
  2097. });
  2098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2099. auto se = detail::scope_exit([&] {
  2100. svr.stop();
  2101. thread.join();
  2102. ASSERT_FALSE(svr.is_running());
  2103. });
  2104. svr.wait_until_ready();
  2105. {
  2106. Client cli(HOST, PORT);
  2107. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2108. ASSERT_TRUE(res);
  2109. EXPECT_EQ(StatusCode::OK_200, res->status);
  2110. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2111. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2112. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2113. }
  2114. }
  2115. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2116. TEST(ExceptionTest, WithoutExceptionHandler) {
  2117. Server svr;
  2118. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2119. throw std::runtime_error("exception...");
  2120. });
  2121. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2122. throw std::runtime_error("exception\r\n...");
  2123. });
  2124. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2125. auto se = detail::scope_exit([&] {
  2126. svr.stop();
  2127. listen_thread.join();
  2128. ASSERT_FALSE(svr.is_running());
  2129. });
  2130. svr.wait_until_ready();
  2131. Client cli("localhost", PORT);
  2132. {
  2133. auto res = cli.Get("/exception");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2136. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2137. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2138. }
  2139. {
  2140. auto res = cli.Get("/unknown");
  2141. ASSERT_TRUE(res);
  2142. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2143. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2144. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2145. }
  2146. }
  2147. TEST(ExceptionTest, WithExceptionHandler) {
  2148. Server svr;
  2149. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2150. std::exception_ptr ep) {
  2151. EXPECT_FALSE(ep == nullptr);
  2152. try {
  2153. std::rethrow_exception(ep);
  2154. } catch (std::exception &e) {
  2155. EXPECT_EQ("abc", std::string(e.what()));
  2156. } catch (...) {}
  2157. res.status = StatusCode::InternalServerError_500;
  2158. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2159. "text/html"); // <= Content-Length still 13 at this point
  2160. });
  2161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2162. res.set_content("Hello World!\n", "text/plain");
  2163. throw std::runtime_error("abc");
  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. for (size_t i = 0; i < 10; i++) {
  2173. Client cli(HOST, PORT);
  2174. for (size_t j = 0; j < 100; j++) {
  2175. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2176. ASSERT_TRUE(res);
  2177. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2178. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2179. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2180. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2181. }
  2182. cli.set_keep_alive(true);
  2183. for (size_t j = 0; j < 100; j++) {
  2184. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2185. ASSERT_TRUE(res);
  2186. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2187. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2188. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2189. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2190. }
  2191. }
  2192. }
  2193. TEST(ExceptionTest, AndErrorHandler) {
  2194. Server svr;
  2195. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2196. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2197. });
  2198. svr.set_exception_handler(
  2199. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2200. EXPECT_FALSE(ep == nullptr);
  2201. try {
  2202. std::rethrow_exception(ep);
  2203. } catch (std::exception &e) {
  2204. res.set_content(e.what(), "text/html");
  2205. } catch (...) {}
  2206. res.status = StatusCode::InternalServerError_500;
  2207. });
  2208. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2209. throw std::runtime_error("EXCEPTION");
  2210. });
  2211. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2212. res.set_content("ERROR", "text/html");
  2213. res.status = StatusCode::InternalServerError_500;
  2214. });
  2215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. thread.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. svr.wait_until_ready();
  2222. Client cli(HOST, PORT);
  2223. {
  2224. auto res = cli.Get("/exception");
  2225. ASSERT_TRUE(res);
  2226. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2227. EXPECT_EQ("EXCEPTION", res->body);
  2228. }
  2229. {
  2230. auto res = cli.Get("/error");
  2231. ASSERT_TRUE(res);
  2232. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2233. EXPECT_EQ("ERROR", res->body);
  2234. }
  2235. {
  2236. auto res = cli.Get("/invalid");
  2237. ASSERT_TRUE(res);
  2238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2239. EXPECT_EQ("NOT_FOUND", res->body);
  2240. }
  2241. }
  2242. #endif
  2243. TEST(NoContentTest, ContentLength) {
  2244. Server svr;
  2245. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2246. res.status = StatusCode::NoContent_204;
  2247. });
  2248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2249. auto se = detail::scope_exit([&] {
  2250. svr.stop();
  2251. thread.join();
  2252. ASSERT_FALSE(svr.is_running());
  2253. });
  2254. svr.wait_until_ready();
  2255. {
  2256. Client cli(HOST, PORT);
  2257. auto res = cli.Get("/hi");
  2258. ASSERT_TRUE(res);
  2259. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2260. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2261. }
  2262. }
  2263. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2264. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2266. ASSERT_TRUE(svr.is_valid());
  2267. #else
  2268. Server svr;
  2269. #endif
  2270. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2271. if (req.path == "/routing_handler") {
  2272. res.set_header("PRE_ROUTING", "on");
  2273. res.set_content("Routing Handler", "text/plain");
  2274. return httplib::Server::HandlerResponse::Handled;
  2275. }
  2276. return httplib::Server::HandlerResponse::Unhandled;
  2277. });
  2278. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2279. res.set_content("Error", "text/html");
  2280. });
  2281. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2282. if (req.path == "/routing_handler") {
  2283. res.set_header("POST_ROUTING", "on");
  2284. }
  2285. });
  2286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2287. res.set_content("Hello World!\n", "text/plain");
  2288. });
  2289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2290. auto se = detail::scope_exit([&] {
  2291. svr.stop();
  2292. thread.join();
  2293. ASSERT_FALSE(svr.is_running());
  2294. });
  2295. svr.wait_until_ready();
  2296. {
  2297. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2298. SSLClient cli(HOST, PORT);
  2299. cli.enable_server_certificate_verification(false);
  2300. #else
  2301. Client cli(HOST, PORT);
  2302. #endif
  2303. auto res = cli.Get("/routing_handler");
  2304. ASSERT_TRUE(res);
  2305. EXPECT_EQ(StatusCode::OK_200, res->status);
  2306. EXPECT_EQ("Routing Handler", res->body);
  2307. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2309. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2310. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2311. }
  2312. {
  2313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2314. SSLClient cli(HOST, PORT);
  2315. cli.enable_server_certificate_verification(false);
  2316. #else
  2317. Client cli(HOST, PORT);
  2318. #endif
  2319. auto res = cli.Get("/hi");
  2320. ASSERT_TRUE(res);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. EXPECT_EQ("Hello World!\n", res->body);
  2323. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2324. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2325. }
  2326. {
  2327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2328. SSLClient cli(HOST, PORT);
  2329. cli.enable_server_certificate_verification(false);
  2330. #else
  2331. Client cli(HOST, PORT);
  2332. #endif
  2333. auto res = cli.Get("/aaa");
  2334. ASSERT_TRUE(res);
  2335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2336. EXPECT_EQ("Error", res->body);
  2337. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2338. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2339. }
  2340. }
  2341. TEST(RequestHandlerTest, PreRequestHandler) {
  2342. auto route_path = "/user/:user";
  2343. Server svr;
  2344. svr.Get("/hi", [](const Request &, Response &res) {
  2345. res.set_content("hi", "text/plain");
  2346. });
  2347. svr.Get(route_path, [](const Request &req, Response &res) {
  2348. res.set_content(req.path_params.at("user"), "text/plain");
  2349. });
  2350. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2351. if (req.matched_route == route_path) {
  2352. auto user = req.path_params.at("user");
  2353. if (user != "john") {
  2354. res.status = StatusCode::Forbidden_403;
  2355. res.set_content("error", "text/html");
  2356. return Server::HandlerResponse::Handled;
  2357. }
  2358. }
  2359. return Server::HandlerResponse::Unhandled;
  2360. });
  2361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2362. auto se = detail::scope_exit([&] {
  2363. svr.stop();
  2364. thread.join();
  2365. ASSERT_FALSE(svr.is_running());
  2366. });
  2367. svr.wait_until_ready();
  2368. Client cli(HOST, PORT);
  2369. {
  2370. auto res = cli.Get("/hi");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ("hi", res->body);
  2374. }
  2375. {
  2376. auto res = cli.Get("/user/john");
  2377. ASSERT_TRUE(res);
  2378. EXPECT_EQ(StatusCode::OK_200, res->status);
  2379. EXPECT_EQ("john", res->body);
  2380. }
  2381. {
  2382. auto res = cli.Get("/user/invalid-user");
  2383. ASSERT_TRUE(res);
  2384. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2385. EXPECT_EQ("error", res->body);
  2386. }
  2387. }
  2388. TEST(InvalidFormatTest, StatusCode) {
  2389. Server svr;
  2390. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2391. res.set_content("Hello World!\n", "text/plain");
  2392. res.status = 9999; // Status should be a three-digit code...
  2393. });
  2394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. thread.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. {
  2402. Client cli(HOST, PORT);
  2403. auto res = cli.Get("/hi");
  2404. ASSERT_FALSE(res);
  2405. }
  2406. }
  2407. TEST(URLFragmentTest, WithFragment) {
  2408. Server svr;
  2409. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2410. EXPECT_TRUE(req.target == "/hi");
  2411. });
  2412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2413. auto se = detail::scope_exit([&] {
  2414. svr.stop();
  2415. thread.join();
  2416. ASSERT_FALSE(svr.is_running());
  2417. });
  2418. svr.wait_until_ready();
  2419. {
  2420. Client cli(HOST, PORT);
  2421. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2422. EXPECT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. res = cli.Get("/hi%23key1=val1=key2=val2");
  2425. EXPECT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2427. }
  2428. }
  2429. TEST(HeaderWriter, SetHeaderWriter) {
  2430. Server svr;
  2431. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2432. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2433. return detail::write_headers(strm, hdrs);
  2434. });
  2435. svr.Get("/hi", [](const Request &req, Response &res) {
  2436. auto it = req.headers.find("CustomClientHeader");
  2437. EXPECT_TRUE(it != req.headers.end());
  2438. EXPECT_EQ(it->second, "CustomClientValue");
  2439. res.set_content("Hello World!\n", "text/plain");
  2440. });
  2441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2442. auto se = detail::scope_exit([&] {
  2443. svr.stop();
  2444. thread.join();
  2445. ASSERT_FALSE(svr.is_running());
  2446. });
  2447. svr.wait_until_ready();
  2448. {
  2449. Client cli(HOST, PORT);
  2450. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2451. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2452. return detail::write_headers(strm, hdrs);
  2453. });
  2454. auto res = cli.Get("/hi");
  2455. EXPECT_TRUE(res);
  2456. EXPECT_EQ(StatusCode::OK_200, res->status);
  2457. auto it = res->headers.find("CustomServerHeader");
  2458. EXPECT_TRUE(it != res->headers.end());
  2459. EXPECT_EQ(it->second, "CustomServerValue");
  2460. }
  2461. }
  2462. class ServerTest : public ::testing::Test {
  2463. protected:
  2464. ServerTest()
  2465. : cli_(HOST, PORT)
  2466. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2467. ,
  2468. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2469. #endif
  2470. {
  2471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2472. cli_.enable_server_certificate_verification(false);
  2473. #endif
  2474. }
  2475. virtual void SetUp() {
  2476. svr_.set_mount_point("/", "./www");
  2477. svr_.set_mount_point("/mount", "./www2");
  2478. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2479. svr_.Get("/hi",
  2480. [&](const Request & /*req*/, Response &res) {
  2481. res.set_content("Hello World!", "text/plain");
  2482. })
  2483. .Get("/file_content",
  2484. [&](const Request & /*req*/, Response &res) {
  2485. res.set_file_content("./www/dir/test.html");
  2486. })
  2487. .Get("/file_content_with_content_type",
  2488. [&](const Request & /*req*/, Response &res) {
  2489. res.set_file_content("./www/file", "text/plain");
  2490. })
  2491. .Get("/invalid_file_content",
  2492. [&](const Request & /*req*/, Response &res) {
  2493. res.set_file_content("./www/dir/invalid_file_path");
  2494. })
  2495. .Get("/http_response_splitting",
  2496. [&](const Request & /*req*/, Response &res) {
  2497. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2498. EXPECT_EQ(0U, res.headers.size());
  2499. EXPECT_FALSE(res.has_header("a"));
  2500. res.set_header("a", "1\nSet-Cookie: a=1");
  2501. EXPECT_EQ(0U, res.headers.size());
  2502. EXPECT_FALSE(res.has_header("a"));
  2503. res.set_header("a", "1\rSet-Cookie: a=1");
  2504. EXPECT_EQ(0U, res.headers.size());
  2505. EXPECT_FALSE(res.has_header("a"));
  2506. res.set_header("a\r\nb", "0");
  2507. EXPECT_EQ(0U, res.headers.size());
  2508. EXPECT_FALSE(res.has_header("a"));
  2509. res.set_header("a\rb", "0");
  2510. EXPECT_EQ(0U, res.headers.size());
  2511. EXPECT_FALSE(res.has_header("a"));
  2512. res.set_header("a\nb", "0");
  2513. EXPECT_EQ(0U, res.headers.size());
  2514. EXPECT_FALSE(res.has_header("a"));
  2515. res.set_redirect("1\r\nSet-Cookie: a=1");
  2516. EXPECT_EQ(0U, res.headers.size());
  2517. EXPECT_FALSE(res.has_header("Location"));
  2518. })
  2519. .Get("/slow",
  2520. [&](const Request & /*req*/, Response &res) {
  2521. std::this_thread::sleep_for(std::chrono::seconds(2));
  2522. res.set_content("slow", "text/plain");
  2523. })
  2524. #if 0
  2525. .Post("/slowpost",
  2526. [&](const Request & /*req*/, Response &res) {
  2527. std::this_thread::sleep_for(std::chrono::seconds(2));
  2528. res.set_content("slow", "text/plain");
  2529. })
  2530. #endif
  2531. .Get("/remote_addr",
  2532. [&](const Request &req, Response &res) {
  2533. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2534. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2535. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2536. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2537. res.set_content(req.remote_addr, "text/plain");
  2538. })
  2539. .Get("/local_addr",
  2540. [&](const Request &req, Response &res) {
  2541. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2542. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2543. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2544. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2545. auto local_addr = req.local_addr;
  2546. auto local_port = std::to_string(req.local_port);
  2547. res.set_content(local_addr.append(":").append(local_port),
  2548. "text/plain");
  2549. })
  2550. .Get("/endwith%",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_content("Hello World!", "text/plain");
  2553. })
  2554. .Get("/a\\+\\+b",
  2555. [&](const Request &req, Response &res) {
  2556. ASSERT_TRUE(req.has_param("a +b"));
  2557. auto val = req.get_param_value("a +b");
  2558. res.set_content(val, "text/plain");
  2559. })
  2560. .Get("/", [&](const Request & /*req*/,
  2561. Response &res) { res.set_redirect("/hi"); })
  2562. .Post("/1",
  2563. [](const Request & /*req*/, Response &res) {
  2564. res.set_redirect("/2", StatusCode::SeeOther_303);
  2565. })
  2566. .Get("/2",
  2567. [](const Request & /*req*/, Response &res) {
  2568. res.set_content("redirected.", "text/plain");
  2569. res.status = StatusCode::OK_200;
  2570. })
  2571. .Post("/person",
  2572. [&](const Request &req, Response &res) {
  2573. if (req.has_param("name") && req.has_param("note")) {
  2574. persons_[req.get_param_value("name")] =
  2575. req.get_param_value("note");
  2576. } else {
  2577. res.status = StatusCode::BadRequest_400;
  2578. }
  2579. })
  2580. .Put("/person",
  2581. [&](const Request &req, Response &res) {
  2582. if (req.has_param("name") && req.has_param("note")) {
  2583. persons_[req.get_param_value("name")] =
  2584. req.get_param_value("note");
  2585. } else {
  2586. res.status = StatusCode::BadRequest_400;
  2587. }
  2588. })
  2589. .Get("/person/(.*)",
  2590. [&](const Request &req, Response &res) {
  2591. string name = req.matches[1];
  2592. if (persons_.find(name) != persons_.end()) {
  2593. auto note = persons_[name];
  2594. res.set_content(note, "text/plain");
  2595. } else {
  2596. res.status = StatusCode::NotFound_404;
  2597. }
  2598. })
  2599. .Delete("/person",
  2600. [&](const Request &req, Response &res) {
  2601. if (req.has_param("name")) {
  2602. string name = req.get_param_value("name");
  2603. if (persons_.find(name) != persons_.end()) {
  2604. persons_.erase(name);
  2605. res.set_content("DELETED", "text/plain");
  2606. } else {
  2607. res.status = StatusCode::NotFound_404;
  2608. }
  2609. } else {
  2610. res.status = StatusCode::BadRequest_400;
  2611. }
  2612. })
  2613. .Post("/x-www-form-urlencoded-json",
  2614. [&](const Request &req, Response &res) {
  2615. auto json = req.get_param_value("json");
  2616. ASSERT_EQ(JSON_DATA, json);
  2617. res.set_content(json, "appliation/json");
  2618. res.status = StatusCode::OK_200;
  2619. })
  2620. .Get("/streamed-chunked",
  2621. [&](const Request & /*req*/, Response &res) {
  2622. res.set_chunked_content_provider(
  2623. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2624. sink.os << "123";
  2625. sink.os << "456";
  2626. sink.os << "789";
  2627. sink.done();
  2628. return true;
  2629. });
  2630. })
  2631. .Get("/streamed-chunked-with-prohibited-trailer",
  2632. [&](const Request & /*req*/, Response &res) {
  2633. auto i = new int(0);
  2634. // Declare both a prohibited trailer (Content-Length) and an
  2635. // allowed one
  2636. res.set_header("Trailer", "Content-Length, X-Allowed");
  2637. res.set_chunked_content_provider(
  2638. "text/plain",
  2639. [i](size_t /*offset*/, DataSink &sink) {
  2640. switch (*i) {
  2641. case 0: sink.os << "123"; break;
  2642. case 1: sink.os << "456"; break;
  2643. case 2: sink.os << "789"; break;
  2644. case 3: {
  2645. sink.done_with_trailer(
  2646. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2647. } break;
  2648. }
  2649. (*i)++;
  2650. return true;
  2651. },
  2652. [i](bool success) {
  2653. EXPECT_TRUE(success);
  2654. delete i;
  2655. });
  2656. })
  2657. .Get("/streamed-chunked2",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. auto i = new int(0);
  2660. res.set_chunked_content_provider(
  2661. "text/plain",
  2662. [i](size_t /*offset*/, DataSink &sink) {
  2663. switch (*i) {
  2664. case 0: sink.os << "123"; break;
  2665. case 1: sink.os << "456"; break;
  2666. case 2: sink.os << "789"; break;
  2667. case 3: sink.done(); break;
  2668. }
  2669. (*i)++;
  2670. return true;
  2671. },
  2672. [i](bool success) {
  2673. EXPECT_TRUE(success);
  2674. delete i;
  2675. });
  2676. })
  2677. .Get("/streamed-chunked-with-trailer",
  2678. [&](const Request & /*req*/, Response &res) {
  2679. auto i = new int(0);
  2680. res.set_header("Trailer", "Dummy1, Dummy2");
  2681. res.set_chunked_content_provider(
  2682. "text/plain",
  2683. [i](size_t /*offset*/, DataSink &sink) {
  2684. switch (*i) {
  2685. case 0: sink.os << "123"; break;
  2686. case 1: sink.os << "456"; break;
  2687. case 2: sink.os << "789"; break;
  2688. case 3: {
  2689. sink.done_with_trailer(
  2690. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2691. } break;
  2692. }
  2693. (*i)++;
  2694. return true;
  2695. },
  2696. [i](bool success) {
  2697. EXPECT_TRUE(success);
  2698. delete i;
  2699. });
  2700. })
  2701. .Get("/streamed",
  2702. [&](const Request & /*req*/, Response &res) {
  2703. res.set_content_provider(
  2704. 6, "text/plain",
  2705. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2706. sink.os << (offset < 3 ? "a" : "b");
  2707. return true;
  2708. });
  2709. })
  2710. .Get("/streamed-with-range",
  2711. [&](const Request &req, Response &res) {
  2712. auto data = new std::string("abcdefg");
  2713. res.set_content_provider(
  2714. data->size(), "text/plain",
  2715. [data](size_t offset, size_t length, DataSink &sink) {
  2716. size_t DATA_CHUNK_SIZE = 4;
  2717. const auto &d = *data;
  2718. auto out_len =
  2719. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2720. auto ret =
  2721. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2722. EXPECT_TRUE(ret);
  2723. return true;
  2724. },
  2725. [data, &req](bool success) {
  2726. EXPECT_EQ(success, !req.has_param("error"));
  2727. delete data;
  2728. });
  2729. })
  2730. .Get("/streamed-cancel",
  2731. [&](const Request & /*req*/, Response &res) {
  2732. res.set_content_provider(
  2733. size_t(-1), "text/plain",
  2734. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2735. sink.os << "data_chunk";
  2736. return true;
  2737. });
  2738. })
  2739. .Get("/regex-with-delimiter",
  2740. [&](const Request &req, Response & /*res*/) {
  2741. ASSERT_TRUE(req.has_param("key"));
  2742. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2743. })
  2744. .Get("/with-range",
  2745. [&](const Request & /*req*/, Response &res) {
  2746. res.set_content("abcdefg", "text/plain");
  2747. })
  2748. .Get("/test-start-time",
  2749. [&](const Request &req, Response & /*res*/) {
  2750. EXPECT_NE(req.start_time_,
  2751. std::chrono::steady_clock::time_point::min());
  2752. })
  2753. .Get("/with-range-customized-response",
  2754. [&](const Request & /*req*/, Response &res) {
  2755. res.status = StatusCode::BadRequest_400;
  2756. res.set_content(JSON_DATA, "application/json");
  2757. })
  2758. .Post("/chunked",
  2759. [&](const Request &req, Response & /*res*/) {
  2760. EXPECT_EQ(req.body, "dechunked post body");
  2761. })
  2762. .Post("/large-chunked",
  2763. [&](const Request &req, Response & /*res*/) {
  2764. std::string expected(6 * 30 * 1024u, 'a');
  2765. EXPECT_EQ(req.body, expected);
  2766. })
  2767. .Post("/multipart",
  2768. [&](const Request &req, Response & /*res*/) {
  2769. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2770. req.form.get_field_count("text2") +
  2771. req.form.get_field_count("file3") +
  2772. req.form.get_field_count("file4"));
  2773. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2774. req.form.get_file_count("file2"));
  2775. ASSERT_TRUE(!req.form.has_file("???"));
  2776. ASSERT_TRUE(!req.form.has_field("???"));
  2777. ASSERT_TRUE(req.body.empty());
  2778. {
  2779. const auto &text = req.form.get_field("text1");
  2780. EXPECT_EQ("text default", text);
  2781. }
  2782. {
  2783. const auto &text = req.form.get_field("text2");
  2784. EXPECT_EQ("aωb", text);
  2785. }
  2786. {
  2787. const auto &file = req.form.get_file("file1");
  2788. EXPECT_EQ("hello.txt", file.filename);
  2789. EXPECT_EQ("text/plain", file.content_type);
  2790. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2791. }
  2792. {
  2793. const auto &file = req.form.get_file("file2");
  2794. EXPECT_EQ("world.json", file.filename);
  2795. EXPECT_EQ("application/json", file.content_type);
  2796. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2797. }
  2798. {
  2799. const auto &text = req.form.get_field("file3");
  2800. EXPECT_EQ(0u, text.size());
  2801. }
  2802. {
  2803. const auto &text = req.form.get_field("file4");
  2804. EXPECT_EQ(0u, text.size());
  2805. }
  2806. })
  2807. .Post("/multipart/multi_file_values",
  2808. [&](const Request &req, Response & /*res*/) {
  2809. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2810. req.form.get_field_count("multi_text1"));
  2811. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2812. ASSERT_TRUE(!req.form.has_file("???"));
  2813. ASSERT_TRUE(!req.form.has_field("???"));
  2814. ASSERT_TRUE(req.body.empty());
  2815. {
  2816. const auto &text = req.form.get_field("text");
  2817. EXPECT_EQ("default text", text);
  2818. }
  2819. {
  2820. const auto &text1_values = req.form.get_fields("multi_text1");
  2821. EXPECT_EQ(2u, text1_values.size());
  2822. EXPECT_EQ("aaaaa", text1_values[0]);
  2823. EXPECT_EQ("bbbbb", text1_values[1]);
  2824. }
  2825. {
  2826. const auto &file1_values = req.form.get_files("multi_file1");
  2827. EXPECT_EQ(2u, file1_values.size());
  2828. auto file1 = file1_values[0];
  2829. EXPECT_EQ(file1.filename, "hello.txt");
  2830. EXPECT_EQ(file1.content_type, "text/plain");
  2831. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2832. auto file2 = file1_values[1];
  2833. EXPECT_EQ(file2.filename, "world.json");
  2834. EXPECT_EQ(file2.content_type, "application/json");
  2835. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2836. }
  2837. })
  2838. .Post("/empty",
  2839. [&](const Request &req, Response &res) {
  2840. EXPECT_EQ(req.body, "");
  2841. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2842. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2843. res.set_content("empty", "text/plain");
  2844. })
  2845. .Post("/empty-no-content-type",
  2846. [&](const Request &req, Response &res) {
  2847. EXPECT_EQ(req.body, "");
  2848. EXPECT_FALSE(req.has_header("Content-Type"));
  2849. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2850. res.set_content("empty-no-content-type", "text/plain");
  2851. })
  2852. .Post("/path-only",
  2853. [&](const Request &req, Response &res) {
  2854. EXPECT_EQ(req.body, "");
  2855. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2856. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2857. res.set_content("path-only", "text/plain");
  2858. })
  2859. .Post("/path-headers-only",
  2860. [&](const Request &req, Response &res) {
  2861. EXPECT_EQ(req.body, "");
  2862. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2863. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2864. EXPECT_EQ("world", req.get_header_value("hello"));
  2865. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2866. res.set_content("path-headers-only", "text/plain");
  2867. })
  2868. .Post("/post-large",
  2869. [&](const Request &req, Response &res) {
  2870. EXPECT_EQ(req.body, LARGE_DATA);
  2871. res.set_content(req.body, "text/plain");
  2872. })
  2873. .Post("/post-loopback",
  2874. [&](const Request &, Response &res,
  2875. ContentReader const &content_reader) {
  2876. std::string body;
  2877. content_reader([&](const char *data, size_t data_length) {
  2878. body.append(data, data_length);
  2879. return true;
  2880. });
  2881. res.set_content(body, "text/plain");
  2882. })
  2883. .Put("/put-loopback",
  2884. [&](const Request &, Response &res,
  2885. ContentReader const &content_reader) {
  2886. std::string body;
  2887. content_reader([&](const char *data, size_t data_length) {
  2888. body.append(data, data_length);
  2889. return true;
  2890. });
  2891. res.set_content(body, "text/plain");
  2892. })
  2893. .Patch("/patch-loopback",
  2894. [&](const Request &, Response &res,
  2895. ContentReader const &content_reader) {
  2896. std::string body;
  2897. content_reader([&](const char *data, size_t data_length) {
  2898. body.append(data, data_length);
  2899. return true;
  2900. });
  2901. res.set_content(body, "text/plain");
  2902. })
  2903. .Put("/empty-no-content-type",
  2904. [&](const Request &req, Response &res) {
  2905. EXPECT_EQ(req.body, "");
  2906. EXPECT_FALSE(req.has_header("Content-Type"));
  2907. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2908. res.set_content("empty-no-content-type", "text/plain");
  2909. })
  2910. .Put("/put",
  2911. [&](const Request &req, Response &res) {
  2912. EXPECT_EQ(req.body, "PUT");
  2913. res.set_content(req.body, "text/plain");
  2914. })
  2915. .Put("/put-large",
  2916. [&](const Request &req, Response &res) {
  2917. EXPECT_EQ(req.body, LARGE_DATA);
  2918. res.set_content(req.body, "text/plain");
  2919. })
  2920. .Patch("/patch",
  2921. [&](const Request &req, Response &res) {
  2922. EXPECT_EQ(req.body, "PATCH");
  2923. res.set_content(req.body, "text/plain");
  2924. })
  2925. .Delete("/delete",
  2926. [&](const Request & /*req*/, Response &res) {
  2927. res.set_content("DELETE", "text/plain");
  2928. })
  2929. .Delete("/delete-body",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "content");
  2932. res.set_content(req.body, "text/plain");
  2933. })
  2934. .Options(R"(\*)",
  2935. [&](const Request & /*req*/, Response &res) {
  2936. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2937. })
  2938. .Get("/request-target",
  2939. [&](const Request &req, Response & /*res*/) {
  2940. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2941. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2942. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2943. })
  2944. .Get("/long-query-value",
  2945. [&](const Request &req, Response & /*res*/) {
  2946. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2947. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2948. })
  2949. .Get("/too-long-query-value",
  2950. [&](const Request &req, Response & /*res*/) {
  2951. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2952. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2953. })
  2954. .Get("/array-param",
  2955. [&](const Request &req, Response & /*res*/) {
  2956. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2957. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2958. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2959. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2960. })
  2961. .Post("/validate-no-multiple-headers",
  2962. [&](const Request &req, Response & /*res*/) {
  2963. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2964. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2965. })
  2966. .Post("/content_receiver",
  2967. [&](const Request &req, Response &res,
  2968. const ContentReader &content_reader) {
  2969. if (req.is_multipart_form_data()) {
  2970. std::vector<FormData> items;
  2971. content_reader(
  2972. [&](const FormData &file) {
  2973. items.push_back(file);
  2974. return true;
  2975. },
  2976. [&](const char *data, size_t data_length) {
  2977. items.back().content.append(data, data_length);
  2978. return true;
  2979. });
  2980. EXPECT_EQ(5u, items.size());
  2981. {
  2982. const auto &file = get_file_value(items, "text1");
  2983. EXPECT_TRUE(file.filename.empty());
  2984. EXPECT_EQ("text default", file.content);
  2985. }
  2986. {
  2987. const auto &file = get_file_value(items, "text2");
  2988. EXPECT_TRUE(file.filename.empty());
  2989. EXPECT_EQ("aωb", file.content);
  2990. }
  2991. {
  2992. const auto &file = get_file_value(items, "file1");
  2993. EXPECT_EQ("hello.txt", file.filename);
  2994. EXPECT_EQ("text/plain", file.content_type);
  2995. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2996. }
  2997. {
  2998. const auto &file = get_file_value(items, "file2");
  2999. EXPECT_EQ("world.json", file.filename);
  3000. EXPECT_EQ("application/json", file.content_type);
  3001. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3002. }
  3003. {
  3004. const auto &file = get_file_value(items, "file3");
  3005. EXPECT_TRUE(file.filename.empty());
  3006. EXPECT_EQ("application/octet-stream", file.content_type);
  3007. EXPECT_EQ(0u, file.content.size());
  3008. }
  3009. } else {
  3010. std::string body;
  3011. content_reader([&](const char *data, size_t data_length) {
  3012. EXPECT_EQ(7U, data_length);
  3013. body.append(data, data_length);
  3014. return true;
  3015. });
  3016. EXPECT_EQ(body, "content");
  3017. res.set_content(body, "text/plain");
  3018. }
  3019. })
  3020. .Put("/content_receiver",
  3021. [&](const Request & /*req*/, Response &res,
  3022. const ContentReader &content_reader) {
  3023. std::string body;
  3024. content_reader([&](const char *data, size_t data_length) {
  3025. body.append(data, data_length);
  3026. return true;
  3027. });
  3028. EXPECT_EQ(body, "content");
  3029. res.set_content(body, "text/plain");
  3030. })
  3031. .Patch("/content_receiver",
  3032. [&](const Request & /*req*/, Response &res,
  3033. const ContentReader &content_reader) {
  3034. std::string body;
  3035. content_reader([&](const char *data, size_t data_length) {
  3036. body.append(data, data_length);
  3037. return true;
  3038. });
  3039. EXPECT_EQ(body, "content");
  3040. res.set_content(body, "text/plain");
  3041. })
  3042. .Post("/query-string-and-body",
  3043. [&](const Request &req, Response & /*res*/) {
  3044. ASSERT_TRUE(req.has_param("key"));
  3045. EXPECT_EQ(req.get_param_value("key"), "value");
  3046. EXPECT_EQ(req.body, "content");
  3047. })
  3048. .Get("/last-request",
  3049. [&](const Request &req, Response & /*res*/) {
  3050. EXPECT_EQ("close", req.get_header_value("Connection"));
  3051. })
  3052. .Get(R"(/redirect/(\d+))",
  3053. [&](const Request &req, Response &res) {
  3054. auto num = std::stoi(req.matches[1]) + 1;
  3055. std::string url = "/redirect/" + std::to_string(num);
  3056. res.set_redirect(url);
  3057. })
  3058. .Post("/binary",
  3059. [&](const Request &req, Response &res) {
  3060. EXPECT_EQ(4U, req.body.size());
  3061. EXPECT_EQ("application/octet-stream",
  3062. req.get_header_value("Content-Type"));
  3063. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3064. res.set_content(req.body, "application/octet-stream");
  3065. })
  3066. .Put("/binary",
  3067. [&](const Request &req, Response &res) {
  3068. EXPECT_EQ(4U, req.body.size());
  3069. EXPECT_EQ("application/octet-stream",
  3070. req.get_header_value("Content-Type"));
  3071. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3072. res.set_content(req.body, "application/octet-stream");
  3073. })
  3074. .Patch("/binary",
  3075. [&](const Request &req, Response &res) {
  3076. EXPECT_EQ(4U, req.body.size());
  3077. EXPECT_EQ("application/octet-stream",
  3078. req.get_header_value("Content-Type"));
  3079. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3080. res.set_content(req.body, "application/octet-stream");
  3081. })
  3082. .Delete("/binary",
  3083. [&](const Request &req, Response &res) {
  3084. EXPECT_EQ(4U, req.body.size());
  3085. EXPECT_EQ("application/octet-stream",
  3086. req.get_header_value("Content-Type"));
  3087. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3088. res.set_content(req.body, "application/octet-stream");
  3089. })
  3090. .Get("/issue1772",
  3091. [&](const Request & /*req*/, Response &res) {
  3092. res.status = 401;
  3093. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3094. })
  3095. .Delete("/issue609",
  3096. [](const httplib::Request &, httplib::Response &res,
  3097. const httplib::ContentReader &) {
  3098. res.set_content("ok", "text/plain");
  3099. })
  3100. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3101. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3102. .Get("/compress",
  3103. [&](const Request & /*req*/, Response &res) {
  3104. res.set_content(
  3105. "12345678901234567890123456789012345678901234567890123456789"
  3106. "01234567890123456789012345678901234567890",
  3107. "text/plain");
  3108. })
  3109. .Get("/nocompress",
  3110. [&](const Request & /*req*/, Response &res) {
  3111. res.set_content(
  3112. "12345678901234567890123456789012345678901234567890123456789"
  3113. "01234567890123456789012345678901234567890",
  3114. "application/octet-stream");
  3115. })
  3116. .Post("/compress-multipart",
  3117. [&](const Request &req, Response & /*res*/) {
  3118. EXPECT_EQ(2u, req.form.fields.size());
  3119. ASSERT_TRUE(!req.form.has_field("???"));
  3120. {
  3121. const auto &text = req.form.get_field("key1");
  3122. EXPECT_EQ("test", text);
  3123. }
  3124. {
  3125. const auto &text = req.form.get_field("key2");
  3126. EXPECT_EQ("--abcdefg123", text);
  3127. }
  3128. })
  3129. #endif
  3130. ;
  3131. persons_["john"] = "programmer";
  3132. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3133. svr_.wait_until_ready();
  3134. }
  3135. virtual void TearDown() {
  3136. svr_.stop();
  3137. if (!request_threads_.empty()) {
  3138. std::this_thread::sleep_for(std::chrono::seconds(1));
  3139. for (auto &t : request_threads_) {
  3140. t.join();
  3141. }
  3142. }
  3143. t_.join();
  3144. }
  3145. map<string, string> persons_;
  3146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3147. SSLClient cli_;
  3148. SSLServer svr_;
  3149. #else
  3150. Client cli_;
  3151. Server svr_;
  3152. #endif
  3153. thread t_;
  3154. std::vector<thread> request_threads_;
  3155. };
  3156. TEST_F(ServerTest, GetMethod200) {
  3157. auto res = cli_.Get("/hi");
  3158. ASSERT_TRUE(res);
  3159. EXPECT_EQ("HTTP/1.1", res->version);
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. EXPECT_EQ("OK", res->reason);
  3162. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3163. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3164. EXPECT_EQ("Hello World!", res->body);
  3165. }
  3166. TEST_F(ServerTest, GetEmptyFile) {
  3167. auto res = cli_.Get("/empty_file");
  3168. ASSERT_TRUE(res);
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3171. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3172. EXPECT_EQ("", res->body);
  3173. }
  3174. TEST_F(ServerTest, GetFileContent) {
  3175. auto res = cli_.Get("/file_content");
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3179. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3180. EXPECT_EQ("test.html", res->body);
  3181. }
  3182. TEST_F(ServerTest, GetFileContentWithRange) {
  3183. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3186. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3187. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3188. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3189. EXPECT_EQ("est", res->body);
  3190. }
  3191. TEST_F(ServerTest, GetFileContentWithContentType) {
  3192. auto res = cli_.Get("/file_content_with_content_type");
  3193. ASSERT_TRUE(res);
  3194. EXPECT_EQ(StatusCode::OK_200, res->status);
  3195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3196. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3197. EXPECT_EQ("file\n", res->body);
  3198. }
  3199. TEST_F(ServerTest, GetInvalidFileContent) {
  3200. auto res = cli_.Get("/invalid_file_content");
  3201. ASSERT_TRUE(res);
  3202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3203. }
  3204. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3205. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ("HTTP/1.1", res->version);
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3210. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3211. EXPECT_EQ("Hello World!", res->body);
  3212. }
  3213. TEST_F(ServerTest, GetMethod302) {
  3214. auto res = cli_.Get("/");
  3215. ASSERT_TRUE(res);
  3216. EXPECT_EQ(StatusCode::Found_302, res->status);
  3217. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3218. }
  3219. TEST_F(ServerTest, GetMethod302Redirect) {
  3220. cli_.set_follow_location(true);
  3221. auto res = cli_.Get("/");
  3222. ASSERT_TRUE(res);
  3223. EXPECT_EQ(StatusCode::OK_200, res->status);
  3224. EXPECT_EQ("Hello World!", res->body);
  3225. EXPECT_EQ("/hi", res->location);
  3226. }
  3227. TEST_F(ServerTest, GetMethod404) {
  3228. auto res = cli_.Get("/invalid");
  3229. ASSERT_TRUE(res);
  3230. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3231. }
  3232. TEST_F(ServerTest, HeadMethod200) {
  3233. auto res = cli_.Head("/hi");
  3234. ASSERT_TRUE(res);
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3237. EXPECT_TRUE(res->body.empty());
  3238. }
  3239. TEST_F(ServerTest, HeadMethod200Static) {
  3240. auto res = cli_.Head("/mount/dir/index.html");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3244. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3245. EXPECT_TRUE(res->body.empty());
  3246. }
  3247. TEST_F(ServerTest, HeadMethod404) {
  3248. auto res = cli_.Head("/invalid");
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3251. EXPECT_TRUE(res->body.empty());
  3252. }
  3253. TEST_F(ServerTest, GetMethodPersonJohn) {
  3254. auto res = cli_.Get("/person/john");
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3258. EXPECT_EQ("programmer", res->body);
  3259. }
  3260. TEST_F(ServerTest, PostMethod1) {
  3261. auto res = cli_.Get("/person/john1");
  3262. ASSERT_TRUE(res);
  3263. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3264. res = cli_.Post("/person", "name=john1&note=coder",
  3265. "application/x-www-form-urlencoded");
  3266. ASSERT_TRUE(res);
  3267. ASSERT_EQ(StatusCode::OK_200, res->status);
  3268. res = cli_.Get("/person/john1");
  3269. ASSERT_TRUE(res);
  3270. ASSERT_EQ(StatusCode::OK_200, res->status);
  3271. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3272. ASSERT_EQ("coder", res->body);
  3273. }
  3274. TEST_F(ServerTest, PostMethod2) {
  3275. auto res = cli_.Get("/person/john2");
  3276. ASSERT_TRUE(res);
  3277. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3278. Params params;
  3279. params.emplace("name", "john2");
  3280. params.emplace("note", "coder");
  3281. res = cli_.Post("/person", params);
  3282. ASSERT_TRUE(res);
  3283. ASSERT_EQ(StatusCode::OK_200, res->status);
  3284. res = cli_.Get("/person/john2");
  3285. ASSERT_TRUE(res);
  3286. ASSERT_EQ(StatusCode::OK_200, res->status);
  3287. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3288. ASSERT_EQ("coder", res->body);
  3289. }
  3290. TEST_F(ServerTest, PutMethod3) {
  3291. auto res = cli_.Get("/person/john3");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3294. Params params;
  3295. params.emplace("name", "john3");
  3296. params.emplace("note", "coder");
  3297. res = cli_.Put("/person", params);
  3298. ASSERT_TRUE(res);
  3299. ASSERT_EQ(StatusCode::OK_200, res->status);
  3300. res = cli_.Get("/person/john3");
  3301. ASSERT_TRUE(res);
  3302. ASSERT_EQ(StatusCode::OK_200, res->status);
  3303. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3304. ASSERT_EQ("coder", res->body);
  3305. }
  3306. TEST_F(ServerTest, DeleteMethod1) {
  3307. auto res = cli_.Get("/person/john4");
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3310. Params params;
  3311. params.emplace("name", "john4");
  3312. params.emplace("note", "coder");
  3313. res = cli_.Post("/person", params);
  3314. ASSERT_TRUE(res);
  3315. ASSERT_EQ(StatusCode::OK_200, res->status);
  3316. res = cli_.Get("/person/john4");
  3317. ASSERT_TRUE(res);
  3318. ASSERT_EQ(StatusCode::OK_200, res->status);
  3319. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3320. ASSERT_EQ("coder", res->body);
  3321. Params delete_params;
  3322. delete_params.emplace("name", "john4");
  3323. res = cli_.Delete("/person", delete_params);
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::OK_200, res->status);
  3326. ASSERT_EQ("DELETED", res->body);
  3327. res = cli_.Get("/person/john4");
  3328. ASSERT_TRUE(res);
  3329. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3330. }
  3331. TEST_F(ServerTest, DeleteMethod2) {
  3332. auto res = cli_.Get("/person/john5");
  3333. ASSERT_TRUE(res);
  3334. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3335. Params params;
  3336. params.emplace("name", "john5");
  3337. params.emplace("note", "developer");
  3338. res = cli_.Post("/person", params);
  3339. ASSERT_TRUE(res);
  3340. ASSERT_EQ(StatusCode::OK_200, res->status);
  3341. res = cli_.Get("/person/john5");
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::OK_200, res->status);
  3344. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3345. ASSERT_EQ("developer", res->body);
  3346. Params delete_params;
  3347. delete_params.emplace("name", "john5");
  3348. Headers headers;
  3349. headers.emplace("Custom-Header", "test-value");
  3350. res = cli_.Delete("/person", headers, delete_params);
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ("DELETED", res->body);
  3354. res = cli_.Get("/person/john5");
  3355. ASSERT_TRUE(res);
  3356. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3357. }
  3358. TEST_F(ServerTest, DeleteMethod3) {
  3359. auto res = cli_.Get("/person/john6");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3362. Params params;
  3363. params.emplace("name", "john6");
  3364. params.emplace("note", "tester");
  3365. res = cli_.Post("/person", params);
  3366. ASSERT_TRUE(res);
  3367. ASSERT_EQ(StatusCode::OK_200, res->status);
  3368. res = cli_.Get("/person/john6");
  3369. ASSERT_TRUE(res);
  3370. ASSERT_EQ(StatusCode::OK_200, res->status);
  3371. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3372. ASSERT_EQ("tester", res->body);
  3373. Params delete_params;
  3374. delete_params.emplace("name", "john6");
  3375. Headers headers;
  3376. headers.emplace("Custom-Header", "test-value");
  3377. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3378. ASSERT_TRUE(res);
  3379. ASSERT_EQ(StatusCode::OK_200, res->status);
  3380. ASSERT_EQ("DELETED", res->body);
  3381. res = cli_.Get("/person/john6");
  3382. ASSERT_TRUE(res);
  3383. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3384. }
  3385. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3386. Params params;
  3387. params.emplace("json", JSON_DATA);
  3388. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::OK_200, res->status);
  3391. ASSERT_EQ(JSON_DATA, res->body);
  3392. }
  3393. TEST_F(ServerTest, PostEmptyContent) {
  3394. auto res = cli_.Post("/empty", "", "text/plain");
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("empty", res->body);
  3398. }
  3399. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3400. auto res = cli_.Post("/empty-no-content-type");
  3401. ASSERT_TRUE(res);
  3402. ASSERT_EQ(StatusCode::OK_200, res->status);
  3403. ASSERT_EQ("empty-no-content-type", res->body);
  3404. }
  3405. TEST_F(ServerTest, PostPathOnly) {
  3406. auto res = cli_.Post("/path-only");
  3407. ASSERT_TRUE(res);
  3408. ASSERT_EQ(StatusCode::OK_200, res->status);
  3409. ASSERT_EQ("path-only", res->body);
  3410. }
  3411. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3412. auto res = cli_.Post("/path-headers-only",
  3413. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3414. ASSERT_TRUE(res);
  3415. ASSERT_EQ(StatusCode::OK_200, res->status);
  3416. ASSERT_EQ("path-headers-only", res->body);
  3417. }
  3418. TEST_F(ServerTest, PostLarge) {
  3419. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3420. ASSERT_TRUE(res);
  3421. ASSERT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ(LARGE_DATA, res->body);
  3423. }
  3424. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3425. auto res = cli_.Put("/empty-no-content-type");
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::OK_200, res->status);
  3428. ASSERT_EQ("empty-no-content-type", res->body);
  3429. }
  3430. TEST_F(ServerTest, GetMethodDir) {
  3431. auto res = cli_.Get("/dir/");
  3432. ASSERT_TRUE(res);
  3433. EXPECT_EQ(StatusCode::OK_200, res->status);
  3434. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3435. auto body = R"(<html>
  3436. <head>
  3437. </head>
  3438. <body>
  3439. <a href="/dir/test.html">Test</a>
  3440. <a href="/hi">hi</a>
  3441. </body>
  3442. </html>
  3443. )";
  3444. EXPECT_EQ(body, res->body);
  3445. }
  3446. TEST_F(ServerTest, GetMethodDirTest) {
  3447. auto res = cli_.Get("/dir/test.html");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ("test.html", res->body);
  3452. }
  3453. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3454. auto res = cli_.Get("/dir/../dir/test.html");
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::OK_200, res->status);
  3457. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("test.html", res->body);
  3459. }
  3460. TEST_F(ServerTest, GetMethodInvalidPath) {
  3461. auto res = cli_.Get("/dir/../test.html");
  3462. ASSERT_TRUE(res);
  3463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3464. }
  3465. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3466. auto res = cli_.Get("/../www/dir/test.html");
  3467. ASSERT_TRUE(res);
  3468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3469. }
  3470. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3471. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3472. ASSERT_TRUE(res);
  3473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3474. }
  3475. TEST_F(ServerTest, GetMethodDirMountTest) {
  3476. auto res = cli_.Get("/mount/dir/test.html");
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3480. EXPECT_EQ("test.html", res->body);
  3481. }
  3482. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3483. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3487. EXPECT_EQ("test.html", res->body);
  3488. }
  3489. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3490. auto res = cli_.Get("/mount/dir/../test.html");
  3491. ASSERT_TRUE(res);
  3492. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3493. }
  3494. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3495. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3498. }
  3499. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3500. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3503. }
  3504. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3505. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3508. }
  3509. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3510. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3513. }
  3514. TEST_F(ServerTest, PostMethod303) {
  3515. auto res = cli_.Post("/1", "body", "text/plain");
  3516. ASSERT_TRUE(res);
  3517. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3518. EXPECT_EQ("/2", res->get_header_value("Location"));
  3519. }
  3520. TEST_F(ServerTest, PostMethod303Redirect) {
  3521. cli_.set_follow_location(true);
  3522. auto res = cli_.Post("/1", "body", "text/plain");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ("redirected.", res->body);
  3526. EXPECT_EQ("/2", res->location);
  3527. }
  3528. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3529. auto res = cli_.Get("/dir/test.abcde");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3533. EXPECT_EQ("abcde", res->body);
  3534. }
  3535. TEST_F(ServerTest, StaticFileRange) {
  3536. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3539. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3540. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3541. EXPECT_EQ(true, res->has_header("Content-Range"));
  3542. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3543. EXPECT_EQ(std::string("cd"), res->body);
  3544. }
  3545. TEST_F(ServerTest, StaticFileRanges) {
  3546. auto res =
  3547. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3548. ASSERT_TRUE(res);
  3549. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3550. EXPECT_TRUE(
  3551. res->get_header_value("Content-Type")
  3552. .find(
  3553. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3554. 0);
  3555. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3556. }
  3557. TEST_F(ServerTest, StaticFileRangeHead) {
  3558. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3561. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3563. EXPECT_EQ(true, res->has_header("Content-Range"));
  3564. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3565. }
  3566. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3567. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3568. ASSERT_TRUE(res);
  3569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3571. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3572. EXPECT_EQ(true, res->has_header("Content-Range"));
  3573. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3574. res->get_header_value("Content-Range"));
  3575. EXPECT_EQ("LAST\n", res->body);
  3576. }
  3577. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3578. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3579. ASSERT_TRUE(res);
  3580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3582. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3583. EXPECT_EQ(true, res->has_header("Content-Range"));
  3584. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3585. }
  3586. TEST_F(ServerTest, StaticFileBigFile) {
  3587. auto res = cli_.Get("/dir/1MB.txt");
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::OK_200, res->status);
  3590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3591. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3592. }
  3593. TEST_F(ServerTest, InvalidBaseDirMount) {
  3594. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3595. }
  3596. TEST_F(ServerTest, Binary) {
  3597. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3598. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3599. "application/octet-stream");
  3600. ASSERT_TRUE(res);
  3601. ASSERT_EQ(StatusCode::OK_200, res->status);
  3602. ASSERT_EQ(4U, res->body.size());
  3603. res = cli_.Put("/binary", binary.data(), binary.size(),
  3604. "application/octet-stream");
  3605. ASSERT_TRUE(res);
  3606. ASSERT_EQ(StatusCode::OK_200, res->status);
  3607. ASSERT_EQ(4U, res->body.size());
  3608. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3609. "application/octet-stream");
  3610. ASSERT_TRUE(res);
  3611. ASSERT_EQ(StatusCode::OK_200, res->status);
  3612. ASSERT_EQ(4U, res->body.size());
  3613. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3614. "application/octet-stream");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::OK_200, res->status);
  3617. ASSERT_EQ(4U, res->body.size());
  3618. }
  3619. TEST_F(ServerTest, BinaryString) {
  3620. auto binary = std::string("\x00\x01\x02\x03", 4);
  3621. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3622. ASSERT_TRUE(res);
  3623. ASSERT_EQ(StatusCode::OK_200, res->status);
  3624. ASSERT_EQ(4U, res->body.size());
  3625. res = cli_.Put("/binary", binary, "application/octet-stream");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ(4U, res->body.size());
  3629. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3630. ASSERT_TRUE(res);
  3631. ASSERT_EQ(StatusCode::OK_200, res->status);
  3632. ASSERT_EQ(4U, res->body.size());
  3633. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3634. ASSERT_TRUE(res);
  3635. ASSERT_EQ(StatusCode::OK_200, res->status);
  3636. ASSERT_EQ(4U, res->body.size());
  3637. }
  3638. TEST_F(ServerTest, EmptyRequest) {
  3639. auto res = cli_.Get("");
  3640. ASSERT_TRUE(!res);
  3641. EXPECT_EQ(Error::Connection, res.error());
  3642. }
  3643. TEST_F(ServerTest, LongRequest) {
  3644. std::string request;
  3645. for (size_t i = 0; i < 545; i++) {
  3646. request += "/TooLongRequest";
  3647. }
  3648. request += "OK";
  3649. auto res = cli_.Get(request.c_str());
  3650. ASSERT_TRUE(res);
  3651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3652. }
  3653. TEST_F(ServerTest, TooLongRequest) {
  3654. std::string request;
  3655. for (size_t i = 0; i < 546; i++) {
  3656. request += "/TooLongRequest";
  3657. }
  3658. request += "_NG";
  3659. auto start = std::chrono::high_resolution_clock::now();
  3660. cli_.set_keep_alive(true);
  3661. auto res = cli_.Get(request.c_str());
  3662. auto end = std::chrono::high_resolution_clock::now();
  3663. auto elapsed =
  3664. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3665. .count();
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3668. EXPECT_LE(elapsed, 100);
  3669. EXPECT_EQ("close", res->get_header_value("Connection"));
  3670. EXPECT_FALSE(cli_.is_socket_open());
  3671. }
  3672. TEST_F(ServerTest, AlmostTooLongRequest) {
  3673. // test for #2046 - URI length check shouldn't include other content on req
  3674. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3675. // leading /, space, HTTP/1.1)
  3676. std::string request =
  3677. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3678. auto res = cli_.Get(request.c_str());
  3679. ASSERT_TRUE(res);
  3680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3681. }
  3682. TEST_F(ServerTest, LongHeader) {
  3683. Request req;
  3684. req.method = "GET";
  3685. req.path = "/hi";
  3686. std::string host_and_port;
  3687. host_and_port += HOST;
  3688. host_and_port += ":";
  3689. host_and_port += std::to_string(PORT);
  3690. req.headers.emplace("Host", host_and_port.c_str());
  3691. req.headers.emplace("Accept", "*/*");
  3692. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3693. req.headers.emplace(
  3694. "Header-Name",
  3695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@");
  3724. auto res = std::make_shared<Response>();
  3725. auto error = Error::Success;
  3726. auto ret = cli_.send(req, *res, error);
  3727. ASSERT_TRUE(ret);
  3728. EXPECT_EQ(StatusCode::OK_200, res->status);
  3729. }
  3730. TEST_F(ServerTest, LongQueryValue) {
  3731. auto start = std::chrono::high_resolution_clock::now();
  3732. cli_.set_keep_alive(true);
  3733. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3734. auto end = std::chrono::high_resolution_clock::now();
  3735. auto elapsed =
  3736. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3737. .count();
  3738. ASSERT_TRUE(res);
  3739. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3740. EXPECT_LE(elapsed, 100);
  3741. EXPECT_EQ("close", res->get_header_value("Connection"));
  3742. EXPECT_FALSE(cli_.is_socket_open());
  3743. }
  3744. TEST_F(ServerTest, TooLongQueryValue) {
  3745. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3746. ASSERT_FALSE(res);
  3747. EXPECT_EQ(Error::Read, res.error());
  3748. }
  3749. TEST_F(ServerTest, TooLongHeader) {
  3750. Request req;
  3751. req.method = "GET";
  3752. req.path = "/hi";
  3753. std::string host_and_port;
  3754. host_and_port += HOST;
  3755. host_and_port += ":";
  3756. host_and_port += std::to_string(PORT);
  3757. req.headers.emplace("Host", host_and_port.c_str());
  3758. req.headers.emplace("Accept", "*/*");
  3759. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3760. req.headers.emplace(
  3761. "Header-Name",
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@");
  3791. auto res = std::make_shared<Response>();
  3792. auto error = Error::Success;
  3793. auto ret = cli_.send(req, *res, error);
  3794. ASSERT_TRUE(ret);
  3795. EXPECT_EQ(StatusCode::OK_200, res->status);
  3796. }
  3797. TEST_F(ServerTest, HeaderCountAtLimit) {
  3798. // Test with headers just under the 100 limit
  3799. httplib::Headers headers;
  3800. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3801. // This should keep us just under the 100 header limit
  3802. for (int i = 0; i < 95; i++) {
  3803. std::string name = "X-Test-Header-" + std::to_string(i);
  3804. std::string value = "value" + std::to_string(i);
  3805. headers.emplace(name, value);
  3806. }
  3807. // This should work fine as we're under the limit
  3808. auto res = cli_.Get("/hi", headers);
  3809. EXPECT_TRUE(res);
  3810. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3811. }
  3812. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3813. // Test with many headers to exceed the 100 limit
  3814. httplib::Headers headers;
  3815. // Add 150 headers to definitely exceed the 100 limit
  3816. for (int i = 0; i < 150; i++) {
  3817. std::string name = "X-Test-Header-" + std::to_string(i);
  3818. std::string value = "value" + std::to_string(i);
  3819. headers.emplace(name, value);
  3820. }
  3821. // This should fail due to exceeding header count limit
  3822. cli_.set_keep_alive(true);
  3823. auto res = cli_.Get("/hi", headers);
  3824. // The request should either fail or return 400 Bad Request
  3825. if (res) {
  3826. // If we get a response, it should be 400 Bad Request
  3827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3828. } else {
  3829. // Or the request should fail entirely
  3830. EXPECT_FALSE(res);
  3831. }
  3832. EXPECT_EQ("close", res->get_header_value("Connection"));
  3833. EXPECT_FALSE(cli_.is_socket_open());
  3834. }
  3835. TEST_F(ServerTest, PercentEncoding) {
  3836. auto res = cli_.Get("/e%6edwith%");
  3837. ASSERT_TRUE(res);
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. }
  3840. TEST_F(ServerTest, PercentEncodingUnicode) {
  3841. auto res = cli_.Get("/e%u006edwith%");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::OK_200, res->status);
  3844. }
  3845. TEST_F(ServerTest, InvalidPercentEncoding) {
  3846. auto res = cli_.Get("/%endwith%");
  3847. ASSERT_TRUE(res);
  3848. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3849. }
  3850. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3851. auto res = cli_.Get("/%uendwith%");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3854. }
  3855. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3856. auto res = cli_.Get("/hello?aaa=bbb%");
  3857. ASSERT_TRUE(res);
  3858. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3859. }
  3860. TEST_F(ServerTest, PlusSignEncoding) {
  3861. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3862. ASSERT_TRUE(res);
  3863. EXPECT_EQ(StatusCode::OK_200, res->status);
  3864. EXPECT_EQ("a +b", res->body);
  3865. }
  3866. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3867. // This test simulates a potential DoS attack using many headers
  3868. // to verify our security fix prevents memory exhaustion
  3869. httplib::Headers attack_headers;
  3870. // Attempt to add many headers like an attacker would (200 headers to far
  3871. // exceed limit)
  3872. for (int i = 0; i < 200; i++) {
  3873. std::string name = "X-Attack-Header-" + std::to_string(i);
  3874. std::string value = "attack_payload_" + std::to_string(i);
  3875. attack_headers.emplace(name, value);
  3876. }
  3877. // Try to POST with excessive headers
  3878. cli_.set_keep_alive(true);
  3879. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3880. // Should either fail or return 400 Bad Request due to security limit
  3881. if (res) {
  3882. // If we get a response, it should be 400 Bad Request
  3883. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3884. } else {
  3885. // Request failed, which is the expected behavior for DoS protection
  3886. EXPECT_FALSE(res);
  3887. }
  3888. EXPECT_EQ("close", res->get_header_value("Connection"));
  3889. EXPECT_FALSE(cli_.is_socket_open());
  3890. }
  3891. TEST_F(ServerTest, MultipartFormData) {
  3892. UploadFormDataItems items = {
  3893. {"text1", "text default", "", ""},
  3894. {"text2", "aωb", "", ""},
  3895. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3896. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3897. {"file3", "", "", "application/octet-stream"},
  3898. {"file4", "", "", " application/json tmp-string "}};
  3899. auto res = cli_.Post("/multipart", items);
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::OK_200, res->status);
  3902. }
  3903. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3904. UploadFormDataItems items = {
  3905. {"text", "default text", "", ""},
  3906. {"multi_text1", "aaaaa", "", ""},
  3907. {"multi_text1", "bbbbb", "", ""},
  3908. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3909. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3910. "application/json"},
  3911. };
  3912. auto res = cli_.Post("/multipart/multi_file_values", items);
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. }
  3916. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3917. auto res = cli_.Get("/hi");
  3918. ASSERT_TRUE(res);
  3919. EXPECT_EQ(StatusCode::OK_200, res->status);
  3920. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3921. EXPECT_EQ("Hello World!", res->body);
  3922. }
  3923. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3924. Request req;
  3925. req.method = "POST";
  3926. req.path = "/chunked";
  3927. std::string host_and_port;
  3928. host_and_port += HOST;
  3929. host_and_port += ":";
  3930. host_and_port += std::to_string(PORT);
  3931. req.headers.emplace("Host", host_and_port.c_str());
  3932. req.headers.emplace("Accept", "*/*");
  3933. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3934. req.headers.emplace("Content-Type", "text/plain");
  3935. req.headers.emplace("Content-Length", "0");
  3936. req.headers.emplace(
  3937. "Transfer-Encoding",
  3938. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3939. // Client does not chunk, so make a chunked body manually.
  3940. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3941. auto res = std::make_shared<Response>();
  3942. auto error = Error::Success;
  3943. auto ret = cli_.send(req, *res, error);
  3944. ASSERT_TRUE(ret);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. }
  3947. TEST_F(ServerTest, GetStreamed2) {
  3948. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3949. ASSERT_TRUE(res);
  3950. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3951. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3952. EXPECT_EQ(true, res->has_header("Content-Range"));
  3953. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3954. EXPECT_EQ(std::string("ab"), res->body);
  3955. }
  3956. TEST_F(ServerTest, GetStreamed) {
  3957. auto res = cli_.Get("/streamed");
  3958. ASSERT_TRUE(res);
  3959. EXPECT_EQ(StatusCode::OK_200, res->status);
  3960. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3961. EXPECT_EQ(std::string("aaabbb"), res->body);
  3962. }
  3963. TEST_F(ServerTest, GetStreamedWithRange1) {
  3964. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3965. ASSERT_TRUE(res);
  3966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3967. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3968. EXPECT_EQ(true, res->has_header("Content-Range"));
  3969. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3970. EXPECT_EQ(std::string("def"), res->body);
  3971. }
  3972. TEST_F(ServerTest, GetStreamedWithRange2) {
  3973. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3974. ASSERT_TRUE(res);
  3975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3976. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3977. EXPECT_EQ(true, res->has_header("Content-Range"));
  3978. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3979. EXPECT_EQ(std::string("bcdefg"), res->body);
  3980. }
  3981. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3982. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3985. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ(true, res->has_header("Content-Range"));
  3987. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3988. EXPECT_EQ(std::string("efg"), res->body);
  3989. }
  3990. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3991. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3994. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3995. EXPECT_EQ(false, res->has_header("Content-Range"));
  3996. EXPECT_EQ(0U, res->body.size());
  3997. }
  3998. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3999. auto res = cli_.Get("/streamed-with-range",
  4000. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4001. "92233720368547758079223372036854775807"}});
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4004. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4005. EXPECT_EQ(false, res->has_header("Content-Range"));
  4006. EXPECT_EQ(0U, res->body.size());
  4007. }
  4008. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4009. auto res = cli_.Get(
  4010. "/with-range",
  4011. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4012. {"Accept-Encoding", ""}});
  4013. ASSERT_TRUE(res);
  4014. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4015. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4016. EXPECT_EQ(true, res->has_header("Content-Range"));
  4017. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4018. EXPECT_EQ(std::string("abcdefg"), res->body);
  4019. }
  4020. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4021. auto res = cli_.Get("/with-range", {
  4022. {"Range", "bytes=0-"},
  4023. {"Accept-Encoding", ""},
  4024. });
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4027. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4028. EXPECT_EQ(true, res->has_header("Content-Range"));
  4029. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4030. EXPECT_EQ(std::string("abcdefg"), res->body);
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4033. auto res =
  4034. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4038. EXPECT_EQ(false, res->has_header("Content-Range"));
  4039. EXPECT_EQ(267U, res->body.size());
  4040. // Check that both range contents are present
  4041. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4042. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4043. // Check that Content-Range headers are present for both ranges
  4044. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4045. std::string::npos);
  4046. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4047. std::string::npos);
  4048. }
  4049. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4050. Ranges ranges;
  4051. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4052. ranges.emplace_back(0, -1);
  4053. }
  4054. auto res =
  4055. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4058. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ(false, res->has_header("Content-Range"));
  4060. EXPECT_EQ(0U, res->body.size());
  4061. }
  4062. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4063. auto res =
  4064. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ(5U, res->body.size());
  4068. // Check that overlapping ranges are coalesced into a single range
  4069. EXPECT_EQ("bcdef", res->body);
  4070. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4071. // Should be single range, not multipart
  4072. EXPECT_TRUE(res->has_header("Content-Range"));
  4073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4074. }
  4075. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4076. auto res =
  4077. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4078. ASSERT_TRUE(res);
  4079. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4080. EXPECT_EQ(268U, res->body.size());
  4081. // Check that both range contents are present
  4082. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4083. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4084. // Check that Content-Range headers are present for both ranges
  4085. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4086. std::string::npos);
  4087. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4088. std::string::npos);
  4089. }
  4090. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4091. auto res =
  4092. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4093. ASSERT_TRUE(res);
  4094. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4095. EXPECT_EQ(269U, res->body.size());
  4096. // Check that both duplicate range contents are present
  4097. size_t first_abc = res->body.find("abc\r\n");
  4098. EXPECT_TRUE(first_abc != std::string::npos);
  4099. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4100. EXPECT_TRUE(second_abc != std::string::npos);
  4101. // Check that Content-Range headers are present for both ranges
  4102. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4103. EXPECT_TRUE(first_range != std::string::npos);
  4104. size_t second_range =
  4105. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4106. EXPECT_TRUE(second_range != std::string::npos);
  4107. }
  4108. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4109. auto res = cli_.Get("/streamed-with-range?error",
  4110. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4113. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(false, res->has_header("Content-Range"));
  4115. EXPECT_EQ(0U, res->body.size());
  4116. }
  4117. TEST_F(ServerTest, GetStreamedEndless) {
  4118. uint64_t offset = 0;
  4119. auto res = cli_.Get("/streamed-cancel",
  4120. [&](const char * /*data*/, uint64_t data_length) {
  4121. if (offset < 100) {
  4122. offset += data_length;
  4123. return true;
  4124. }
  4125. return false;
  4126. });
  4127. ASSERT_TRUE(!res);
  4128. EXPECT_EQ(Error::Canceled, res.error());
  4129. }
  4130. TEST_F(ServerTest, ClientStop) {
  4131. std::atomic_size_t count{4};
  4132. std::vector<std::thread> threads;
  4133. for (auto i = count.load(); i != 0; --i) {
  4134. threads.emplace_back([&]() {
  4135. auto res = cli_.Get("/streamed-cancel",
  4136. [&](const char *, uint64_t) { return true; });
  4137. --count;
  4138. ASSERT_TRUE(!res);
  4139. EXPECT_TRUE(res.error() == Error::Canceled ||
  4140. res.error() == Error::Read || res.error() == Error::Write);
  4141. });
  4142. }
  4143. std::this_thread::sleep_for(std::chrono::seconds(2));
  4144. while (count != 0) {
  4145. cli_.stop();
  4146. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4147. }
  4148. for (auto &t : threads) {
  4149. t.join();
  4150. }
  4151. }
  4152. TEST_F(ServerTest, GetWithRange1) {
  4153. auto res = cli_.Get("/with-range", {
  4154. make_range_header({{3, 5}}),
  4155. {"Accept-Encoding", ""},
  4156. });
  4157. ASSERT_TRUE(res);
  4158. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4159. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4160. EXPECT_EQ(true, res->has_header("Content-Range"));
  4161. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4162. EXPECT_EQ(std::string("def"), res->body);
  4163. }
  4164. TEST_F(ServerTest, GetWithRange2) {
  4165. auto res = cli_.Get("/with-range", {
  4166. make_range_header({{1, -1}}),
  4167. {"Accept-Encoding", ""},
  4168. });
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4171. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4172. EXPECT_EQ(true, res->has_header("Content-Range"));
  4173. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4174. EXPECT_EQ(std::string("bcdefg"), res->body);
  4175. }
  4176. TEST_F(ServerTest, GetWithRange3) {
  4177. auto res = cli_.Get("/with-range", {
  4178. make_range_header({{0, 0}}),
  4179. {"Accept-Encoding", ""},
  4180. });
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4183. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4184. EXPECT_EQ(true, res->has_header("Content-Range"));
  4185. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4186. EXPECT_EQ(std::string("a"), res->body);
  4187. }
  4188. TEST_F(ServerTest, GetWithRange4) {
  4189. auto res = cli_.Get("/with-range", {
  4190. make_range_header({{-1, 2}}),
  4191. {"Accept-Encoding", ""},
  4192. });
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4195. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4196. EXPECT_EQ(true, res->has_header("Content-Range"));
  4197. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4198. EXPECT_EQ(std::string("fg"), res->body);
  4199. }
  4200. TEST_F(ServerTest, GetWithRange5) {
  4201. auto res = cli_.Get("/with-range", {
  4202. make_range_header({{0, 5}}),
  4203. {"Accept-Encoding", ""},
  4204. });
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4207. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4208. EXPECT_EQ(true, res->has_header("Content-Range"));
  4209. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4210. EXPECT_EQ(std::string("abcdef"), res->body);
  4211. }
  4212. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4213. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4216. }
  4217. TEST_F(ServerTest, GetWithRangeMultipart) {
  4218. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(false, res->has_header("Content-Range"));
  4223. EXPECT_EQ(267U, res->body.size());
  4224. }
  4225. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4226. auto res =
  4227. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4230. }
  4231. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4232. auto res = cli_.Get("/with-range-customized-response",
  4233. {{make_range_header({{1, 2}})}});
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4236. EXPECT_EQ(true, res->has_header("Content-Length"));
  4237. EXPECT_EQ(false, res->has_header("Content-Range"));
  4238. EXPECT_EQ(JSON_DATA, res->body);
  4239. }
  4240. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4241. auto res = cli_.Get("/with-range-customized-response",
  4242. {{make_range_header({{1, 2}, {4, 5}})}});
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4245. EXPECT_EQ(true, res->has_header("Content-Length"));
  4246. EXPECT_EQ(false, res->has_header("Content-Range"));
  4247. EXPECT_EQ(JSON_DATA, res->body);
  4248. }
  4249. TEST_F(ServerTest, Issue1772) {
  4250. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4253. }
  4254. TEST_F(ServerTest, Issue609) {
  4255. auto res = cli_.Delete("/issue609");
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(StatusCode::OK_200, res->status);
  4258. EXPECT_EQ(std::string("ok"), res->body);
  4259. }
  4260. TEST_F(ServerTest, GetStreamedChunked) {
  4261. auto res = cli_.Get("/streamed-chunked");
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ(std::string("123456789"), res->body);
  4265. }
  4266. TEST_F(ServerTest, GetStreamedChunked2) {
  4267. auto res = cli_.Get("/streamed-chunked2");
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::OK_200, res->status);
  4270. EXPECT_EQ(std::string("123456789"), res->body);
  4271. }
  4272. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4273. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::OK_200, res->status);
  4276. EXPECT_EQ(std::string("123456789"), res->body);
  4277. EXPECT_TRUE(res->has_header("Trailer"));
  4278. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4279. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4280. // Trailers are now stored separately from headers (security fix)
  4281. EXPECT_EQ(2U, res->trailers.size());
  4282. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4283. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4284. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4285. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4286. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4287. // Verify trailers are NOT in headers (security verification)
  4288. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4289. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4290. }
  4291. TEST_F(ServerTest, LargeChunkedPost) {
  4292. Request req;
  4293. req.method = "POST";
  4294. req.path = "/large-chunked";
  4295. std::string host_and_port;
  4296. host_and_port += HOST;
  4297. host_and_port += ":";
  4298. host_and_port += std::to_string(PORT);
  4299. req.headers.emplace("Host", host_and_port.c_str());
  4300. req.headers.emplace("Accept", "*/*");
  4301. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4302. req.headers.emplace("Content-Type", "text/plain");
  4303. req.headers.emplace("Content-Length", "0");
  4304. req.headers.emplace("Transfer-Encoding", "chunked");
  4305. std::string long_string(30 * 1024u, 'a');
  4306. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4307. // Attempt to make a large enough post to exceed OS buffers, to test that
  4308. // the server handles short reads if the full chunk data isn't available.
  4309. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4310. auto res = std::make_shared<Response>();
  4311. auto error = Error::Success;
  4312. auto ret = cli_.send(req, *res, error);
  4313. ASSERT_TRUE(ret);
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. }
  4316. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4317. auto res = cli_.Get("/remote_addr");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4321. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4322. }
  4323. TEST_F(ServerTest, GetMethodLocalAddr) {
  4324. auto res = cli_.Get("/local_addr");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4328. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4329. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4330. }
  4331. TEST_F(ServerTest, HTTPResponseSplitting) {
  4332. auto res = cli_.Get("/http_response_splitting");
  4333. ASSERT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. }
  4336. TEST_F(ServerTest, SlowRequest) {
  4337. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4338. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4339. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4340. }
  4341. #if 0
  4342. TEST_F(ServerTest, SlowPost) {
  4343. char buffer[64 * 1024];
  4344. memset(buffer, 0x42, sizeof(buffer));
  4345. auto res = cli_.Post(
  4346. "/slowpost", 64 * 1024 * 1024,
  4347. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4348. auto ret = sink.write(buffer, sizeof(buffer));
  4349. EXPECT_TRUE(ret);
  4350. return true;
  4351. },
  4352. "text/plain");
  4353. ASSERT_TRUE(res);
  4354. EXPECT_EQ(StatusCode::OK_200, res->status);
  4355. }
  4356. TEST_F(ServerTest, SlowPostFail) {
  4357. char buffer[64 * 1024];
  4358. memset(buffer, 0x42, sizeof(buffer));
  4359. cli_.set_write_timeout(std::chrono::seconds(0));
  4360. auto res = cli_.Post(
  4361. "/slowpost", 64 * 1024 * 1024,
  4362. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4363. sink.write(buffer, sizeof(buffer));
  4364. return true;
  4365. },
  4366. "text/plain");
  4367. ASSERT_TRUE(!res);
  4368. EXPECT_EQ(Error::Write, res.error());
  4369. }
  4370. #endif
  4371. TEST_F(ServerTest, Put) {
  4372. auto res = cli_.Put("/put", "PUT", "text/plain");
  4373. ASSERT_TRUE(res);
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. EXPECT_EQ("PUT", res->body);
  4376. }
  4377. TEST_F(ServerTest, PutWithContentProvider) {
  4378. auto res = cli_.Put(
  4379. "/put", 3,
  4380. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4381. sink.os << "PUT";
  4382. return true;
  4383. },
  4384. "text/plain");
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::OK_200, res->status);
  4387. EXPECT_EQ("PUT", res->body);
  4388. }
  4389. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4390. auto res = cli_.Post(
  4391. "/post", 42,
  4392. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4393. return false;
  4394. },
  4395. "text/plain");
  4396. ASSERT_TRUE(!res);
  4397. EXPECT_EQ(Error::Canceled, res.error());
  4398. }
  4399. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4400. auto res = cli_.Put(
  4401. "/put",
  4402. [](size_t /*offset*/, DataSink &sink) {
  4403. sink.os << "PUT";
  4404. sink.done();
  4405. return true;
  4406. },
  4407. "text/plain");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. EXPECT_EQ("PUT", res->body);
  4411. }
  4412. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4413. auto res = cli_.Post(
  4414. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4415. "text/plain");
  4416. ASSERT_TRUE(!res);
  4417. EXPECT_EQ(Error::Canceled, res.error());
  4418. }
  4419. TEST_F(ServerTest, PostLoopBack) {
  4420. std::string body;
  4421. auto res = cli_.Post(
  4422. "/post-loopback", 9,
  4423. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4424. EXPECT_EQ(9u, length);
  4425. sink.write("123", 3);
  4426. sink.write("456", 3);
  4427. sink.write("789", 3);
  4428. return true;
  4429. },
  4430. "text/plain",
  4431. [&body](const char *data, size_t data_length) {
  4432. body.append(data, data_length);
  4433. return true;
  4434. });
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. EXPECT_EQ("123456789", body);
  4438. }
  4439. TEST_F(ServerTest, PutLoopBack) {
  4440. std::string body;
  4441. auto res = cli_.Put(
  4442. "/put-loopback", 9,
  4443. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4444. EXPECT_EQ(9u, length);
  4445. sink.write("123", 3);
  4446. sink.write("456", 3);
  4447. sink.write("789", 3);
  4448. return true;
  4449. },
  4450. "text/plain",
  4451. [&body](const char *data, size_t data_length) {
  4452. body.append(data, data_length);
  4453. return true;
  4454. });
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("123456789", body);
  4458. }
  4459. TEST_F(ServerTest, PatchLoopBack) {
  4460. std::string body;
  4461. auto res = cli_.Patch(
  4462. "/patch-loopback", 9,
  4463. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4464. EXPECT_EQ(9u, length);
  4465. sink.write("123", 3);
  4466. sink.write("456", 3);
  4467. sink.write("789", 3);
  4468. return true;
  4469. },
  4470. "text/plain",
  4471. [&body](const char *data, size_t data_length) {
  4472. body.append(data, data_length);
  4473. return true;
  4474. });
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::OK_200, res->status);
  4477. EXPECT_EQ("123456789", body);
  4478. }
  4479. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4480. std::string body;
  4481. auto res = cli_.Post(
  4482. "/post-loopback",
  4483. [](size_t /*offset*/, DataSink &sink) {
  4484. sink.write("123", 3);
  4485. sink.write("456", 3);
  4486. sink.write("789", 3);
  4487. sink.done();
  4488. return true;
  4489. },
  4490. "text/plain",
  4491. [&body](const char *data, size_t data_length) {
  4492. body.append(data, data_length);
  4493. return true;
  4494. });
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::OK_200, res->status);
  4497. EXPECT_EQ("123456789", body);
  4498. }
  4499. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4500. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4501. cli_.set_compress(true);
  4502. auto res = cli_.Put(
  4503. "/put", 3,
  4504. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4505. sink.os << "PUT";
  4506. return true;
  4507. },
  4508. "text/plain");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ("PUT", res->body);
  4512. }
  4513. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4514. cli_.set_compress(true);
  4515. auto res = cli_.Post(
  4516. "/post", 42,
  4517. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4518. return false;
  4519. },
  4520. "text/plain");
  4521. ASSERT_TRUE(!res);
  4522. EXPECT_EQ(Error::Canceled, res.error());
  4523. }
  4524. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4525. cli_.set_compress(true);
  4526. auto res = cli_.Put(
  4527. "/put",
  4528. [](size_t /*offset*/, DataSink &sink) {
  4529. sink.os << "PUT";
  4530. sink.done();
  4531. return true;
  4532. },
  4533. "text/plain");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("PUT", res->body);
  4537. }
  4538. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4539. cli_.set_compress(true);
  4540. auto res = cli_.Post(
  4541. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4542. "text/plain");
  4543. ASSERT_TRUE(!res);
  4544. EXPECT_EQ(Error::Canceled, res.error());
  4545. }
  4546. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4547. cli_.set_compress(true);
  4548. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4549. ASSERT_TRUE(res);
  4550. EXPECT_EQ(StatusCode::OK_200, res->status);
  4551. EXPECT_EQ(LARGE_DATA, res->body);
  4552. }
  4553. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4555. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4556. Client cli(s.c_str());
  4557. cli.enable_server_certificate_verification(false);
  4558. #else
  4559. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4560. Client cli(s.c_str());
  4561. #endif
  4562. cli.set_compress(true);
  4563. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ(LARGE_DATA, res->body);
  4567. // The compressed size should be less than a 10th of the original. May vary
  4568. // depending on the zlib library.
  4569. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4570. static_cast<uint64_t>(10 * 1024 * 1024));
  4571. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4572. }
  4573. TEST_F(ServerTest, PutContentWithDeflate) {
  4574. cli_.set_compress(false);
  4575. Headers headers;
  4576. headers.emplace("Content-Encoding", "deflate");
  4577. // PUT in deflate format:
  4578. auto res = cli_.Put("/put", headers,
  4579. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. EXPECT_EQ("PUT", res->body);
  4583. }
  4584. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4585. Headers headers;
  4586. headers.emplace("Accept-Encoding", "gzip, deflate");
  4587. auto res = cli_.Get("/streamed-chunked", headers);
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. EXPECT_EQ(std::string("123456789"), res->body);
  4591. }
  4592. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4593. Headers headers;
  4594. headers.emplace("Accept-Encoding", "gzip, deflate");
  4595. auto res = cli_.Get("/streamed-chunked2", headers);
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ(std::string("123456789"), res->body);
  4599. }
  4600. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4601. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. }
  4605. TEST(GzipDecompressor, ChunkedDecompression) {
  4606. std::string data;
  4607. for (size_t i = 0; i < 32 * 1024; ++i) {
  4608. data.push_back(static_cast<char>('a' + i % 26));
  4609. }
  4610. std::string compressed_data;
  4611. {
  4612. httplib::detail::gzip_compressor compressor;
  4613. bool result = compressor.compress(
  4614. data.data(), data.size(),
  4615. /*last=*/true,
  4616. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4617. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4618. compressed_data_size);
  4619. return true;
  4620. });
  4621. ASSERT_TRUE(result);
  4622. }
  4623. std::string decompressed_data;
  4624. {
  4625. httplib::detail::gzip_decompressor decompressor;
  4626. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4627. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4628. size_t chunk_size = 130;
  4629. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4630. chunk_begin += chunk_size) {
  4631. size_t current_chunk_size =
  4632. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4633. bool result = decompressor.decompress(
  4634. compressed_data.data() + chunk_begin, current_chunk_size,
  4635. [&](const char *decompressed_data_chunk,
  4636. size_t decompressed_data_chunk_size) {
  4637. decompressed_data.insert(decompressed_data.size(),
  4638. decompressed_data_chunk,
  4639. decompressed_data_chunk_size);
  4640. return true;
  4641. });
  4642. ASSERT_TRUE(result);
  4643. }
  4644. }
  4645. ASSERT_EQ(data, decompressed_data);
  4646. }
  4647. TEST(GzipDecompressor, DeflateDecompression) {
  4648. std::string original_text = "Raw deflate without gzip";
  4649. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4650. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4651. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4652. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4653. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4654. std::string decompressed_data;
  4655. {
  4656. httplib::detail::gzip_decompressor decompressor;
  4657. bool result = decompressor.decompress(
  4658. compressed_data.data(), compressed_data.size(),
  4659. [&](const char *decompressed_data_chunk,
  4660. size_t decompressed_data_chunk_size) {
  4661. decompressed_data.insert(decompressed_data.size(),
  4662. decompressed_data_chunk,
  4663. decompressed_data_chunk_size);
  4664. return true;
  4665. });
  4666. ASSERT_TRUE(result);
  4667. }
  4668. ASSERT_EQ(original_text, decompressed_data);
  4669. }
  4670. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4671. std::string original_text = "Raw deflate without gzip";
  4672. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4673. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4674. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4675. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4676. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4677. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4678. std::string decompressed_data;
  4679. {
  4680. httplib::detail::gzip_decompressor decompressor;
  4681. bool result = decompressor.decompress(
  4682. compressed_data.data(), compressed_data.size(),
  4683. [&](const char *decompressed_data_chunk,
  4684. size_t decompressed_data_chunk_size) {
  4685. decompressed_data.insert(decompressed_data.size(),
  4686. decompressed_data_chunk,
  4687. decompressed_data_chunk_size);
  4688. return true;
  4689. });
  4690. ASSERT_TRUE(result);
  4691. }
  4692. ASSERT_EQ(original_text, decompressed_data);
  4693. }
  4694. #ifdef _WIN32
  4695. TEST(GzipDecompressor, LargeRandomData) {
  4696. // prepare large random data that is difficult to be compressed and is
  4697. // expected to have large size even when compressed
  4698. std::random_device seed_gen;
  4699. std::mt19937 random(seed_gen());
  4700. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4701. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4702. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4703. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4704. // compress data over 4GiB
  4705. std::string compressed_data;
  4706. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4707. httplib::detail::gzip_compressor compressor;
  4708. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4709. data.size() * sizeof(std::uint32_t), true,
  4710. [&](const char *data, size_t size) {
  4711. compressed_data.insert(
  4712. compressed_data.size(), data, size);
  4713. return true;
  4714. });
  4715. ASSERT_TRUE(result);
  4716. // FIXME: compressed data size is expected to be greater than 4GiB,
  4717. // but there is no guarantee
  4718. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4719. // decompress data over 4GiB
  4720. std::string decompressed_data;
  4721. decompressed_data.reserve(data_size);
  4722. httplib::detail::gzip_decompressor decompressor;
  4723. result = decompressor.decompress(
  4724. compressed_data.data(), compressed_data.size(),
  4725. [&](const char *data, size_t size) {
  4726. decompressed_data.insert(decompressed_data.size(), data, size);
  4727. return true;
  4728. });
  4729. ASSERT_TRUE(result);
  4730. // compare
  4731. ASSERT_EQ(data_size, decompressed_data.size());
  4732. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4733. 0);
  4734. }
  4735. #endif
  4736. #endif
  4737. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4738. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4739. Headers headers;
  4740. headers.emplace("Accept-Encoding", "br");
  4741. auto res = cli_.Get("/streamed-chunked", headers);
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ(std::string("123456789"), res->body);
  4745. }
  4746. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4747. Headers headers;
  4748. headers.emplace("Accept-Encoding", "br");
  4749. auto res = cli_.Get("/streamed-chunked2", headers);
  4750. ASSERT_TRUE(res);
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ(std::string("123456789"), res->body);
  4753. }
  4754. #endif
  4755. TEST_F(ServerTest, Patch) {
  4756. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::OK_200, res->status);
  4759. EXPECT_EQ("PATCH", res->body);
  4760. }
  4761. TEST_F(ServerTest, Delete) {
  4762. auto res = cli_.Delete("/delete");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. EXPECT_EQ("DELETE", res->body);
  4766. }
  4767. TEST_F(ServerTest, DeleteContentReceiver) {
  4768. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ("content", res->body);
  4772. }
  4773. TEST_F(ServerTest, Options) {
  4774. auto res = cli_.Options("*");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4778. EXPECT_TRUE(res->body.empty());
  4779. }
  4780. TEST_F(ServerTest, URL) {
  4781. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4782. ASSERT_TRUE(res);
  4783. EXPECT_EQ(StatusCode::OK_200, res->status);
  4784. }
  4785. TEST_F(ServerTest, ArrayParam) {
  4786. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4787. ASSERT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. }
  4790. TEST_F(ServerTest, NoMultipleHeaders) {
  4791. Headers headers = {{"Content-Length", "5"}};
  4792. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4793. "text/plain");
  4794. ASSERT_TRUE(res);
  4795. EXPECT_EQ(StatusCode::OK_200, res->status);
  4796. }
  4797. TEST_F(ServerTest, PostContentReceiver) {
  4798. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4799. ASSERT_TRUE(res);
  4800. ASSERT_EQ(StatusCode::OK_200, res->status);
  4801. ASSERT_EQ("content", res->body);
  4802. }
  4803. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4804. UploadFormDataItems items = {
  4805. {"text1", "text default", "", ""},
  4806. {"text2", "aωb", "", ""},
  4807. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4808. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4809. {"file3", "", "", "application/octet-stream"},
  4810. };
  4811. auto res = cli_.Post("/content_receiver", items);
  4812. ASSERT_TRUE(res);
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. }
  4815. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4816. UploadFormDataItems items = {
  4817. {"text1", "text default", "", ""},
  4818. {"text2", "aωb", "", ""},
  4819. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4820. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4821. {"file3", "", "", "application/octet-stream"},
  4822. };
  4823. auto boundary = std::string("+++++");
  4824. std::string body;
  4825. for (const auto &item : items) {
  4826. body += "--" + boundary + "\r\n";
  4827. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4828. if (!item.filename.empty()) {
  4829. body += "; filename=\"" + item.filename + "\"";
  4830. }
  4831. body += "\r\n";
  4832. if (!item.content_type.empty()) {
  4833. body += "Content-Type: " + item.content_type + "\r\n";
  4834. }
  4835. body += "\r\n";
  4836. body += item.content + "\r\n";
  4837. }
  4838. body += "--" + boundary + "--\r\n";
  4839. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4840. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. }
  4844. TEST_F(ServerTest, PostContentReceiverGzip) {
  4845. cli_.set_compress(true);
  4846. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4847. ASSERT_TRUE(res);
  4848. ASSERT_EQ(StatusCode::OK_200, res->status);
  4849. ASSERT_EQ("content", res->body);
  4850. }
  4851. TEST_F(ServerTest, PutContentReceiver) {
  4852. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4853. ASSERT_TRUE(res);
  4854. ASSERT_EQ(StatusCode::OK_200, res->status);
  4855. ASSERT_EQ("content", res->body);
  4856. }
  4857. TEST_F(ServerTest, PatchContentReceiver) {
  4858. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4859. ASSERT_TRUE(res);
  4860. ASSERT_EQ(StatusCode::OK_200, res->status);
  4861. ASSERT_EQ("content", res->body);
  4862. }
  4863. template <typename ClientType>
  4864. void TestWithHeadersAndContentReceiver(
  4865. ClientType &cli,
  4866. std::function<Result(ClientType &, const std::string &, const Headers &,
  4867. const std::string &, const std::string &,
  4868. ContentReceiver, DownloadProgress)>
  4869. request_func) {
  4870. Headers headers;
  4871. headers.emplace("X-Custom-Header", "test-value");
  4872. std::string received_body;
  4873. auto res = request_func(
  4874. cli, "/content_receiver", headers, "content", "application/json",
  4875. [&](const char *data, size_t data_length) {
  4876. received_body.append(data, data_length);
  4877. return true;
  4878. },
  4879. nullptr);
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("content", received_body);
  4883. }
  4884. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4885. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4886. using ClientT = SSLClient;
  4887. #else
  4888. using ClientT = Client;
  4889. #endif
  4890. TestWithHeadersAndContentReceiver<ClientT>(
  4891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4892. const std::string &body, const std::string &content_type,
  4893. ContentReceiver receiver, DownloadProgress progress) {
  4894. return cli.Post(path, headers, body, content_type, receiver, progress);
  4895. });
  4896. }
  4897. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4899. using ClientT = SSLClient;
  4900. #else
  4901. using ClientT = Client;
  4902. #endif
  4903. TestWithHeadersAndContentReceiver<ClientT>(
  4904. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4905. const std::string &body, const std::string &content_type,
  4906. ContentReceiver receiver, DownloadProgress progress) {
  4907. return cli.Put(path, headers, body, content_type, receiver, progress);
  4908. });
  4909. }
  4910. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4912. using ClientT = SSLClient;
  4913. #else
  4914. using ClientT = Client;
  4915. #endif
  4916. TestWithHeadersAndContentReceiver<ClientT>(
  4917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4918. const std::string &body, const std::string &content_type,
  4919. ContentReceiver receiver, DownloadProgress progress) {
  4920. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4921. });
  4922. }
  4923. template <typename ClientType>
  4924. void TestWithHeadersAndContentReceiverWithProgress(
  4925. ClientType &cli,
  4926. std::function<Result(ClientType &, const std::string &, const Headers &,
  4927. const std::string &, const std::string &,
  4928. ContentReceiver, DownloadProgress)>
  4929. request_func) {
  4930. Headers headers;
  4931. headers.emplace("X-Test-Header", "progress-test");
  4932. std::string received_body;
  4933. auto progress_called = false;
  4934. auto res = request_func(
  4935. cli, "/content_receiver", headers, "content", "text/plain",
  4936. [&](const char *data, size_t data_length) {
  4937. received_body.append(data, data_length);
  4938. return true;
  4939. },
  4940. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4941. progress_called = true;
  4942. return true;
  4943. });
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("content", received_body);
  4947. EXPECT_TRUE(progress_called);
  4948. }
  4949. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4950. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4951. using ClientT = SSLClient;
  4952. #else
  4953. using ClientT = Client;
  4954. #endif
  4955. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4956. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4957. const std::string &body, const std::string &content_type,
  4958. ContentReceiver receiver, DownloadProgress progress) {
  4959. return cli.Post(path, headers, body, content_type, receiver, progress);
  4960. });
  4961. }
  4962. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4964. using ClientT = SSLClient;
  4965. #else
  4966. using ClientT = Client;
  4967. #endif
  4968. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4969. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4970. const std::string &body, const std::string &content_type,
  4971. ContentReceiver receiver, DownloadProgress progress) {
  4972. return cli.Put(path, headers, body, content_type, receiver, progress);
  4973. });
  4974. }
  4975. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4977. using ClientT = SSLClient;
  4978. #else
  4979. using ClientT = Client;
  4980. #endif
  4981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4983. const std::string &body, const std::string &content_type,
  4984. ContentReceiver receiver, DownloadProgress progress) {
  4985. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4986. });
  4987. }
  4988. template <typename ClientType>
  4989. void TestWithHeadersAndContentReceiverError(
  4990. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4991. const Headers &, const std::string &,
  4992. const std::string &, ContentReceiver)>
  4993. request_func) {
  4994. Headers headers;
  4995. headers.emplace("X-Error-Test", "true");
  4996. std::string received_body;
  4997. auto receiver_failed = false;
  4998. auto res =
  4999. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5000. [&](const char *data, size_t data_length) {
  5001. received_body.append(data, data_length);
  5002. receiver_failed = true;
  5003. return false;
  5004. });
  5005. ASSERT_FALSE(res);
  5006. EXPECT_TRUE(receiver_failed);
  5007. }
  5008. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5009. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5010. using ClientT = SSLClient;
  5011. #else
  5012. using ClientT = Client;
  5013. #endif
  5014. TestWithHeadersAndContentReceiverError<ClientT>(
  5015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5016. const std::string &body, const std::string &content_type,
  5017. ContentReceiver receiver) {
  5018. return cli.Post(path, headers, body, content_type, receiver);
  5019. });
  5020. }
  5021. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5022. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5023. using ClientT = SSLClient;
  5024. #else
  5025. using ClientT = Client;
  5026. #endif
  5027. TestWithHeadersAndContentReceiverError<ClientT>(
  5028. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5029. const std::string &body, const std::string &content_type,
  5030. ContentReceiver receiver) {
  5031. return cli.Put(path, headers, body, content_type, receiver);
  5032. });
  5033. }
  5034. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5036. using ClientT = SSLClient;
  5037. #else
  5038. using ClientT = Client;
  5039. #endif
  5040. TestWithHeadersAndContentReceiverError<ClientT>(
  5041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5042. const std::string &body, const std::string &content_type,
  5043. ContentReceiver receiver) {
  5044. return cli.Patch(path, headers, body, content_type, receiver);
  5045. });
  5046. }
  5047. TEST_F(ServerTest, PostQueryStringAndBody) {
  5048. auto res =
  5049. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5050. ASSERT_TRUE(res);
  5051. ASSERT_EQ(StatusCode::OK_200, res->status);
  5052. }
  5053. TEST_F(ServerTest, HTTP2Magic) {
  5054. Request req;
  5055. req.method = "PRI";
  5056. req.path = "*";
  5057. req.body = "SM";
  5058. auto res = std::make_shared<Response>();
  5059. auto error = Error::Success;
  5060. auto ret = cli_.send(req, *res, error);
  5061. ASSERT_TRUE(ret);
  5062. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5063. }
  5064. TEST_F(ServerTest, KeepAlive) {
  5065. auto res = cli_.Get("/hi");
  5066. ASSERT_TRUE(res);
  5067. EXPECT_EQ(StatusCode::OK_200, res->status);
  5068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5069. EXPECT_EQ("Hello World!", res->body);
  5070. res = cli_.Get("/hi");
  5071. ASSERT_TRUE(res);
  5072. EXPECT_EQ(StatusCode::OK_200, res->status);
  5073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5074. EXPECT_EQ("Hello World!", res->body);
  5075. res = cli_.Get("/hi");
  5076. ASSERT_TRUE(res);
  5077. EXPECT_EQ(StatusCode::OK_200, res->status);
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. EXPECT_EQ("Hello World!", res->body);
  5080. res = cli_.Get("/not-exist");
  5081. ASSERT_TRUE(res);
  5082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5083. res = cli_.Post("/empty", "", "text/plain");
  5084. ASSERT_TRUE(res);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5087. EXPECT_EQ("empty", res->body);
  5088. EXPECT_EQ("close", res->get_header_value("Connection"));
  5089. res = cli_.Post(
  5090. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5091. "text/plain");
  5092. ASSERT_TRUE(res);
  5093. EXPECT_EQ(StatusCode::OK_200, res->status);
  5094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5095. EXPECT_EQ("empty", res->body);
  5096. cli_.set_keep_alive(false);
  5097. res = cli_.Get("/last-request");
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("close", res->get_header_value("Connection"));
  5101. }
  5102. TEST_F(ServerTest, TooManyRedirect) {
  5103. cli_.set_follow_location(true);
  5104. auto res = cli_.Get("/redirect/0");
  5105. ASSERT_TRUE(!res);
  5106. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5107. }
  5108. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5109. Request req;
  5110. req.method = "FOOBAR";
  5111. req.path = "/hi";
  5112. cli_.set_keep_alive(true);
  5113. auto res = cli_.send(req);
  5114. ASSERT_TRUE(res);
  5115. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5116. EXPECT_EQ("close", res->get_header_value("Connection"));
  5117. EXPECT_FALSE(cli_.is_socket_open());
  5118. }
  5119. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5121. TEST_F(ServerTest, Gzip) {
  5122. Headers headers;
  5123. headers.emplace("Accept-Encoding", "gzip, deflate");
  5124. auto res = cli_.Get("/compress", headers);
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5128. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5129. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5130. "7890123456789012345678901234567890",
  5131. res->body);
  5132. EXPECT_EQ(StatusCode::OK_200, res->status);
  5133. }
  5134. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5135. Headers headers;
  5136. headers.emplace("Accept-Encoding", "");
  5137. auto res = cli_.Get("/compress", headers);
  5138. ASSERT_TRUE(res);
  5139. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5141. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5142. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5143. "7890123456789012345678901234567890",
  5144. res->body);
  5145. EXPECT_EQ(StatusCode::OK_200, res->status);
  5146. }
  5147. TEST_F(ServerTest, GzipWithContentReceiver) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "gzip, deflate");
  5150. std::string body;
  5151. auto res = cli_.Get("/compress", headers,
  5152. [&](const char *data, uint64_t data_length) {
  5153. EXPECT_EQ(100U, data_length);
  5154. body.append(data, data_length);
  5155. return true;
  5156. });
  5157. ASSERT_TRUE(res);
  5158. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5160. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5161. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5162. "7890123456789012345678901234567890",
  5163. body);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. }
  5166. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5167. Headers headers;
  5168. headers.emplace("Accept-Encoding", "gzip, deflate");
  5169. cli_.set_decompress(false);
  5170. auto res = cli_.Get("/compress", headers);
  5171. ASSERT_TRUE(res);
  5172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5174. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5175. EXPECT_EQ(33U, res->body.size());
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "");
  5181. std::string body;
  5182. auto res = cli_.Get("/compress", headers,
  5183. [&](const char *data, uint64_t data_length) {
  5184. EXPECT_EQ(100U, data_length);
  5185. body.append(data, data_length);
  5186. return true;
  5187. });
  5188. ASSERT_TRUE(res);
  5189. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5193. "7890123456789012345678901234567890",
  5194. body);
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. }
  5197. TEST_F(ServerTest, NoGzip) {
  5198. Headers headers;
  5199. headers.emplace("Accept-Encoding", "gzip, deflate");
  5200. auto res = cli_.Get("/nocompress", headers);
  5201. ASSERT_TRUE(res);
  5202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5206. "7890123456789012345678901234567890",
  5207. res->body);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. }
  5210. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5211. Headers headers;
  5212. headers.emplace("Accept-Encoding", "gzip, deflate");
  5213. std::string body;
  5214. auto res = cli_.Get("/nocompress", headers,
  5215. [&](const char *data, uint64_t data_length) {
  5216. EXPECT_EQ(100U, data_length);
  5217. body.append(data, data_length);
  5218. return true;
  5219. });
  5220. ASSERT_TRUE(res);
  5221. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5222. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5223. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5224. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5225. "7890123456789012345678901234567890",
  5226. body);
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. }
  5229. TEST_F(ServerTest, MultipartFormDataGzip) {
  5230. UploadFormDataItems items = {
  5231. {"key1", "test", "", ""},
  5232. {"key2", "--abcdefg123", "", ""},
  5233. };
  5234. cli_.set_compress(true);
  5235. auto res = cli_.Post("/compress-multipart", items);
  5236. ASSERT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. }
  5239. #endif
  5240. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5241. TEST_F(ServerTest, Brotli) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "br");
  5244. auto res = cli_.Get("/compress", headers);
  5245. ASSERT_TRUE(res);
  5246. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5249. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5250. "7890123456789012345678901234567890",
  5251. res->body);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. #endif
  5255. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5256. TEST_F(ServerTest, Zstd) {
  5257. Headers headers;
  5258. headers.emplace("Accept-Encoding", "zstd");
  5259. auto res = cli_.Get("/compress", headers);
  5260. ASSERT_TRUE(res);
  5261. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5263. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5264. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5265. "7890123456789012345678901234567890",
  5266. res->body);
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. }
  5269. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5270. Headers headers;
  5271. headers.emplace("Accept-Encoding", "");
  5272. auto res = cli_.Get("/compress", headers);
  5273. ASSERT_TRUE(res);
  5274. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5276. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5278. "7890123456789012345678901234567890",
  5279. res->body);
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. }
  5282. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "zstd");
  5285. std::string body;
  5286. auto res = cli_.Get("/compress", headers,
  5287. [&](const char *data, uint64_t data_length) {
  5288. EXPECT_EQ(100U, data_length);
  5289. body.append(data, data_length);
  5290. return true;
  5291. });
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5296. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5297. "7890123456789012345678901234567890",
  5298. body);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. }
  5301. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5302. Headers headers;
  5303. headers.emplace("Accept-Encoding", "zstd");
  5304. cli_.set_decompress(false);
  5305. auto res = cli_.Get("/compress", headers);
  5306. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5307. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5308. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5309. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5313. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. ASSERT_EQ(26U, res->body.size());
  5316. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5317. 0);
  5318. }
  5319. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5320. Headers headers;
  5321. headers.emplace("Accept-Encoding", "");
  5322. std::string body;
  5323. auto res = cli_.Get("/compress", headers,
  5324. [&](const char *data, uint64_t data_length) {
  5325. EXPECT_EQ(100U, data_length);
  5326. body.append(data, data_length);
  5327. return true;
  5328. });
  5329. ASSERT_TRUE(res);
  5330. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5332. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5333. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5334. "7890123456789012345678901234567890",
  5335. body);
  5336. EXPECT_EQ(StatusCode::OK_200, res->status);
  5337. }
  5338. TEST_F(ServerTest, NoZstd) {
  5339. Headers headers;
  5340. headers.emplace("Accept-Encoding", "zstd");
  5341. auto res = cli_.Get("/nocompress", headers);
  5342. ASSERT_TRUE(res);
  5343. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5344. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5345. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5346. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5347. "7890123456789012345678901234567890",
  5348. res->body);
  5349. EXPECT_EQ(StatusCode::OK_200, res->status);
  5350. }
  5351. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5352. Headers headers;
  5353. headers.emplace("Accept-Encoding", "zstd");
  5354. std::string body;
  5355. auto res = cli_.Get("/nocompress", headers,
  5356. [&](const char *data, uint64_t data_length) {
  5357. EXPECT_EQ(100U, data_length);
  5358. body.append(data, data_length);
  5359. return true;
  5360. });
  5361. ASSERT_TRUE(res);
  5362. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5363. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5364. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5365. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5366. "7890123456789012345678901234567890",
  5367. body);
  5368. EXPECT_EQ(StatusCode::OK_200, res->status);
  5369. }
  5370. // TODO: How to enable zstd ??
  5371. TEST_F(ServerTest, MultipartFormDataZstd) {
  5372. UploadFormDataItems items = {
  5373. {"key1", "test", "", ""},
  5374. {"key2", "--abcdefg123", "", ""},
  5375. };
  5376. Headers headers;
  5377. headers.emplace("Accept-Encoding", "zstd");
  5378. cli_.set_compress(true);
  5379. auto res = cli_.Post("/compress-multipart", headers, items);
  5380. ASSERT_TRUE(res);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. }
  5383. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5384. Headers headers;
  5385. headers.emplace("Accept-Encoding", "zstd");
  5386. cli_.set_compress(true);
  5387. auto res = cli_.Put(
  5388. "/put", headers, 3,
  5389. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5390. sink.os << "PUT";
  5391. return true;
  5392. },
  5393. "text/plain");
  5394. ASSERT_TRUE(res);
  5395. EXPECT_EQ(StatusCode::OK_200, res->status);
  5396. EXPECT_EQ("PUT", res->body);
  5397. }
  5398. // Pre-compression logging tests
  5399. TEST_F(ServerTest, PreCompressionLogging) {
  5400. // Test data for compression (matches the actual /compress endpoint content)
  5401. const std::string test_content =
  5402. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5403. "3456789012345678901234567890";
  5404. // Variables to capture logging data
  5405. std::string pre_compression_body;
  5406. std::string pre_compression_content_type;
  5407. std::string pre_compression_content_encoding;
  5408. std::string post_compression_body;
  5409. std::string post_compression_content_type;
  5410. std::string post_compression_content_encoding;
  5411. // Set up pre-compression logger
  5412. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5413. const Response &res) {
  5414. pre_compression_body = res.body;
  5415. pre_compression_content_type = res.get_header_value("Content-Type");
  5416. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5417. });
  5418. // Set up post-compression logger
  5419. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5420. post_compression_body = res.body;
  5421. post_compression_content_type = res.get_header_value("Content-Type");
  5422. post_compression_content_encoding =
  5423. res.get_header_value("Content-Encoding");
  5424. });
  5425. // Test with gzip compression
  5426. Headers headers;
  5427. headers.emplace("Accept-Encoding", "gzip");
  5428. auto res = cli_.Get("/compress", headers);
  5429. // Verify response was compressed
  5430. ASSERT_TRUE(res);
  5431. EXPECT_EQ(StatusCode::OK_200, res->status);
  5432. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5433. // Verify pre-compression logger captured uncompressed content
  5434. EXPECT_EQ(test_content, pre_compression_body);
  5435. EXPECT_EQ("text/plain", pre_compression_content_type);
  5436. EXPECT_TRUE(pre_compression_content_encoding
  5437. .empty()); // No encoding header before compression
  5438. // Verify post-compression logger captured compressed content
  5439. EXPECT_NE(test_content,
  5440. post_compression_body); // Should be different after compression
  5441. EXPECT_EQ("text/plain", post_compression_content_type);
  5442. EXPECT_EQ("gzip", post_compression_content_encoding);
  5443. // Verify compressed content is smaller
  5444. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5445. }
  5446. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5447. const std::string test_content =
  5448. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5449. "3456789012345678901234567890";
  5450. std::string pre_compression_body;
  5451. std::string post_compression_body;
  5452. svr_.set_pre_compression_logger(
  5453. [&](const Request & /*req*/, const Response &res) {
  5454. pre_compression_body = res.body;
  5455. });
  5456. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5457. post_compression_body = res.body;
  5458. });
  5459. Headers headers;
  5460. headers.emplace("Accept-Encoding", "br");
  5461. auto res = cli_.Get("/compress", headers);
  5462. ASSERT_TRUE(res);
  5463. EXPECT_EQ(StatusCode::OK_200, res->status);
  5464. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5465. // Verify pre-compression content is uncompressed
  5466. EXPECT_EQ(test_content, pre_compression_body);
  5467. // Verify post-compression content is compressed
  5468. EXPECT_NE(test_content, post_compression_body);
  5469. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5470. }
  5471. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5472. const std::string test_content =
  5473. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5474. "3456789012345678901234567890";
  5475. std::string pre_compression_body;
  5476. std::string post_compression_body;
  5477. svr_.set_pre_compression_logger(
  5478. [&](const Request & /*req*/, const Response &res) {
  5479. pre_compression_body = res.body;
  5480. });
  5481. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5482. post_compression_body = res.body;
  5483. });
  5484. // Request without compression (use /nocompress endpoint)
  5485. Headers headers;
  5486. auto res = cli_.Get("/nocompress", headers);
  5487. ASSERT_TRUE(res);
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5490. // Pre-compression logger should not be called when no compression is applied
  5491. EXPECT_TRUE(
  5492. pre_compression_body.empty()); // Pre-compression logger not called
  5493. EXPECT_EQ(
  5494. test_content,
  5495. post_compression_body); // Post-compression logger captures final content
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. bool pre_logger_called = false;
  5503. // Set only pre-compression logger
  5504. svr_.set_pre_compression_logger(
  5505. [&](const Request & /*req*/, const Response &res) {
  5506. pre_compression_body = res.body;
  5507. pre_logger_called = true;
  5508. });
  5509. Headers headers;
  5510. headers.emplace("Accept-Encoding", "gzip");
  5511. auto res = cli_.Get("/compress", headers);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5515. // Verify pre-compression logger was called
  5516. EXPECT_TRUE(pre_logger_called);
  5517. EXPECT_EQ(test_content, pre_compression_body);
  5518. }
  5519. TEST(ZstdDecompressor, ChunkedDecompression) {
  5520. std::string data;
  5521. for (size_t i = 0; i < 32 * 1024; ++i) {
  5522. data.push_back(static_cast<char>('a' + i % 26));
  5523. }
  5524. std::string compressed_data;
  5525. {
  5526. httplib::detail::zstd_compressor compressor;
  5527. bool result = compressor.compress(
  5528. data.data(), data.size(),
  5529. /*last=*/true,
  5530. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5531. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5532. compressed_data_size);
  5533. return true;
  5534. });
  5535. ASSERT_TRUE(result);
  5536. }
  5537. std::string decompressed_data;
  5538. {
  5539. httplib::detail::zstd_decompressor decompressor;
  5540. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5541. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5542. size_t chunk_size = 130;
  5543. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5544. chunk_begin += chunk_size) {
  5545. size_t current_chunk_size =
  5546. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5547. bool result = decompressor.decompress(
  5548. compressed_data.data() + chunk_begin, current_chunk_size,
  5549. [&](const char *decompressed_data_chunk,
  5550. size_t decompressed_data_chunk_size) {
  5551. decompressed_data.insert(decompressed_data.size(),
  5552. decompressed_data_chunk,
  5553. decompressed_data_chunk_size);
  5554. return true;
  5555. });
  5556. ASSERT_TRUE(result);
  5557. }
  5558. }
  5559. ASSERT_EQ(data, decompressed_data);
  5560. }
  5561. TEST(ZstdDecompressor, Decompress) {
  5562. std::string original_text = "Compressed with ZSTD";
  5563. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5564. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5565. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5566. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5567. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5568. std::string decompressed_data;
  5569. {
  5570. httplib::detail::zstd_decompressor decompressor;
  5571. bool result = decompressor.decompress(
  5572. compressed_data.data(), compressed_data.size(),
  5573. [&](const char *decompressed_data_chunk,
  5574. size_t decompressed_data_chunk_size) {
  5575. decompressed_data.insert(decompressed_data.size(),
  5576. decompressed_data_chunk,
  5577. decompressed_data_chunk_size);
  5578. return true;
  5579. });
  5580. ASSERT_TRUE(result);
  5581. }
  5582. ASSERT_EQ(original_text, decompressed_data);
  5583. }
  5584. #endif
  5585. // Sends a raw request to a server listening at HOST:PORT.
  5586. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5587. std::string *resp = nullptr) {
  5588. auto error = Error::Success;
  5589. auto client_sock = detail::create_client_socket(
  5590. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5591. /*connection_timeout_sec=*/5, 0,
  5592. /*read_timeout_sec=*/5, 0,
  5593. /*write_timeout_sec=*/5, 0, std::string(), error);
  5594. if (client_sock == INVALID_SOCKET) { return false; }
  5595. auto ret = detail::process_client_socket(
  5596. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5597. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5598. if (req.size() !=
  5599. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5600. return false;
  5601. }
  5602. char buf[512];
  5603. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5604. while (line_reader.getline()) {
  5605. if (resp) { *resp += line_reader.ptr(); }
  5606. }
  5607. return true;
  5608. });
  5609. detail::close_socket(client_sock);
  5610. return ret;
  5611. }
  5612. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5613. Server svr;
  5614. std::string header_value;
  5615. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5616. header_value = req.get_header_value("foo");
  5617. res.set_content("ok", "text/plain");
  5618. });
  5619. thread t = thread([&] { svr.listen(HOST, PORT); });
  5620. auto se = detail::scope_exit([&] {
  5621. svr.stop();
  5622. t.join();
  5623. ASSERT_FALSE(svr.is_running());
  5624. });
  5625. svr.wait_until_ready();
  5626. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5627. // like characters are not treated the same - use vertical tab and escape.
  5628. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5629. "foo: \t \v bar \x1B\t \r\n"
  5630. "Connection: close\r\n"
  5631. "\r\n";
  5632. std::string res;
  5633. ASSERT_TRUE(send_request(5, req, &res));
  5634. EXPECT_EQ(header_value, "");
  5635. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5636. }
  5637. // Sends a raw request and verifies that there isn't a crash or exception.
  5638. static void test_raw_request(const std::string &req,
  5639. std::string *out = nullptr) {
  5640. Server svr;
  5641. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5642. res.set_content("ok", "text/plain");
  5643. });
  5644. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5645. res.set_content("ok", "text/plain");
  5646. });
  5647. svr.Get("/header_field_value_check",
  5648. [&](const Request & /*req*/, Response &res) {
  5649. res.set_content("ok", "text/plain");
  5650. });
  5651. // Server read timeout must be longer than the client read timeout for the
  5652. // bug to reproduce, probably to force the server to process a request
  5653. // without a trailing blank line.
  5654. const time_t client_read_timeout_sec = 1;
  5655. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5656. bool listen_thread_ok = false;
  5657. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5658. auto se = detail::scope_exit([&] {
  5659. svr.stop();
  5660. t.join();
  5661. ASSERT_FALSE(svr.is_running());
  5662. EXPECT_TRUE(listen_thread_ok);
  5663. });
  5664. svr.wait_until_ready();
  5665. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5666. }
  5667. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5668. // A certain header line causes an exception if the header property is parsed
  5669. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5670. test_raw_request(
  5671. "GET /hi HTTP/1.1\r\n"
  5672. " : "
  5673. " "
  5674. " ");
  5675. }
  5676. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5677. // A certain header line causes an exception if the header property *name* is
  5678. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5679. // greedy matcher and requires backtracking when there are a lot of ":"
  5680. // characters.
  5681. // This occurs with libc++ but not libstdc++.
  5682. test_raw_request(
  5683. "GET /hi HTTP/1.1\r\n"
  5684. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5685. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5686. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5687. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5688. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5689. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5690. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5691. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5692. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5693. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5694. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5695. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5696. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5697. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5698. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5699. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5700. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5701. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5702. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5703. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5704. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5705. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5706. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5707. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5708. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5709. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5710. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5711. "&&&%%%");
  5712. }
  5713. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5714. // Make sure this doesn't crash the server.
  5715. // In a previous version of the header line regex, the "\r" rendered the line
  5716. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5717. // a new position where the leading white space ended and the field value
  5718. // began.
  5719. // The crash occurs with libc++ but not libstdc++.
  5720. test_raw_request("GET /hi HTTP/1.1\r\n"
  5721. "a:" +
  5722. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5723. "\r\n"
  5724. "\r\n");
  5725. }
  5726. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5727. std::string out;
  5728. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5729. "Content-Type: text/plain\r\n"
  5730. "Transfer-Encoding: chunked\r\n"
  5731. "\r\n"
  5732. "nothex\r\n",
  5733. &out);
  5734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5735. }
  5736. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5737. std::string out;
  5738. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5739. "Content-Type: text/plain\r\n"
  5740. "Transfer-Encoding: chunked\r\n"
  5741. "\r\n"
  5742. "3\r\n"
  5743. "xyz\r\n"
  5744. "NaN\r\n",
  5745. &out);
  5746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5747. }
  5748. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5749. std::string out;
  5750. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5751. "Content-Type: text/plain\r\n"
  5752. "Transfer-Encoding: chunked\r\n"
  5753. "\r\n"
  5754. // Length is too large for 64 bits.
  5755. "1ffffffffffffffff\r\n"
  5756. "xyz\r\n",
  5757. &out);
  5758. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5759. }
  5760. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5761. test_raw_request("GET /hi HTTP/1.1\r\n"
  5762. "Content-Type: text/plain\r\n\r");
  5763. }
  5764. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5765. std::string out;
  5766. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5767. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5768. }
  5769. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5770. std::string out;
  5771. std::string request(
  5772. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5773. test_raw_request(request, &out);
  5774. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5775. }
  5776. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5777. std::string out;
  5778. std::string request(
  5779. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5780. test_raw_request(request, &out);
  5781. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5782. }
  5783. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5784. std::string out;
  5785. std::string request(
  5786. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5787. test_raw_request(request, &out);
  5788. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5789. }
  5790. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5791. std::string out;
  5792. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5793. "Test: \r\n\r\n",
  5794. &out);
  5795. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5796. }
  5797. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5798. Server svr;
  5799. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5800. res.set_header("Cache-Control", "no-cache");
  5801. res.set_chunked_content_provider(
  5802. "text/event-stream", [](size_t offset, DataSink &sink) {
  5803. std::string s = "data:";
  5804. s += std::to_string(offset);
  5805. s += "\n\n";
  5806. auto ret = sink.write(s.data(), s.size());
  5807. EXPECT_TRUE(ret);
  5808. std::this_thread::sleep_for(std::chrono::seconds(1));
  5809. return true;
  5810. });
  5811. });
  5812. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5813. svr.wait_until_ready();
  5814. Client client(HOST, PORT);
  5815. const Headers headers = {{"Accept", "text/event-stream"}};
  5816. auto get_thread = std::thread([&client, &headers]() {
  5817. auto res = client.Get(
  5818. "/events", headers,
  5819. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5820. });
  5821. auto se = detail::scope_exit([&] {
  5822. svr.stop();
  5823. get_thread.join();
  5824. listen_thread.join();
  5825. ASSERT_FALSE(svr.is_running());
  5826. });
  5827. // Give GET time to get a few messages.
  5828. std::this_thread::sleep_for(std::chrono::seconds(2));
  5829. }
  5830. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5831. httplib::Server svr;
  5832. svr.Post("/hi",
  5833. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5834. res.status = StatusCode::OK_200;
  5835. });
  5836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5837. svr.wait_until_ready();
  5838. Client cli(HOST, PORT);
  5839. auto res = cli.Post("/hi", "data", "text/plain");
  5840. ASSERT_TRUE(res);
  5841. EXPECT_EQ(StatusCode::OK_200, res->status);
  5842. svr.stop();
  5843. thread.join();
  5844. ASSERT_FALSE(svr.is_running());
  5845. res = cli.Post("/hi", "data", "text/plain");
  5846. ASSERT_FALSE(res);
  5847. }
  5848. TEST(ServerStopTest, ListenFailure) {
  5849. Server svr;
  5850. auto t = thread([&]() {
  5851. auto ret = svr.listen("????", PORT);
  5852. EXPECT_FALSE(ret);
  5853. });
  5854. svr.wait_until_ready();
  5855. svr.stop();
  5856. t.join();
  5857. }
  5858. TEST(ServerStopTest, Decommision) {
  5859. Server svr;
  5860. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5861. for (int i = 0; i < 4; i++) {
  5862. auto is_even = !(i % 2);
  5863. std::thread t{[&] {
  5864. try {
  5865. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5866. if (is_even) {
  5867. throw std::runtime_error("Some thing that happens to go wrong.");
  5868. }
  5869. svr.listen(HOST, PORT);
  5870. } catch (...) { svr.decommission(); }
  5871. }};
  5872. svr.wait_until_ready();
  5873. // Server is up
  5874. {
  5875. Client cli(HOST, PORT);
  5876. auto res = cli.Get("/hi");
  5877. if (is_even) {
  5878. EXPECT_FALSE(res);
  5879. } else {
  5880. EXPECT_TRUE(res);
  5881. EXPECT_EQ("hi...", res->body);
  5882. }
  5883. }
  5884. svr.stop();
  5885. t.join();
  5886. // Server is down...
  5887. {
  5888. Client cli(HOST, PORT);
  5889. auto res = cli.Get("/hi");
  5890. EXPECT_FALSE(res);
  5891. }
  5892. }
  5893. }
  5894. // Helper function for string body upload progress tests
  5895. template <typename SetupHandler, typename ClientCall>
  5896. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5897. ClientCall &&client_call,
  5898. const string &body) {
  5899. Server svr;
  5900. setup_handler(svr);
  5901. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5902. auto se = detail::scope_exit([&] {
  5903. svr.stop();
  5904. t.join();
  5905. });
  5906. svr.wait_until_ready();
  5907. Client cli(HOST, PORT);
  5908. vector<uint64_t> progress_values;
  5909. bool progress_called = false;
  5910. auto res =
  5911. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5912. progress_values.push_back(current);
  5913. progress_called = true;
  5914. return true;
  5915. });
  5916. ASSERT_TRUE(res);
  5917. EXPECT_EQ(200, res->status);
  5918. EXPECT_TRUE(progress_called);
  5919. }
  5920. TEST(UploadProgressTest, PostStringBodyBasic) {
  5921. TestStringBodyUploadProgress(
  5922. [](Server &svr) {
  5923. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5924. res.set_content("received", "text/plain");
  5925. });
  5926. },
  5927. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5928. return cli.Post("/test", body, "text/plain", progress_callback);
  5929. },
  5930. "test data for upload progress");
  5931. }
  5932. TEST(UploadProgressTest, PutStringBodyBasic) {
  5933. TestStringBodyUploadProgress(
  5934. [](Server &svr) {
  5935. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5936. res.set_content("put received", "text/plain");
  5937. });
  5938. },
  5939. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5940. return cli.Put("/test", body, "text/plain", progress_callback);
  5941. },
  5942. "put test data for upload progress");
  5943. }
  5944. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5945. TestStringBodyUploadProgress(
  5946. [](Server &svr) {
  5947. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5948. res.set_content("patch received", "text/plain");
  5949. });
  5950. },
  5951. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5952. return cli.Patch("/test", body, "text/plain", progress_callback);
  5953. },
  5954. "patch test data for upload progress");
  5955. }
  5956. // Helper function for content provider upload progress tests
  5957. template <typename SetupHandler, typename ClientCall>
  5958. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5959. ClientCall &&client_call) {
  5960. Server svr;
  5961. setup_handler(svr);
  5962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5963. auto se = detail::scope_exit([&] {
  5964. svr.stop();
  5965. t.join();
  5966. });
  5967. svr.wait_until_ready();
  5968. Client cli(HOST, PORT);
  5969. vector<uint64_t> progress_values;
  5970. auto res =
  5971. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5972. progress_values.push_back(current);
  5973. return true;
  5974. });
  5975. ASSERT_TRUE(res);
  5976. EXPECT_EQ(200, res->status);
  5977. EXPECT_FALSE(progress_values.empty());
  5978. }
  5979. TEST(UploadProgressTest, PostContentProviderProgress) {
  5980. TestContentProviderUploadProgress(
  5981. [](Server &svr) {
  5982. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5983. res.set_content("provider received", "text/plain");
  5984. });
  5985. },
  5986. [](Client &cli, UploadProgress progress_callback) {
  5987. return cli.Post(
  5988. "/test", 10,
  5989. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5990. sink.os << "test data";
  5991. return true;
  5992. },
  5993. "text/plain", progress_callback);
  5994. });
  5995. }
  5996. // Helper function for multipart upload progress tests
  5997. template <typename SetupHandler, typename ClientCall>
  5998. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5999. ClientCall &&client_call,
  6000. const string &endpoint) {
  6001. Server svr;
  6002. setup_handler(svr);
  6003. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6004. auto se = detail::scope_exit([&] {
  6005. svr.stop();
  6006. t.join();
  6007. });
  6008. svr.wait_until_ready();
  6009. Client cli(HOST, PORT);
  6010. vector<uint64_t> progress_values;
  6011. UploadFormDataItems items = {
  6012. {"field1", "value1", "", ""},
  6013. {"field2", "longer value for progress tracking test", "", ""},
  6014. {"file1", "file content data for upload progress", "test.txt",
  6015. "text/plain"}};
  6016. auto res = client_call(cli, endpoint, items,
  6017. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6018. progress_values.push_back(current);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(res);
  6022. EXPECT_EQ(200, res->status);
  6023. EXPECT_FALSE(progress_values.empty());
  6024. }
  6025. TEST(UploadProgressTest, PostMultipartProgress) {
  6026. TestMultipartUploadProgress(
  6027. [](Server &svr) {
  6028. svr.Post("/multipart", [](const Request &req, Response &res) {
  6029. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6030. res.set_content("multipart received", "text/plain");
  6031. });
  6032. },
  6033. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6034. UploadProgress progress_callback) {
  6035. return cli.Post(endpoint, items, progress_callback);
  6036. },
  6037. "/multipart");
  6038. }
  6039. // Helper function for basic download progress tests
  6040. template <typename SetupHandler, typename ClientCall>
  6041. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6042. ClientCall &&client_call, const string &endpoint,
  6043. size_t expected_content_size) {
  6044. Server svr;
  6045. setup_handler(svr);
  6046. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6047. auto se = detail::scope_exit([&] {
  6048. svr.stop();
  6049. t.join();
  6050. });
  6051. svr.wait_until_ready();
  6052. Client cli(HOST, PORT);
  6053. vector<uint64_t> progress_values;
  6054. auto res = client_call(cli, endpoint,
  6055. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6056. progress_values.push_back(current);
  6057. return true;
  6058. });
  6059. ASSERT_TRUE(res);
  6060. EXPECT_EQ(200, res->status);
  6061. EXPECT_FALSE(progress_values.empty());
  6062. EXPECT_EQ(expected_content_size, res->body.size());
  6063. }
  6064. TEST(DownloadProgressTest, GetBasic) {
  6065. TestBasicDownloadProgress(
  6066. [](Server &svr) {
  6067. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6068. string content(1000, 'D');
  6069. res.set_content(content, "text/plain");
  6070. });
  6071. },
  6072. [](Client &cli, const string &endpoint,
  6073. DownloadProgress progress_callback) {
  6074. return cli.Get(endpoint, progress_callback);
  6075. },
  6076. "/download", 1000u);
  6077. }
  6078. // Helper function for content receiver download progress tests
  6079. template <typename SetupHandler, typename ClientCall>
  6080. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6081. ClientCall &&client_call,
  6082. const string &endpoint,
  6083. size_t expected_content_size) {
  6084. Server svr;
  6085. setup_handler(svr);
  6086. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6087. auto se = detail::scope_exit([&] {
  6088. svr.stop();
  6089. t.join();
  6090. });
  6091. svr.wait_until_ready();
  6092. Client cli(HOST, PORT);
  6093. vector<uint64_t> progress_values;
  6094. string received_body;
  6095. auto res = client_call(
  6096. cli, endpoint,
  6097. [&](const char *data, size_t data_length) -> bool {
  6098. received_body.append(data, data_length);
  6099. return true;
  6100. },
  6101. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6102. progress_values.push_back(current);
  6103. return true;
  6104. });
  6105. ASSERT_TRUE(res);
  6106. EXPECT_EQ(200, res->status);
  6107. EXPECT_FALSE(progress_values.empty());
  6108. EXPECT_EQ(expected_content_size, received_body.size());
  6109. EXPECT_TRUE(res->body.empty());
  6110. }
  6111. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6112. TestContentReceiverDownloadProgress(
  6113. [](Server &svr) {
  6114. svr.Get("/download-receiver",
  6115. [](const Request & /*req*/, Response &res) {
  6116. string content(2000, 'R');
  6117. res.set_content(content, "text/plain");
  6118. });
  6119. },
  6120. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6121. DownloadProgress progress_callback) {
  6122. return cli.Get(endpoint, content_receiver, progress_callback);
  6123. },
  6124. "/download-receiver", 2000u);
  6125. }
  6126. TEST(StreamingTest, NoContentLengthStreaming) {
  6127. Server svr;
  6128. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6129. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6130. if (offset < 6) {
  6131. sink.os << (offset < 3 ? "a" : "b");
  6132. } else {
  6133. sink.done();
  6134. }
  6135. return true;
  6136. });
  6137. });
  6138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6139. auto listen_se = detail::scope_exit([&] {
  6140. svr.stop();
  6141. listen_thread.join();
  6142. ASSERT_FALSE(svr.is_running());
  6143. });
  6144. svr.wait_until_ready();
  6145. Client client(HOST, PORT);
  6146. auto get_thread = std::thread([&client]() {
  6147. std::string s;
  6148. auto res =
  6149. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6150. s += std::string(data, len);
  6151. return true;
  6152. });
  6153. ASSERT_TRUE(res);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ("aaabbb", s);
  6156. });
  6157. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6158. // Give GET time to get a few messages.
  6159. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6160. }
  6161. TEST(MountTest, Unmount) {
  6162. Server svr;
  6163. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6164. auto se = detail::scope_exit([&] {
  6165. svr.stop();
  6166. listen_thread.join();
  6167. ASSERT_FALSE(svr.is_running());
  6168. });
  6169. svr.wait_until_ready();
  6170. Client cli("localhost", PORT);
  6171. svr.set_mount_point("/mount2", "./www2");
  6172. auto res = cli.Get("/");
  6173. ASSERT_TRUE(res);
  6174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6175. res = cli.Get("/mount2/dir/test.html");
  6176. ASSERT_TRUE(res);
  6177. EXPECT_EQ(StatusCode::OK_200, res->status);
  6178. svr.set_mount_point("/", "./www");
  6179. res = cli.Get("/dir/");
  6180. ASSERT_TRUE(res);
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. svr.remove_mount_point("/");
  6183. res = cli.Get("/dir/");
  6184. ASSERT_TRUE(res);
  6185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6186. svr.remove_mount_point("/mount2");
  6187. res = cli.Get("/mount2/dir/test.html");
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6190. }
  6191. TEST(MountTest, Redicect) {
  6192. Server svr;
  6193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6194. auto se = detail::scope_exit([&] {
  6195. svr.stop();
  6196. listen_thread.join();
  6197. ASSERT_FALSE(svr.is_running());
  6198. });
  6199. svr.set_mount_point("/", "./www");
  6200. svr.wait_until_ready();
  6201. Client cli("localhost", PORT);
  6202. auto res = cli.Get("/dir/");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. res = cli.Get("/dir");
  6206. ASSERT_TRUE(res);
  6207. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6208. res = cli.Get("/file");
  6209. ASSERT_TRUE(res);
  6210. EXPECT_EQ(StatusCode::OK_200, res->status);
  6211. res = cli.Get("/file/");
  6212. ASSERT_TRUE(res);
  6213. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6214. cli.set_follow_location(true);
  6215. res = cli.Get("/dir");
  6216. ASSERT_TRUE(res);
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. }
  6219. TEST(MountTest, MultibytesPathName) {
  6220. Server svr;
  6221. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6222. auto se = detail::scope_exit([&] {
  6223. svr.stop();
  6224. listen_thread.join();
  6225. ASSERT_FALSE(svr.is_running());
  6226. });
  6227. svr.set_mount_point("/", "./www");
  6228. svr.wait_until_ready();
  6229. Client cli("localhost", PORT);
  6230. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6231. ASSERT_TRUE(res);
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6234. }
  6235. TEST(KeepAliveTest, ReadTimeout) {
  6236. Server svr;
  6237. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6238. std::this_thread::sleep_for(std::chrono::seconds(2));
  6239. res.set_content("a", "text/plain");
  6240. });
  6241. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6242. res.set_content("b", "text/plain");
  6243. });
  6244. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6245. auto se = detail::scope_exit([&] {
  6246. svr.stop();
  6247. listen_thread.join();
  6248. ASSERT_FALSE(svr.is_running());
  6249. });
  6250. svr.wait_until_ready();
  6251. Client cli("localhost", PORT);
  6252. cli.set_keep_alive(true);
  6253. cli.set_read_timeout(std::chrono::seconds(1));
  6254. auto resa = cli.Get("/a");
  6255. ASSERT_FALSE(resa);
  6256. EXPECT_EQ(Error::Read, resa.error());
  6257. auto resb = cli.Get("/b");
  6258. ASSERT_TRUE(resb);
  6259. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6260. EXPECT_EQ("b", resb->body);
  6261. }
  6262. TEST(KeepAliveTest, MaxCount) {
  6263. size_t keep_alive_max_count = 3;
  6264. Server svr;
  6265. svr.set_keep_alive_max_count(keep_alive_max_count);
  6266. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6267. res.set_content("Hello World!", "text/plain");
  6268. });
  6269. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6270. auto se = detail::scope_exit([&] {
  6271. svr.stop();
  6272. listen_thread.join();
  6273. ASSERT_FALSE(svr.is_running());
  6274. });
  6275. svr.wait_until_ready();
  6276. Client cli(HOST, PORT);
  6277. cli.set_keep_alive(true);
  6278. for (size_t i = 0; i < 5; i++) {
  6279. auto result = cli.Get("/hi");
  6280. ASSERT_TRUE(result);
  6281. EXPECT_EQ(StatusCode::OK_200, result->status);
  6282. if (i == keep_alive_max_count - 1) {
  6283. EXPECT_EQ("close", result->get_header_value("Connection"));
  6284. } else {
  6285. EXPECT_FALSE(result->has_header("Connection"));
  6286. }
  6287. }
  6288. }
  6289. TEST(KeepAliveTest, Issue1041) {
  6290. Server svr;
  6291. svr.set_keep_alive_timeout(3);
  6292. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6293. res.set_content("Hello World!", "text/plain");
  6294. });
  6295. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6296. auto se = detail::scope_exit([&] {
  6297. svr.stop();
  6298. listen_thread.join();
  6299. ASSERT_FALSE(svr.is_running());
  6300. });
  6301. svr.wait_until_ready();
  6302. Client cli(HOST, PORT);
  6303. cli.set_keep_alive(true);
  6304. auto result = cli.Get("/hi");
  6305. ASSERT_TRUE(result);
  6306. EXPECT_EQ(StatusCode::OK_200, result->status);
  6307. std::this_thread::sleep_for(std::chrono::seconds(5));
  6308. result = cli.Get("/hi");
  6309. ASSERT_TRUE(result);
  6310. EXPECT_EQ(StatusCode::OK_200, result->status);
  6311. }
  6312. TEST(KeepAliveTest, Issue1959) {
  6313. Server svr;
  6314. svr.set_keep_alive_timeout(5);
  6315. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6316. res.set_content("a", "text/plain");
  6317. });
  6318. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6319. auto se = detail::scope_exit([&] {
  6320. if (!svr.is_running()) return;
  6321. svr.stop();
  6322. listen_thread.join();
  6323. ASSERT_FALSE(svr.is_running());
  6324. });
  6325. svr.wait_until_ready();
  6326. Client cli("localhost", PORT);
  6327. cli.set_keep_alive(true);
  6328. using namespace std::chrono;
  6329. auto start = steady_clock::now();
  6330. cli.Get("/a");
  6331. svr.stop();
  6332. listen_thread.join();
  6333. auto end = steady_clock::now();
  6334. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6335. EXPECT_LT(elapsed, 5000);
  6336. }
  6337. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6338. TEST(KeepAliveTest, SSLClientReconnection) {
  6339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6340. ASSERT_TRUE(svr.is_valid());
  6341. svr.set_keep_alive_timeout(1);
  6342. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6343. res.set_content("Hello World!", "text/plain");
  6344. });
  6345. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6346. auto se = detail::scope_exit([&] {
  6347. svr.stop();
  6348. listen_thread.join();
  6349. ASSERT_FALSE(svr.is_running());
  6350. });
  6351. svr.wait_until_ready();
  6352. SSLClient cli(HOST, PORT);
  6353. cli.enable_server_certificate_verification(false);
  6354. cli.set_keep_alive(true);
  6355. auto result = cli.Get("/hi");
  6356. ASSERT_TRUE(result);
  6357. EXPECT_EQ(StatusCode::OK_200, result->status);
  6358. result = cli.Get("/hi");
  6359. ASSERT_TRUE(result);
  6360. EXPECT_EQ(StatusCode::OK_200, result->status);
  6361. std::this_thread::sleep_for(std::chrono::seconds(2));
  6362. // Recoonect
  6363. result = cli.Get("/hi");
  6364. ASSERT_TRUE(result);
  6365. EXPECT_EQ(StatusCode::OK_200, result->status);
  6366. result = cli.Get("/hi");
  6367. ASSERT_TRUE(result);
  6368. EXPECT_EQ(StatusCode::OK_200, result->status);
  6369. }
  6370. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6372. ASSERT_TRUE(svr.is_valid());
  6373. svr.set_keep_alive_timeout(1);
  6374. std::string content = "reconnect";
  6375. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6376. res.set_content("Hello World!", "text/plain");
  6377. });
  6378. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6379. auto se = detail::scope_exit([&] {
  6380. svr.stop();
  6381. listen_thread.join();
  6382. ASSERT_FALSE(svr.is_running());
  6383. });
  6384. svr.wait_until_ready();
  6385. SSLClient cli(HOST, PORT);
  6386. cli.enable_server_certificate_verification(false);
  6387. cli.set_keep_alive(true);
  6388. auto result = cli.Post(
  6389. "/hi", content.size(),
  6390. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6391. sink.write(content.c_str(), content.size());
  6392. return true;
  6393. },
  6394. "text/plain");
  6395. ASSERT_TRUE(result);
  6396. EXPECT_EQ(200, result->status);
  6397. std::this_thread::sleep_for(std::chrono::seconds(2));
  6398. // Recoonect
  6399. result = cli.Post(
  6400. "/hi", content.size(),
  6401. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6402. sink.write(content.c_str(), content.size());
  6403. return true;
  6404. },
  6405. "text/plain");
  6406. ASSERT_TRUE(result);
  6407. EXPECT_EQ(200, result->status);
  6408. result = cli.Post(
  6409. "/hi", content.size(),
  6410. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6411. sink.write(content.c_str(), content.size());
  6412. return true;
  6413. },
  6414. "text/plain");
  6415. ASSERT_TRUE(result);
  6416. EXPECT_EQ(200, result->status);
  6417. }
  6418. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6419. {
  6420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6421. ASSERT_TRUE(svr.is_valid());
  6422. svr.Get("/sni", [&](const Request &req, Response &res) {
  6423. std::string expected;
  6424. if (req.ssl) {
  6425. if (const char *sni =
  6426. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6427. expected = sni;
  6428. }
  6429. }
  6430. EXPECT_EQ(expected, req.get_param_value("expected"));
  6431. res.set_content("ok", "text/plain");
  6432. });
  6433. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6434. auto se = detail::scope_exit([&] {
  6435. svr.stop();
  6436. listen_thread.join();
  6437. ASSERT_FALSE(svr.is_running());
  6438. });
  6439. svr.wait_until_ready();
  6440. {
  6441. SSLClient cli("localhost", PORT);
  6442. cli.enable_server_certificate_verification(false);
  6443. auto res = cli.Get("/sni?expected=localhost");
  6444. ASSERT_TRUE(res);
  6445. }
  6446. {
  6447. SSLClient cli("::1", PORT);
  6448. cli.enable_server_certificate_verification(false);
  6449. auto res = cli.Get("/sni?expected=");
  6450. // NOTE: This may fail if the server is listening on IPv4 only
  6451. // (e.g., when localhost resolves to 127.0.0.1 only)
  6452. if (res) {
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. } else {
  6455. EXPECT_EQ(Error::Connection, res.error());
  6456. }
  6457. }
  6458. }
  6459. }
  6460. #endif
  6461. TEST(ClientProblemDetectionTest, ContentProvider) {
  6462. Server svr;
  6463. size_t content_length = 1024 * 1024;
  6464. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6465. res.set_content_provider(
  6466. content_length, "text/plain",
  6467. [&](size_t offset, size_t length, DataSink &sink) {
  6468. auto out_len = std::min(length, static_cast<size_t>(1024));
  6469. std::string out(out_len, '@');
  6470. sink.write(out.data(), out_len);
  6471. return offset < 4096;
  6472. },
  6473. [](bool success) { ASSERT_FALSE(success); });
  6474. });
  6475. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6476. res.set_content_provider(
  6477. 0, "text/plain",
  6478. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6479. EXPECT_TRUE(false);
  6480. return true;
  6481. },
  6482. [](bool success) { ASSERT_FALSE(success); });
  6483. });
  6484. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6485. auto se = detail::scope_exit([&] {
  6486. svr.stop();
  6487. listen_thread.join();
  6488. ASSERT_FALSE(svr.is_running());
  6489. });
  6490. svr.wait_until_ready();
  6491. Client cli("localhost", PORT);
  6492. {
  6493. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6494. size_t /*data_length*/) { return false; });
  6495. ASSERT_FALSE(res);
  6496. }
  6497. {
  6498. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6499. size_t /*data_length*/) { return false; });
  6500. ASSERT_TRUE(res);
  6501. }
  6502. }
  6503. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6504. Server svr;
  6505. svr.set_error_handler([](Request const &, Response &res) -> void {
  6506. res.set_chunked_content_provider(
  6507. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6508. sink.os << "hello";
  6509. sink.os << "world";
  6510. sink.done();
  6511. return true;
  6512. });
  6513. });
  6514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6515. auto se = detail::scope_exit([&] {
  6516. svr.stop();
  6517. listen_thread.join();
  6518. ASSERT_FALSE(svr.is_running());
  6519. });
  6520. svr.wait_until_ready();
  6521. Client cli("localhost", PORT);
  6522. auto res = cli.Get("/");
  6523. ASSERT_TRUE(res);
  6524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6525. EXPECT_EQ("helloworld", res->body);
  6526. }
  6527. TEST(LongPollingTest, ClientCloseDetection) {
  6528. Server svr;
  6529. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6530. res.set_chunked_content_provider(
  6531. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6532. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6533. sink.os << "hello";
  6534. auto count = 10;
  6535. while (count > 0 && sink.is_writable()) {
  6536. this_thread::sleep_for(chrono::milliseconds(10));
  6537. count--;
  6538. }
  6539. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6540. return true;
  6541. });
  6542. });
  6543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6544. auto se = detail::scope_exit([&] {
  6545. svr.stop();
  6546. listen_thread.join();
  6547. ASSERT_FALSE(svr.is_running());
  6548. });
  6549. svr.wait_until_ready();
  6550. Client cli("localhost", PORT);
  6551. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6552. EXPECT_EQ("hello", string(data, data_length));
  6553. return false; // close the socket immediately.
  6554. });
  6555. ASSERT_FALSE(res);
  6556. }
  6557. TEST(GetWithParametersTest, GetWithParameters) {
  6558. Server svr;
  6559. svr.Get("/", [&](const Request &req, Response &) {
  6560. EXPECT_EQ("world", req.get_param_value("hello"));
  6561. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6562. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6563. });
  6564. svr.Get("/params", [&](const Request &req, Response &) {
  6565. EXPECT_EQ("world", req.get_param_value("hello"));
  6566. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6567. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6568. });
  6569. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6570. EXPECT_EQ("resource-id", req.matches[1]);
  6571. EXPECT_EQ("foo", req.get_param_value("param1"));
  6572. EXPECT_EQ("bar", req.get_param_value("param2"));
  6573. });
  6574. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6575. EXPECT_EQ("user-id", req.path_params.at("id"));
  6576. EXPECT_EQ("foo", req.get_param_value("param1"));
  6577. EXPECT_EQ("bar", req.get_param_value("param2"));
  6578. });
  6579. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6580. auto se = detail::scope_exit([&] {
  6581. svr.stop();
  6582. listen_thread.join();
  6583. ASSERT_FALSE(svr.is_running());
  6584. });
  6585. svr.wait_until_ready();
  6586. {
  6587. Client cli(HOST, PORT);
  6588. Params params;
  6589. params.emplace("hello", "world");
  6590. params.emplace("hello2", "world2");
  6591. params.emplace("hello3", "world3");
  6592. auto res = cli.Get("/", params, Headers{});
  6593. ASSERT_TRUE(res);
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. }
  6596. {
  6597. Client cli(HOST, PORT);
  6598. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6599. ASSERT_TRUE(res);
  6600. EXPECT_EQ(StatusCode::OK_200, res->status);
  6601. }
  6602. {
  6603. Client cli(HOST, PORT);
  6604. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6605. ASSERT_TRUE(res);
  6606. EXPECT_EQ(StatusCode::OK_200, res->status);
  6607. }
  6608. {
  6609. Client cli(HOST, PORT);
  6610. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6611. ASSERT_TRUE(res);
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. }
  6615. TEST(GetWithParametersTest, GetWithParameters2) {
  6616. Server svr;
  6617. svr.Get("/", [&](const Request &req, Response &res) {
  6618. auto text = req.get_param_value("hello");
  6619. res.set_content(text, "text/plain");
  6620. });
  6621. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6622. auto se = detail::scope_exit([&] {
  6623. svr.stop();
  6624. listen_thread.join();
  6625. ASSERT_FALSE(svr.is_running());
  6626. });
  6627. svr.wait_until_ready();
  6628. Client cli("localhost", PORT);
  6629. Params params;
  6630. params.emplace("hello", "world");
  6631. std::string body;
  6632. auto res = cli.Get("/", params, Headers{},
  6633. [&](const char *data, size_t data_length) {
  6634. body.append(data, data_length);
  6635. return true;
  6636. });
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("world", body);
  6640. }
  6641. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6642. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6643. auto host = "httpbin.org";
  6644. auto path = std::string{"/range/32"};
  6645. #else
  6646. auto host = "nghttp2.org";
  6647. auto path = std::string{"/httpbin/range/32"};
  6648. #endif
  6649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6650. SSLClient cli(host);
  6651. #else
  6652. Client cli(host);
  6653. #endif
  6654. cli.set_default_headers({make_range_header({{1, 10}})});
  6655. cli.set_connection_timeout(5);
  6656. {
  6657. auto res = cli.Get(path);
  6658. ASSERT_TRUE(res);
  6659. EXPECT_EQ("bcdefghijk", res->body);
  6660. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6661. }
  6662. {
  6663. auto res = cli.Get(path);
  6664. ASSERT_TRUE(res);
  6665. EXPECT_EQ("bcdefghijk", res->body);
  6666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6667. }
  6668. }
  6669. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6670. Server svr;
  6671. svr.set_default_headers({{"Hello", "World"}});
  6672. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6673. res.set_content("ok", "text/plain");
  6674. });
  6675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6676. auto se = detail::scope_exit([&] {
  6677. svr.stop();
  6678. listen_thread.join();
  6679. ASSERT_FALSE(svr.is_running());
  6680. });
  6681. svr.wait_until_ready();
  6682. Client cli("localhost", PORT);
  6683. auto res = cli.Get("/");
  6684. ASSERT_TRUE(res);
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. EXPECT_EQ("ok", res->body);
  6687. EXPECT_EQ("World", res->get_header_value("Hello"));
  6688. }
  6689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6690. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6692. ASSERT_TRUE(svr.is_valid());
  6693. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6694. std::this_thread::sleep_for(std::chrono::seconds(2));
  6695. res.set_content("a", "text/plain");
  6696. });
  6697. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6698. res.set_content("b", "text/plain");
  6699. });
  6700. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6701. auto se = detail::scope_exit([&] {
  6702. svr.stop();
  6703. listen_thread.join();
  6704. ASSERT_FALSE(svr.is_running());
  6705. });
  6706. svr.wait_until_ready();
  6707. SSLClient cli("localhost", PORT);
  6708. cli.enable_server_certificate_verification(false);
  6709. cli.set_keep_alive(true);
  6710. cli.set_read_timeout(std::chrono::seconds(1));
  6711. auto resa = cli.Get("/a");
  6712. ASSERT_TRUE(!resa);
  6713. EXPECT_EQ(Error::Read, resa.error());
  6714. auto resb = cli.Get("/b");
  6715. ASSERT_TRUE(resb);
  6716. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6717. EXPECT_EQ("b", resb->body);
  6718. }
  6719. #endif
  6720. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6721. protected:
  6722. ServerTestWithAI_PASSIVE()
  6723. : cli_(HOST, PORT)
  6724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6725. ,
  6726. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6727. #endif
  6728. {
  6729. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6730. cli_.enable_server_certificate_verification(false);
  6731. #endif
  6732. }
  6733. virtual void SetUp() {
  6734. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6735. res.set_content("Hello World!", "text/plain");
  6736. });
  6737. t_ = thread(
  6738. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6739. svr_.wait_until_ready();
  6740. }
  6741. virtual void TearDown() {
  6742. svr_.stop();
  6743. t_.join();
  6744. }
  6745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6746. SSLClient cli_;
  6747. SSLServer svr_;
  6748. #else
  6749. Client cli_;
  6750. Server svr_;
  6751. #endif
  6752. thread t_;
  6753. };
  6754. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6755. auto res = cli_.Get("/hi");
  6756. ASSERT_TRUE(res);
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6759. EXPECT_EQ("Hello World!", res->body);
  6760. }
  6761. class ServerUpDownTest : public ::testing::Test {
  6762. protected:
  6763. ServerUpDownTest() : cli_(HOST, PORT) {}
  6764. virtual void SetUp() {
  6765. t_ = thread([&]() {
  6766. svr_.bind_to_any_port(HOST);
  6767. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6768. ASSERT_TRUE(svr_.listen_after_bind());
  6769. });
  6770. svr_.wait_until_ready();
  6771. }
  6772. virtual void TearDown() {
  6773. svr_.stop();
  6774. t_.join();
  6775. }
  6776. Client cli_;
  6777. Server svr_;
  6778. thread t_;
  6779. };
  6780. TEST_F(ServerUpDownTest, QuickStartStop) {
  6781. // Should not crash, especially when run with
  6782. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6783. }
  6784. class PayloadMaxLengthTest : public ::testing::Test {
  6785. protected:
  6786. PayloadMaxLengthTest()
  6787. : cli_(HOST, PORT)
  6788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6789. ,
  6790. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6791. #endif
  6792. {
  6793. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6794. cli_.enable_server_certificate_verification(false);
  6795. #endif
  6796. }
  6797. virtual void SetUp() {
  6798. svr_.set_payload_max_length(8);
  6799. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6800. res.set_content("test", "text/plain");
  6801. });
  6802. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6803. svr_.wait_until_ready();
  6804. }
  6805. virtual void TearDown() {
  6806. svr_.stop();
  6807. t_.join();
  6808. }
  6809. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6810. SSLClient cli_;
  6811. SSLServer svr_;
  6812. #else
  6813. Client cli_;
  6814. Server svr_;
  6815. #endif
  6816. thread t_;
  6817. };
  6818. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6819. auto res = cli_.Post("/test", "123456789", "text/plain");
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6822. res = cli_.Post("/test", "12345678", "text/plain");
  6823. ASSERT_TRUE(res);
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. }
  6826. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6827. // Test chunked encoding with payload exceeding the 8-byte limit
  6828. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6829. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6830. ASSERT_TRUE(res);
  6831. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6832. }
  6833. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6834. // Test chunked encoding with payload within the 8-byte limit
  6835. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6836. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6837. ASSERT_TRUE(res);
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. }
  6840. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6841. // Test using send_request to send chunked data exceeding payload limit
  6842. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6843. "Host: " +
  6844. std::string(HOST) + ":" + std::to_string(PORT) +
  6845. "\r\n"
  6846. "Transfer-Encoding: chunked\r\n"
  6847. "Connection: close\r\n"
  6848. "\r\n"
  6849. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6850. "0123456789\r\n"
  6851. "0\r\n" // End chunk
  6852. "\r\n";
  6853. std::string response;
  6854. bool result = send_request(1, chunked_request, &response);
  6855. if (!result) {
  6856. // If send_request fails, it might be because the server closed the
  6857. // connection due to payload limit enforcement, which is acceptable
  6858. SUCCEED()
  6859. << "Server rejected oversized chunked request (connection closed)";
  6860. } else {
  6861. // If we got a response, check if it's an error response or connection was
  6862. // closed early Short response length indicates connection was closed due to
  6863. // payload limit
  6864. if (response.length() <= 10) {
  6865. SUCCEED() << "Server closed connection for oversized chunked request";
  6866. } else {
  6867. // Check for error status codes
  6868. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6869. response.find("Payload Too Large") != std::string::npos ||
  6870. response.find("400") != std::string::npos);
  6871. }
  6872. }
  6873. }
  6874. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6875. // Test request without Content-Length header exceeding payload limit
  6876. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6877. "Host: " +
  6878. std::string(HOST) + ":" +
  6879. std::to_string(PORT) +
  6880. "\r\n"
  6881. "Connection: close\r\n"
  6882. "\r\n";
  6883. // Add payload exceeding the 8-byte limit
  6884. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6885. request_without_content_length += large_payload;
  6886. std::string response;
  6887. bool result = send_request(1, request_without_content_length, &response);
  6888. if (!result) {
  6889. // If send_request fails, server likely closed connection due to payload
  6890. // limit
  6891. SUCCEED() << "Server rejected oversized request without Content-Length "
  6892. "(connection closed)";
  6893. } else {
  6894. // Check if server responded with error or closed connection early
  6895. if (response.length() <= 10) {
  6896. SUCCEED() << "Server closed connection for oversized request without "
  6897. "Content-Length";
  6898. } else {
  6899. // Check for error status codes
  6900. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6901. response.find("Payload Too Large") != std::string::npos ||
  6902. response.find("400") != std::string::npos);
  6903. }
  6904. }
  6905. }
  6906. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6907. // Test request without Content-Length header within payload limit
  6908. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6909. "Host: " +
  6910. std::string(HOST) + ":" +
  6911. std::to_string(PORT) +
  6912. "\r\n"
  6913. "Connection: close\r\n"
  6914. "\r\n";
  6915. // Add payload within the 8-byte limit
  6916. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6917. request_without_content_length += small_payload;
  6918. std::string response;
  6919. bool result = send_request(1, request_without_content_length, &response);
  6920. // For requests without Content-Length, the server may have different behavior
  6921. // The key is that it should not reject due to payload limit for small
  6922. // payloads
  6923. if (result) {
  6924. // Check for any HTTP response (success or error, but not connection closed)
  6925. if (response.length() > 10) {
  6926. SUCCEED()
  6927. << "Server processed request without Content-Length within limit";
  6928. } else {
  6929. // Short response might indicate connection closed, which is acceptable
  6930. SUCCEED() << "Server closed connection for request without "
  6931. "Content-Length (acceptable behavior)";
  6932. }
  6933. } else {
  6934. // Connection failure might be due to protocol requirements
  6935. SUCCEED() << "Connection issue with request without Content-Length "
  6936. "(environment-specific)";
  6937. }
  6938. }
  6939. class LargePayloadMaxLengthTest : public ::testing::Test {
  6940. protected:
  6941. LargePayloadMaxLengthTest()
  6942. : cli_(HOST, PORT)
  6943. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6944. ,
  6945. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6946. #endif
  6947. {
  6948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6949. cli_.enable_server_certificate_verification(false);
  6950. #endif
  6951. }
  6952. virtual void SetUp() {
  6953. // Set 10MB payload limit
  6954. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6955. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6956. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6957. res.set_content("Large payload test", "text/plain");
  6958. });
  6959. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6960. svr_.wait_until_ready();
  6961. }
  6962. virtual void TearDown() {
  6963. svr_.stop();
  6964. t_.join();
  6965. }
  6966. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6967. SSLClient cli_;
  6968. SSLServer svr_;
  6969. #else
  6970. Client cli_;
  6971. Server svr_;
  6972. #endif
  6973. thread t_;
  6974. };
  6975. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6976. // Test chunked encoding with payload within 10MB limit
  6977. std::string medium_payload(5 * 1024 * 1024,
  6978. 'A'); // 5MB payload, within 10MB limit
  6979. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6980. ASSERT_TRUE(res);
  6981. EXPECT_EQ(StatusCode::OK_200, res->status);
  6982. }
  6983. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6984. // Test chunked encoding with payload exceeding 10MB limit
  6985. std::string large_payload(12 * 1024 * 1024,
  6986. 'B'); // 12MB payload, exceeds 10MB limit
  6987. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6988. ASSERT_TRUE(res);
  6989. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6990. }
  6991. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6992. // Test request without Content-Length header within 10MB limit
  6993. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6994. "Host: " +
  6995. std::string(HOST) + ":" +
  6996. std::to_string(PORT) +
  6997. "\r\n"
  6998. "Connection: close\r\n"
  6999. "\r\n";
  7000. // Add 1MB payload (within 10MB limit)
  7001. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7002. request_without_content_length += medium_payload;
  7003. std::string response;
  7004. bool result = send_request(5, request_without_content_length, &response);
  7005. if (result) {
  7006. // Should get a proper HTTP response for payloads within limit
  7007. if (response.length() > 10) {
  7008. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7009. "10MB limit";
  7010. } else {
  7011. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7012. "Content-Length)";
  7013. }
  7014. } else {
  7015. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7016. }
  7017. }
  7018. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7019. // Test request without Content-Length header exceeding 10MB limit
  7020. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7021. "Host: " +
  7022. std::string(HOST) + ":" +
  7023. std::to_string(PORT) +
  7024. "\r\n"
  7025. "Connection: close\r\n"
  7026. "\r\n";
  7027. // Add 12MB payload (exceeds 10MB limit)
  7028. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7029. request_without_content_length += large_payload;
  7030. std::string response;
  7031. bool result = send_request(10, request_without_content_length, &response);
  7032. if (!result) {
  7033. // Server should close connection due to payload limit
  7034. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7035. "(connection closed)";
  7036. } else {
  7037. // Check for error response
  7038. if (response.length() <= 10) {
  7039. SUCCEED()
  7040. << "Server closed connection for 12MB request exceeding 10MB limit";
  7041. } else {
  7042. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7043. response.find("Payload Too Large") != std::string::npos ||
  7044. response.find("400") != std::string::npos);
  7045. }
  7046. }
  7047. }
  7048. TEST(HostAndPortPropertiesTest, NoSSL) {
  7049. httplib::Client cli("www.google.com", 1234);
  7050. ASSERT_EQ("www.google.com", cli.host());
  7051. ASSERT_EQ(1234, cli.port());
  7052. }
  7053. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7054. httplib::Client cli("www.google.com:1234");
  7055. ASSERT_EQ("www.google.com", cli.host());
  7056. ASSERT_EQ(1234, cli.port());
  7057. }
  7058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7059. TEST(HostAndPortPropertiesTest, SSL) {
  7060. httplib::SSLClient cli("www.google.com");
  7061. ASSERT_EQ("www.google.com", cli.host());
  7062. ASSERT_EQ(443, cli.port());
  7063. }
  7064. #endif
  7065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7066. TEST(SSLClientTest, UpdateCAStore) {
  7067. httplib::SSLClient httplib_client("www.google.com");
  7068. auto ca_store_1 = X509_STORE_new();
  7069. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7070. nullptr);
  7071. httplib_client.set_ca_cert_store(ca_store_1);
  7072. auto ca_store_2 = X509_STORE_new();
  7073. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7074. nullptr);
  7075. httplib_client.set_ca_cert_store(ca_store_2);
  7076. }
  7077. TEST(SSLClientTest, ServerNameIndication_Online) {
  7078. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7079. auto host = "httpbin.org";
  7080. auto path = std::string{"/get"};
  7081. #else
  7082. auto host = "nghttp2.org";
  7083. auto path = std::string{"/httpbin/get"};
  7084. #endif
  7085. SSLClient cli(host, 443);
  7086. auto res = cli.Get(path);
  7087. ASSERT_TRUE(res);
  7088. ASSERT_EQ(StatusCode::OK_200, res->status);
  7089. }
  7090. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7091. // Use a site that will cause SSL verification failure due to self-signed cert
  7092. SSLClient cli("self-signed.badssl.com", 443);
  7093. cli.enable_server_certificate_verification(true);
  7094. auto res = cli.Get("/");
  7095. ASSERT_TRUE(!res);
  7096. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7097. // For SSL server verification errors, ssl_error should be 0, only
  7098. // ssl_openssl_error should be set
  7099. EXPECT_EQ(0, res.ssl_error());
  7100. // Verify OpenSSL error is captured for SSLServerVerification
  7101. // This occurs when SSL_get_verify_result() returns a verification failure
  7102. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7103. res.ssl_openssl_error());
  7104. }
  7105. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7106. // Use a site where hostname doesn't match the certificate
  7107. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7108. SSLClient cli("wrong.host.badssl.com", 443);
  7109. cli.enable_server_certificate_verification(true);
  7110. cli.enable_server_hostname_verification(true);
  7111. auto res = cli.Get("/");
  7112. ASSERT_TRUE(!res);
  7113. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7114. // For SSL hostname verification errors, ssl_error should be 0, only
  7115. // ssl_openssl_error should be set
  7116. EXPECT_EQ(0, res.ssl_error());
  7117. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7118. // This occurs when verify_host() fails due to hostname mismatch
  7119. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7120. res.ssl_openssl_error());
  7121. }
  7122. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7123. Client cli("https://google.com");
  7124. auto res = cli.Get("/");
  7125. ASSERT_TRUE(res);
  7126. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7127. }
  7128. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7129. SSLClient cli("google.com");
  7130. cli.set_ca_cert_path(CA_CERT_FILE);
  7131. auto res = cli.Get("/");
  7132. ASSERT_TRUE(res);
  7133. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7134. }
  7135. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7136. SSLClient cli("google.com");
  7137. cli.enable_server_certificate_verification(true);
  7138. cli.set_ca_cert_path("hello");
  7139. auto res = cli.Get("/");
  7140. ASSERT_TRUE(!res);
  7141. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7142. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7143. // should be set
  7144. EXPECT_EQ(0, res.ssl_error());
  7145. // Verify OpenSSL error is captured for SSLLoadingCerts
  7146. // This error occurs when SSL_CTX_load_verify_locations() fails
  7147. // > openssl errstr 0x80000002
  7148. // error:80000002:system library::No such file or directory
  7149. // > openssl errstr 0xA000126
  7150. // error:0A000126:SSL routines::unexpected eof while reading
  7151. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7152. res.ssl_openssl_error() == 0xA000126);
  7153. }
  7154. TEST(SSLClientTest, ServerCertificateVerification4) {
  7155. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7156. ASSERT_TRUE(svr.is_valid());
  7157. svr.Get("/test", [&](const Request &, Response &res) {
  7158. res.set_content("test", "text/plain");
  7159. svr.stop();
  7160. ASSERT_TRUE(true);
  7161. });
  7162. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7163. auto se = detail::scope_exit([&] {
  7164. t.join();
  7165. ASSERT_FALSE(svr.is_running());
  7166. });
  7167. svr.wait_until_ready();
  7168. SSLClient cli("127.0.0.1", PORT);
  7169. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7170. cli.enable_server_certificate_verification(true);
  7171. cli.set_connection_timeout(30);
  7172. auto res = cli.Get("/test");
  7173. ASSERT_TRUE(res);
  7174. ASSERT_EQ(StatusCode::OK_200, res->status);
  7175. }
  7176. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7177. std::string cert;
  7178. read_file(CA_CERT_FILE, cert);
  7179. SSLClient cli("google.com");
  7180. cli.load_ca_cert_store(cert.data(), cert.size());
  7181. const auto res = cli.Get("/");
  7182. ASSERT_TRUE(res);
  7183. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7184. }
  7185. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7186. // clang-format off
  7187. static constexpr char cert[] =
  7188. "GlobalSign Root CA\n"
  7189. "==================\n"
  7190. "-----BEGIN CERTIFICATE-----\n"
  7191. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7192. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7193. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7194. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7195. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7196. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7197. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7198. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7199. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7200. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7201. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7202. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7203. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7204. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7205. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7206. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7207. "-----END CERTIFICATE-----\n";
  7208. // clang-format on
  7209. SSLClient cli("google.com");
  7210. cli.load_ca_cert_store(cert, sizeof(cert));
  7211. const auto res = cli.Get("/");
  7212. ASSERT_TRUE(res);
  7213. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7214. }
  7215. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7216. SSLClient cli("www.youtube.com");
  7217. cli.set_ca_cert_path(CA_CERT_FILE);
  7218. cli.enable_server_certificate_verification(true);
  7219. cli.set_follow_location(true);
  7220. auto res = cli.Get("/");
  7221. ASSERT_TRUE(res);
  7222. ASSERT_EQ(StatusCode::OK_200, res->status);
  7223. }
  7224. TEST(SSLClientTest, Issue2004_Online) {
  7225. Client client("https://google.com");
  7226. client.set_follow_location(true);
  7227. auto res = client.Get("/");
  7228. ASSERT_TRUE(res);
  7229. ASSERT_EQ(StatusCode::OK_200, res->status);
  7230. auto body = res->body;
  7231. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7232. }
  7233. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7234. // Create SSLClient with invalid cert/key to make is_valid() return false
  7235. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7236. "nonexistent_key.pem");
  7237. // is_valid() should be false due to cert loading failure
  7238. ASSERT_FALSE(cli.is_valid());
  7239. auto res = cli.Get("/");
  7240. ASSERT_FALSE(res);
  7241. EXPECT_EQ(Error::SSLConnection, res.error());
  7242. }
  7243. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7244. // Test for Issue #2251: SSL error not properly reported when client cert
  7245. // and key paths are swapped or mismatched
  7246. // This simulates the scenario where user accidentally swaps the cert and key
  7247. // files
  7248. // Using client cert file as private key and vice versa (completely wrong)
  7249. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7250. // Should fail validation due to cert/key mismatch
  7251. ASSERT_FALSE(cli.is_valid());
  7252. // Attempt to make a request should fail with proper error
  7253. auto res = cli.Get("/");
  7254. ASSERT_FALSE(res);
  7255. EXPECT_EQ(Error::SSLConnection, res.error());
  7256. // SSL error should be recorded in the Result object (this is the key fix for
  7257. // Issue #2251)
  7258. auto openssl_error = res.ssl_openssl_error();
  7259. EXPECT_NE(0u, openssl_error);
  7260. }
  7261. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7262. // Another variant: using valid file paths but with mismatched cert/key pair
  7263. // This tests the case where files exist but contain incompatible key material
  7264. // Using client cert with wrong key (cert2 key)
  7265. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7266. // Should fail validation
  7267. ASSERT_FALSE(cli.is_valid());
  7268. auto res = cli.Get("/");
  7269. ASSERT_FALSE(res);
  7270. // Must report error properly, not appear as success
  7271. EXPECT_EQ(Error::SSLConnection, res.error());
  7272. // OpenSSL error should be captured in Result
  7273. EXPECT_NE(0u, res.ssl_openssl_error());
  7274. }
  7275. #if 0
  7276. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7277. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7278. ASSERT_TRUE(cli != nullptr);
  7279. cli->set_address_family(AF_INET6);
  7280. cli->set_interface("en0");
  7281. auto res = cli->Get("/get");
  7282. ASSERT_TRUE(res);
  7283. ASSERT_EQ(StatusCode::OK_200, res->status);
  7284. }
  7285. #endif
  7286. void ClientCertPresent(
  7287. const std::string &client_cert_file,
  7288. const std::string &client_private_key_file,
  7289. const std::string &client_encrypted_private_key_pass = std::string()) {
  7290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7291. CLIENT_CA_CERT_DIR);
  7292. ASSERT_TRUE(svr.is_valid());
  7293. svr.Get("/test", [&](const Request &req, Response &res) {
  7294. res.set_content("test", "text/plain");
  7295. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7296. ASSERT_TRUE(peer_cert != nullptr);
  7297. auto subject_name = X509_get_subject_name(peer_cert);
  7298. ASSERT_TRUE(subject_name != nullptr);
  7299. std::string common_name;
  7300. {
  7301. char name[BUFSIZ];
  7302. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7303. name, sizeof(name));
  7304. common_name.assign(name, static_cast<size_t>(name_len));
  7305. }
  7306. EXPECT_EQ("Common Name", common_name);
  7307. X509_free(peer_cert);
  7308. });
  7309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7310. auto se = detail::scope_exit([&] {
  7311. svr.stop();
  7312. t.join();
  7313. ASSERT_FALSE(svr.is_running());
  7314. });
  7315. svr.wait_until_ready();
  7316. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7317. client_encrypted_private_key_pass);
  7318. cli.enable_server_certificate_verification(false);
  7319. cli.set_connection_timeout(30);
  7320. auto res = cli.Get("/test");
  7321. ASSERT_TRUE(res);
  7322. ASSERT_EQ(StatusCode::OK_200, res->status);
  7323. }
  7324. TEST(SSLClientServerTest, ClientCertPresent) {
  7325. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7326. }
  7327. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7328. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7329. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7330. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7331. }
  7332. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7333. void MemoryClientCertPresent(
  7334. const std::string &client_cert_file,
  7335. const std::string &client_private_key_file,
  7336. const std::string &client_encrypted_private_key_pass = std::string()) {
  7337. auto f = fopen(SERVER_CERT_FILE, "r+");
  7338. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7339. fclose(f);
  7340. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7341. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7342. fclose(f);
  7343. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7344. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7345. auto client_ca_cert_store = X509_STORE_new();
  7346. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7347. X509_free(client_cert);
  7348. fclose(f);
  7349. f = fopen(client_cert_file.c_str(), "r+");
  7350. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7351. fclose(f);
  7352. f = fopen(client_private_key_file.c_str(), "r+");
  7353. auto client_private_key = PEM_read_PrivateKey(
  7354. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7355. fclose(f);
  7356. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7357. ASSERT_TRUE(svr.is_valid());
  7358. svr.Get("/test", [&](const Request &req, Response &res) {
  7359. res.set_content("test", "text/plain");
  7360. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7361. ASSERT_TRUE(peer_cert != nullptr);
  7362. auto subject_name = X509_get_subject_name(peer_cert);
  7363. ASSERT_TRUE(subject_name != nullptr);
  7364. std::string common_name;
  7365. {
  7366. char name[BUFSIZ];
  7367. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7368. name, sizeof(name));
  7369. common_name.assign(name, static_cast<size_t>(name_len));
  7370. }
  7371. EXPECT_EQ("Common Name", common_name);
  7372. X509_free(peer_cert);
  7373. });
  7374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7382. client_encrypted_private_key_pass);
  7383. cli.enable_server_certificate_verification(false);
  7384. cli.set_connection_timeout(30);
  7385. auto res = cli.Get("/test");
  7386. ASSERT_TRUE(res);
  7387. ASSERT_EQ(StatusCode::OK_200, res->status);
  7388. X509_free(server_cert);
  7389. EVP_PKEY_free(server_private_key);
  7390. X509_free(client_cert);
  7391. EVP_PKEY_free(client_private_key);
  7392. }
  7393. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7394. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7395. }
  7396. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7397. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7398. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7399. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7400. }
  7401. #endif
  7402. TEST(SSLClientServerTest, ClientCertMissing) {
  7403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7404. CLIENT_CA_CERT_DIR);
  7405. ASSERT_TRUE(svr.is_valid());
  7406. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7408. auto se = detail::scope_exit([&] {
  7409. svr.stop();
  7410. t.join();
  7411. ASSERT_FALSE(svr.is_running());
  7412. });
  7413. svr.wait_until_ready();
  7414. SSLClient cli(HOST, PORT);
  7415. cli.set_connection_timeout(30);
  7416. auto res = cli.Get("/test");
  7417. ASSERT_TRUE(!res);
  7418. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7419. // For SSL server verification errors, ssl_error should be 0, only
  7420. // ssl_openssl_error should be set
  7421. EXPECT_EQ(0, res.ssl_error());
  7422. // Verify OpenSSL error is captured for SSLServerVerification
  7423. // Note: This test may have different error codes depending on the exact
  7424. // verification failure
  7425. EXPECT_NE(0UL, res.ssl_openssl_error());
  7426. }
  7427. TEST(SSLClientServerTest, TrustDirOptional) {
  7428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7429. ASSERT_TRUE(svr.is_valid());
  7430. svr.Get("/test", [&](const Request &, Response &res) {
  7431. res.set_content("test", "text/plain");
  7432. });
  7433. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7434. auto se = detail::scope_exit([&] {
  7435. svr.stop();
  7436. t.join();
  7437. ASSERT_FALSE(svr.is_running());
  7438. });
  7439. svr.wait_until_ready();
  7440. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7441. cli.enable_server_certificate_verification(false);
  7442. cli.set_connection_timeout(30);
  7443. auto res = cli.Get("/test");
  7444. ASSERT_TRUE(res);
  7445. ASSERT_EQ(StatusCode::OK_200, res->status);
  7446. }
  7447. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7448. class NoListenSSLServer : public SSLServer {
  7449. public:
  7450. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7451. const char *client_ca_cert_file_path,
  7452. const char *client_ca_cert_dir_path = nullptr)
  7453. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7454. client_ca_cert_dir_path),
  7455. stop_(false) {}
  7456. std::atomic_bool stop_;
  7457. private:
  7458. bool process_and_close_socket(socket_t /*sock*/) override {
  7459. // Don't create SSL context
  7460. while (!stop_.load()) {
  7461. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7462. }
  7463. return true;
  7464. }
  7465. };
  7466. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7467. CLIENT_CA_CERT_FILE);
  7468. ASSERT_TRUE(svr.is_valid());
  7469. svr.Get("/test", [&](const Request &, Response &res) {
  7470. res.set_content("test", "text/plain");
  7471. });
  7472. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7473. auto se = detail::scope_exit([&] {
  7474. svr.stop_ = true;
  7475. svr.stop();
  7476. t.join();
  7477. ASSERT_FALSE(svr.is_running());
  7478. });
  7479. svr.wait_until_ready();
  7480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7481. cli.enable_server_certificate_verification(false);
  7482. cli.set_connection_timeout(1);
  7483. auto res = cli.Get("/test");
  7484. ASSERT_TRUE(!res);
  7485. EXPECT_EQ(Error::SSLConnection, res.error());
  7486. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7487. }
  7488. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7489. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7490. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7491. SSL_CTX_set_options(&ssl_ctx,
  7492. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7493. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7494. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7495. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7496. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7497. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7498. "ECDHE-DSS-AES128-SHA256:"
  7499. "ECDHE-RSA-AES256-SHA256:"
  7500. "ECDHE-DSS-AES256-SHA256:";
  7501. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7502. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7503. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7504. SSL_FILETYPE_PEM) != 1) {
  7505. return false;
  7506. }
  7507. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7508. CLIENT_CA_CERT_DIR);
  7509. SSL_CTX_set_verify(
  7510. &ssl_ctx,
  7511. SSL_VERIFY_PEER |
  7512. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7513. nullptr);
  7514. return true;
  7515. };
  7516. SSLServer svr(setup_ssl_ctx_callback);
  7517. ASSERT_TRUE(svr.is_valid());
  7518. svr.Get("/test", [&](const Request &req, Response &res) {
  7519. res.set_content("test", "text/plain");
  7520. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7521. ASSERT_TRUE(peer_cert != nullptr);
  7522. auto subject_name = X509_get_subject_name(peer_cert);
  7523. ASSERT_TRUE(subject_name != nullptr);
  7524. std::string common_name;
  7525. {
  7526. char name[BUFSIZ];
  7527. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7528. name, sizeof(name));
  7529. common_name.assign(name, static_cast<size_t>(name_len));
  7530. }
  7531. EXPECT_EQ("Common Name", common_name);
  7532. X509_free(peer_cert);
  7533. });
  7534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7535. auto se = detail::scope_exit([&] {
  7536. svr.stop();
  7537. t.join();
  7538. ASSERT_FALSE(svr.is_running());
  7539. });
  7540. svr.wait_until_ready();
  7541. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7542. cli.enable_server_certificate_verification(false);
  7543. cli.set_connection_timeout(30);
  7544. auto res = cli.Get("/test");
  7545. ASSERT_TRUE(res);
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. }
  7548. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7550. ASSERT_TRUE(svr.is_valid());
  7551. // Set up a handler to verify client certificate is present
  7552. bool client_cert_verified = false;
  7553. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7554. // Verify that client certificate was provided
  7555. client_cert_verified = true;
  7556. res.set_content("success", "text/plain");
  7557. });
  7558. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7559. auto se = detail::scope_exit([&] {
  7560. svr.stop();
  7561. t.join();
  7562. ASSERT_FALSE(svr.is_running());
  7563. });
  7564. svr.wait_until_ready();
  7565. // Client with certificate
  7566. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7567. cli.enable_server_certificate_verification(false);
  7568. cli.set_connection_timeout(30);
  7569. auto res = cli.Get("/test");
  7570. ASSERT_TRUE(res);
  7571. ASSERT_EQ(StatusCode::OK_200, res->status);
  7572. ASSERT_TRUE(client_cert_verified);
  7573. EXPECT_EQ("success", res->body);
  7574. }
  7575. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7576. // Test that when client CA cert file is provided,
  7577. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7578. // Create a server with client authentication
  7579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7580. ASSERT_TRUE(svr.is_valid());
  7581. // We can't directly access the SSL_CTX from SSLServer to verify,
  7582. // but we can test that the server properly requests client certificates
  7583. // and accepts valid ones from the specified CA
  7584. bool handler_called = false;
  7585. svr.Get("/test", [&](const Request &req, Response &res) {
  7586. handler_called = true;
  7587. // Verify that a client certificate was provided
  7588. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7589. ASSERT_TRUE(peer_cert != nullptr);
  7590. // Get the issuer name
  7591. auto issuer_name = X509_get_issuer_name(peer_cert);
  7592. ASSERT_TRUE(issuer_name != nullptr);
  7593. char issuer_buf[256];
  7594. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7595. // The client certificate should be issued by our test CA
  7596. std::string issuer_str(issuer_buf);
  7597. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7598. X509_free(peer_cert);
  7599. res.set_content("authenticated", "text/plain");
  7600. });
  7601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7602. auto se = detail::scope_exit([&] {
  7603. svr.stop();
  7604. t.join();
  7605. ASSERT_FALSE(svr.is_running());
  7606. });
  7607. svr.wait_until_ready();
  7608. // Connect with a client certificate issued by the CA
  7609. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7610. cli.enable_server_certificate_verification(false);
  7611. cli.set_connection_timeout(30);
  7612. auto res = cli.Get("/test");
  7613. ASSERT_TRUE(res);
  7614. ASSERT_EQ(StatusCode::OK_200, res->status);
  7615. ASSERT_TRUE(handler_called);
  7616. EXPECT_EQ("authenticated", res->body);
  7617. }
  7618. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7619. // Test 1: Valid CA file - no error should be recorded
  7620. {
  7621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7622. CLIENT_CA_CERT_FILE);
  7623. ASSERT_TRUE(svr.is_valid());
  7624. // With valid setup, last_ssl_error should be 0
  7625. EXPECT_EQ(0, svr.ssl_last_error());
  7626. }
  7627. // Test 2: Invalid CA file content
  7628. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7629. {
  7630. // Create a temporary file with completely invalid content
  7631. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7632. {
  7633. std::ofstream ofs(temp_invalid_ca);
  7634. ofs << "This is not a certificate file at all\n";
  7635. ofs << "Just plain text content\n";
  7636. }
  7637. // Create server with invalid CA file
  7638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7639. // Clean up temporary file
  7640. std::remove(temp_invalid_ca);
  7641. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7642. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7643. // Note: SSL_CTX_load_verify_locations typically fails first,
  7644. // but our error handling code path is still exercised
  7645. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7646. }
  7647. }
  7648. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7649. // Test SSL server using X509_STORE constructor with client CA certificates
  7650. // This test verifies that Phase 2 implementation correctly extracts CA names
  7651. // from an X509_STORE and sets them in the SSL context
  7652. // Load the CA certificate into memory
  7653. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7654. ASSERT_NE(nullptr, bio);
  7655. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7656. BIO_free(bio);
  7657. ASSERT_NE(nullptr, ca_cert);
  7658. // Create an X509_STORE and add the CA certificate
  7659. auto store = X509_STORE_new();
  7660. ASSERT_NE(nullptr, store);
  7661. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7662. // Load server certificate and private key
  7663. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7664. ASSERT_NE(nullptr, cert_bio);
  7665. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7666. BIO_free(cert_bio);
  7667. ASSERT_NE(nullptr, server_cert);
  7668. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7669. ASSERT_NE(nullptr, key_bio);
  7670. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7671. BIO_free(key_bio);
  7672. ASSERT_NE(nullptr, server_key);
  7673. // Create SSLServer with X509_STORE constructor
  7674. // Note: X509_STORE ownership is transferred to SSL_CTX
  7675. SSLServer svr(server_cert, server_key, store);
  7676. ASSERT_TRUE(svr.is_valid());
  7677. // No SSL error should be recorded for valid setup
  7678. EXPECT_EQ(0, svr.ssl_last_error());
  7679. // Set up server endpoints
  7680. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7681. res.set_content("ok", "text/plain");
  7682. });
  7683. // Start server in a thread
  7684. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7685. svr.wait_until_ready();
  7686. // Connect with client certificate (using constructor with paths)
  7687. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7688. cli.enable_server_certificate_verification(false);
  7689. auto res = cli.Get("/test-x509store");
  7690. ASSERT_TRUE(res);
  7691. EXPECT_EQ(200, res->status);
  7692. EXPECT_EQ("ok", res->body);
  7693. // Clean up
  7694. X509_free(server_cert);
  7695. EVP_PKEY_free(server_key);
  7696. X509_free(ca_cert);
  7697. svr.stop();
  7698. server_thread.join();
  7699. }
  7700. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7701. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7702. // prepare large data
  7703. std::random_device seed_gen;
  7704. std::mt19937 random(seed_gen());
  7705. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7706. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7707. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7708. // server
  7709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7710. ASSERT_TRUE(svr.is_valid());
  7711. svr.Post("/binary", [&](const Request &req, Response &res) {
  7712. EXPECT_EQ(large_size_byte, req.body.size());
  7713. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7714. res.set_content(req.body, "application/octet-stream");
  7715. });
  7716. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7717. auto se = detail::scope_exit([&] {
  7718. svr.stop();
  7719. listen_thread.join();
  7720. ASSERT_FALSE(svr.is_running());
  7721. });
  7722. svr.wait_until_ready();
  7723. // client POST
  7724. SSLClient cli("localhost", PORT);
  7725. cli.enable_server_certificate_verification(false);
  7726. cli.set_read_timeout(std::chrono::seconds(100));
  7727. cli.set_write_timeout(std::chrono::seconds(100));
  7728. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7729. large_size_byte, "application/octet-stream");
  7730. // compare
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ(large_size_byte, res->body.size());
  7733. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7734. }
  7735. #endif
  7736. #ifdef _WIN32
  7737. TEST(CleanupTest, WSACleanup) {
  7738. int ret = WSACleanup();
  7739. ASSERT_EQ(0, ret);
  7740. }
  7741. #endif
  7742. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7743. TEST(NoSSLSupport, SimpleInterface) {
  7744. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7745. }
  7746. #endif
  7747. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7748. TEST(InvalidScheme, SimpleInterface) {
  7749. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7750. }
  7751. #endif
  7752. TEST(NoScheme, SimpleInterface) {
  7753. Client cli("yahoo.com:80");
  7754. ASSERT_TRUE(cli.is_valid());
  7755. }
  7756. TEST(SendAPI, SimpleInterface_Online) {
  7757. Client cli("http://yahoo.com");
  7758. Request req;
  7759. req.method = "GET";
  7760. req.path = "/";
  7761. auto res = cli.send(req);
  7762. ASSERT_TRUE(res);
  7763. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7764. }
  7765. TEST(SendAPI, WithParamsInRequest) {
  7766. Server svr;
  7767. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7768. EXPECT_TRUE(req.has_param("test"));
  7769. EXPECT_EQ("test_value", req.get_param_value("test"));
  7770. });
  7771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7772. auto se = detail::scope_exit([&] {
  7773. svr.stop();
  7774. t.join();
  7775. ASSERT_FALSE(svr.is_running());
  7776. });
  7777. svr.wait_until_ready();
  7778. Client cli(HOST, PORT);
  7779. {
  7780. Request req;
  7781. req.method = "GET";
  7782. req.path = "/";
  7783. req.params.emplace("test", "test_value");
  7784. auto res = cli.send(req);
  7785. ASSERT_TRUE(res);
  7786. }
  7787. {
  7788. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7789. ASSERT_TRUE(res);
  7790. }
  7791. }
  7792. TEST(ClientImplMethods, GetSocketTest) {
  7793. httplib::Server svr;
  7794. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7795. res.status = StatusCode::OK_200;
  7796. });
  7797. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. thread.join();
  7801. ASSERT_FALSE(svr.is_running());
  7802. });
  7803. svr.wait_until_ready();
  7804. {
  7805. httplib::Client cli("http://127.0.0.1:3333");
  7806. cli.set_keep_alive(true);
  7807. // Use the behavior of cpp-httplib of opening the connection
  7808. // only when the first request happens. If that changes,
  7809. // this test would be obsolete.
  7810. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7811. // This also implicitly tests the server. But other tests would fail much
  7812. // earlier than this one to be considered.
  7813. auto res = cli.Get("/");
  7814. ASSERT_TRUE(res);
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7817. }
  7818. }
  7819. // Disabled due to out-of-memory problem on GitHub Actions
  7820. #ifdef _WIN64
  7821. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7822. // allocate content size larger than 2GB in memory
  7823. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7824. char *content = (char *)malloc(content_size);
  7825. ASSERT_TRUE(content);
  7826. Server svr;
  7827. svr.Get("/foo",
  7828. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7829. res.set_content(content, content_size, "application/octet-stream");
  7830. });
  7831. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7832. auto se = detail::scope_exit([&] {
  7833. svr.stop();
  7834. listen_thread.join();
  7835. if (content) free(content);
  7836. ASSERT_FALSE(svr.is_running());
  7837. });
  7838. svr.wait_until_ready();
  7839. Client cli(HOST, PORT);
  7840. auto res = cli.Get("/foo");
  7841. ASSERT_TRUE(res);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. EXPECT_EQ(content_size, res->body.length());
  7844. }
  7845. #endif
  7846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7847. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7848. Client cli("http://yahoo.com");
  7849. auto res = cli.Get("/");
  7850. ASSERT_TRUE(res);
  7851. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7852. cli.set_follow_location(true);
  7853. res = cli.Get("/");
  7854. ASSERT_TRUE(res);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7857. }
  7858. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7859. Client cli("https://yahoo.com");
  7860. auto res = cli.Get("/");
  7861. ASSERT_TRUE(res);
  7862. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7863. cli.set_follow_location(true);
  7864. res = cli.Get("/");
  7865. ASSERT_TRUE(res);
  7866. EXPECT_EQ(StatusCode::OK_200, res->status);
  7867. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7868. }
  7869. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7870. Client cli("https://yahoo.com");
  7871. auto res = cli.Get("/");
  7872. ASSERT_TRUE(res);
  7873. ASSERT_FALSE(!res);
  7874. ASSERT_TRUE(res);
  7875. ASSERT_FALSE(res == nullptr);
  7876. ASSERT_TRUE(res != nullptr);
  7877. EXPECT_EQ(Error::Success, res.error());
  7878. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7879. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7880. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7881. cli.set_follow_location(true);
  7882. res = cli.Get("/");
  7883. ASSERT_TRUE(res);
  7884. EXPECT_EQ(Error::Success, res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7886. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7889. }
  7890. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7891. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7892. Client cli("https://cdnjs.cloudflare.com");
  7893. auto res =
  7894. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7895. ASSERT_TRUE(res);
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ(287630U, res->body.size());
  7898. EXPECT_EQ("application/javascript; charset=utf-8",
  7899. res->get_header_value("Content-Type"));
  7900. }
  7901. #endif
  7902. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7903. #undef REDIR_HOST // Silence compiler warning
  7904. #define REDIR_HOST "https://httpbingo.org"
  7905. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7906. Client cli(REDIR_HOST);
  7907. cli.set_follow_location(true);
  7908. auto res =
  7909. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7910. ASSERT_TRUE(res);
  7911. EXPECT_EQ(StatusCode::OK_200, res->status);
  7912. }
  7913. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7914. Client cli(REDIR_HOST);
  7915. cli.set_follow_location(true);
  7916. Params params;
  7917. params.emplace("url", "http://example.com");
  7918. params.emplace("status_code", "302");
  7919. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. }
  7923. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7924. Client cli(REDIR_HOST);
  7925. cli.set_follow_location(true);
  7926. Params params;
  7927. params.emplace("url", "http://example.com");
  7928. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7929. ASSERT_TRUE(res);
  7930. EXPECT_EQ(StatusCode::OK_200, res->status);
  7931. }
  7932. TEST(HttpToHttpsRedirectTest, CertFile) {
  7933. Server svr;
  7934. ASSERT_TRUE(svr.is_valid());
  7935. svr.Get("/index", [&](const Request &, Response &res) {
  7936. res.set_redirect("https://127.0.0.1:1235/index");
  7937. svr.stop();
  7938. });
  7939. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7940. ASSERT_TRUE(ssl_svr.is_valid());
  7941. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7942. res.set_content("test", "text/plain");
  7943. ssl_svr.stop();
  7944. });
  7945. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7946. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7947. auto se = detail::scope_exit([&] {
  7948. t2.join();
  7949. t.join();
  7950. ASSERT_FALSE(svr.is_running());
  7951. });
  7952. svr.wait_until_ready();
  7953. ssl_svr.wait_until_ready();
  7954. Client cli("127.0.0.1", PORT);
  7955. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7956. cli.enable_server_certificate_verification(true);
  7957. cli.set_follow_location(true);
  7958. cli.set_connection_timeout(30);
  7959. auto res = cli.Get("/index");
  7960. ASSERT_TRUE(res);
  7961. ASSERT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST(SSLClientRedirectTest, CertFile) {
  7964. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7965. ASSERT_TRUE(ssl_svr1.is_valid());
  7966. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7967. res.set_redirect("https://127.0.0.1:1235/index");
  7968. ssl_svr1.stop();
  7969. });
  7970. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7971. ASSERT_TRUE(ssl_svr2.is_valid());
  7972. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7973. res.set_content("test", "text/plain");
  7974. ssl_svr2.stop();
  7975. });
  7976. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7977. thread t2 =
  7978. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7979. auto se = detail::scope_exit([&] {
  7980. t2.join();
  7981. t.join();
  7982. ASSERT_FALSE(ssl_svr1.is_running());
  7983. });
  7984. ssl_svr1.wait_until_ready();
  7985. ssl_svr2.wait_until_ready();
  7986. SSLClient cli("127.0.0.1", PORT);
  7987. std::string cert;
  7988. read_file(SERVER_CERT2_FILE, cert);
  7989. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7990. cli.enable_server_certificate_verification(true);
  7991. cli.set_follow_location(true);
  7992. cli.set_connection_timeout(30);
  7993. auto res = cli.Get("/index");
  7994. ASSERT_TRUE(res);
  7995. ASSERT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. TEST(MultipartFormDataTest, LargeData) {
  7998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7999. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8000. const ContentReader &content_reader) {
  8001. if (req.is_multipart_form_data()) {
  8002. std::vector<FormData> items;
  8003. content_reader(
  8004. [&](const FormData &file) {
  8005. items.push_back(file);
  8006. return true;
  8007. },
  8008. [&](const char *data, size_t data_length) {
  8009. items.back().content.append(data, data_length);
  8010. return true;
  8011. });
  8012. EXPECT_TRUE(std::string(items[0].name) == "document");
  8013. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8014. EXPECT_TRUE(items[0].filename == "2MB_data");
  8015. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8016. EXPECT_TRUE(items[1].name == "hello");
  8017. EXPECT_TRUE(items[1].content == "world");
  8018. EXPECT_TRUE(items[1].filename == "");
  8019. EXPECT_TRUE(items[1].content_type == "");
  8020. } else {
  8021. std::string body;
  8022. content_reader([&](const char *data, size_t data_length) {
  8023. body.append(data, data_length);
  8024. return true;
  8025. });
  8026. }
  8027. });
  8028. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8029. auto se = detail::scope_exit([&] {
  8030. svr.stop();
  8031. t.join();
  8032. ASSERT_FALSE(svr.is_running());
  8033. });
  8034. svr.wait_until_ready();
  8035. {
  8036. std::string data(1024 * 1024 * 2, '.');
  8037. std::stringstream buffer;
  8038. buffer << data;
  8039. Client cli("https://localhost:8080");
  8040. cli.enable_server_certificate_verification(false);
  8041. UploadFormDataItems items{
  8042. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8043. {"hello", "world", "", ""},
  8044. };
  8045. auto res = cli.Post("/post", items);
  8046. ASSERT_TRUE(res);
  8047. ASSERT_EQ(StatusCode::OK_200, res->status);
  8048. }
  8049. }
  8050. TEST(MultipartFormDataTest, DataProviderItems) {
  8051. std::random_device seed_gen;
  8052. std::mt19937 random(seed_gen());
  8053. std::string rand1;
  8054. rand1.resize(1000);
  8055. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8056. std::string rand2;
  8057. rand2.resize(3000);
  8058. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8060. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8061. const ContentReader &content_reader) {
  8062. ASSERT_FALSE(req.is_multipart_form_data());
  8063. std::string body;
  8064. content_reader([&](const char *data, size_t data_length) {
  8065. body.append(data, data_length);
  8066. return true;
  8067. });
  8068. EXPECT_EQ(body, "");
  8069. });
  8070. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8071. const ContentReader &content_reader) {
  8072. ASSERT_TRUE(req.is_multipart_form_data());
  8073. std::vector<FormData> items;
  8074. content_reader(
  8075. [&](const FormData &file) {
  8076. items.push_back(file);
  8077. return true;
  8078. },
  8079. [&](const char *data, size_t data_length) {
  8080. items.back().content.append(data, data_length);
  8081. return true;
  8082. });
  8083. ASSERT_TRUE(items.size() == 2);
  8084. EXPECT_EQ(std::string(items[0].name), "name1");
  8085. EXPECT_EQ(items[0].content, "Testing123");
  8086. EXPECT_EQ(items[0].filename, "filename1");
  8087. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8088. EXPECT_EQ(items[1].name, "name2");
  8089. EXPECT_EQ(items[1].content, "Testing456");
  8090. EXPECT_EQ(items[1].filename, "");
  8091. EXPECT_EQ(items[1].content_type, "");
  8092. });
  8093. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8094. const ContentReader &content_reader) {
  8095. ASSERT_TRUE(req.is_multipart_form_data());
  8096. std::vector<FormData> items;
  8097. content_reader(
  8098. [&](const FormData &file) {
  8099. items.push_back(file);
  8100. return true;
  8101. },
  8102. [&](const char *data, size_t data_length) {
  8103. items.back().content.append(data, data_length);
  8104. return true;
  8105. });
  8106. ASSERT_TRUE(items.size() == 2);
  8107. EXPECT_EQ(items[0].name, "name3");
  8108. EXPECT_EQ(items[0].content, rand1);
  8109. EXPECT_EQ(items[0].filename, "filename3");
  8110. EXPECT_EQ(items[0].content_type, "");
  8111. EXPECT_EQ(items[1].name, "name4");
  8112. EXPECT_EQ(items[1].content, rand2);
  8113. EXPECT_EQ(items[1].filename, "filename4");
  8114. EXPECT_EQ(items[1].content_type, "");
  8115. });
  8116. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8117. const ContentReader &content_reader) {
  8118. ASSERT_TRUE(req.is_multipart_form_data());
  8119. std::vector<FormData> items;
  8120. content_reader(
  8121. [&](const FormData &file) {
  8122. items.push_back(file);
  8123. return true;
  8124. },
  8125. [&](const char *data, size_t data_length) {
  8126. items.back().content.append(data, data_length);
  8127. return true;
  8128. });
  8129. ASSERT_TRUE(items.size() == 4);
  8130. EXPECT_EQ(std::string(items[0].name), "name1");
  8131. EXPECT_EQ(items[0].content, "Testing123");
  8132. EXPECT_EQ(items[0].filename, "filename1");
  8133. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8134. EXPECT_EQ(items[1].name, "name2");
  8135. EXPECT_EQ(items[1].content, "Testing456");
  8136. EXPECT_EQ(items[1].filename, "");
  8137. EXPECT_EQ(items[1].content_type, "");
  8138. EXPECT_EQ(items[2].name, "name3");
  8139. EXPECT_EQ(items[2].content, rand1);
  8140. EXPECT_EQ(items[2].filename, "filename3");
  8141. EXPECT_EQ(items[2].content_type, "");
  8142. EXPECT_EQ(items[3].name, "name4");
  8143. EXPECT_EQ(items[3].content, rand2);
  8144. EXPECT_EQ(items[3].filename, "filename4");
  8145. EXPECT_EQ(items[3].content_type, "");
  8146. });
  8147. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8148. auto se = detail::scope_exit([&] {
  8149. svr.stop();
  8150. t.join();
  8151. ASSERT_FALSE(svr.is_running());
  8152. });
  8153. svr.wait_until_ready();
  8154. {
  8155. Client cli("https://localhost:8080");
  8156. cli.enable_server_certificate_verification(false);
  8157. UploadFormDataItems items{
  8158. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8159. {"name2", "Testing456", "", ""}, // not a file
  8160. };
  8161. {
  8162. auto res = cli.Post("/post-none", {}, {}, {});
  8163. ASSERT_TRUE(res);
  8164. ASSERT_EQ(StatusCode::OK_200, res->status);
  8165. }
  8166. FormDataProviderItems providers;
  8167. {
  8168. auto res =
  8169. cli.Post("/post-items", {}, items, providers); // empty providers
  8170. ASSERT_TRUE(res);
  8171. ASSERT_EQ(StatusCode::OK_200, res->status);
  8172. }
  8173. providers.push_back({"name3",
  8174. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8175. // test the offset is given correctly at each step
  8176. if (!offset)
  8177. sink.os.write(rand1.data(), 30);
  8178. else if (offset == 30)
  8179. sink.os.write(rand1.data() + 30, 300);
  8180. else if (offset == 330)
  8181. sink.os.write(rand1.data() + 330, 670);
  8182. else if (offset == rand1.size())
  8183. sink.done();
  8184. return true;
  8185. },
  8186. "filename3",
  8187. {}});
  8188. providers.push_back({"name4",
  8189. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8190. // test the offset is given correctly at each step
  8191. if (!offset)
  8192. sink.os.write(rand2.data(), 2000);
  8193. else if (offset == 2000)
  8194. sink.os.write(rand2.data() + 2000, 1);
  8195. else if (offset == 2001)
  8196. sink.os.write(rand2.data() + 2001, 999);
  8197. else if (offset == rand2.size())
  8198. sink.done();
  8199. return true;
  8200. },
  8201. "filename4",
  8202. {}});
  8203. {
  8204. auto res = cli.Post("/post-providers", {}, {}, providers);
  8205. ASSERT_TRUE(res);
  8206. ASSERT_EQ(StatusCode::OK_200, res->status);
  8207. }
  8208. {
  8209. auto res = cli.Post("/post-both", {}, items, providers);
  8210. ASSERT_TRUE(res);
  8211. ASSERT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. }
  8214. }
  8215. TEST(MultipartFormDataTest, BadHeader) {
  8216. Server svr;
  8217. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8218. res.set_content("ok", "text/plain");
  8219. });
  8220. thread t = thread([&] { svr.listen(HOST, PORT); });
  8221. auto se = detail::scope_exit([&] {
  8222. svr.stop();
  8223. t.join();
  8224. ASSERT_FALSE(svr.is_running());
  8225. });
  8226. svr.wait_until_ready();
  8227. const std::string body =
  8228. "This is the preamble. It is to be ignored, though it\r\n"
  8229. "is a handy place for composition agents to include an\r\n"
  8230. "explanatory note to non-MIME conformant readers.\r\n"
  8231. "\r\n"
  8232. "\r\n"
  8233. "--simple boundary\r\n"
  8234. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8235. ": BAD...\r\n"
  8236. "\r\n"
  8237. "value1\r\n"
  8238. "--simple boundary\r\n"
  8239. "Content-Disposition: form-data; name=\"field2\"; "
  8240. "filename=\"example.txt\"\r\n"
  8241. "\r\n"
  8242. "value2\r\n"
  8243. "--simple boundary--\r\n"
  8244. "This is the epilogue. It is also to be ignored.\r\n";
  8245. std::string content_type =
  8246. R"(multipart/form-data; boundary="simple boundary")";
  8247. Client cli(HOST, PORT);
  8248. auto res = cli.Post("/post", body, content_type.c_str());
  8249. ASSERT_TRUE(res);
  8250. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8251. }
  8252. TEST(MultipartFormDataTest, WithPreamble) {
  8253. Server svr;
  8254. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8255. res.set_content("ok", "text/plain");
  8256. });
  8257. thread t = thread([&] { svr.listen(HOST, PORT); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. t.join();
  8261. ASSERT_FALSE(svr.is_running());
  8262. });
  8263. svr.wait_until_ready();
  8264. const std::string body =
  8265. "This is the preamble. It is to be ignored, though it\r\n"
  8266. "is a handy place for composition agents to include an\r\n"
  8267. "explanatory note to non-MIME conformant readers.\r\n"
  8268. "\r\n"
  8269. "\r\n"
  8270. "--simple boundary\r\n"
  8271. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8272. "\r\n"
  8273. "value1\r\n"
  8274. "--simple boundary\r\n"
  8275. "Content-Disposition: form-data; name=\"field2\"; "
  8276. "filename=\"example.txt\"\r\n"
  8277. "\r\n"
  8278. "value2\r\n"
  8279. "--simple boundary--\r\n"
  8280. "This is the epilogue. It is also to be ignored.\r\n";
  8281. std::string content_type =
  8282. R"(multipart/form-data; boundary="simple boundary")";
  8283. Client cli(HOST, PORT);
  8284. auto res = cli.Post("/post", body, content_type.c_str());
  8285. ASSERT_TRUE(res);
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. }
  8288. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8290. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8291. const ContentReader &content_reader) {
  8292. if (req.is_multipart_form_data()) {
  8293. std::vector<FormData> items;
  8294. content_reader(
  8295. [&](const FormData &file) {
  8296. items.push_back(file);
  8297. return true;
  8298. },
  8299. [&](const char *data, size_t data_length) {
  8300. items.back().content.append(data, data_length);
  8301. return true;
  8302. });
  8303. EXPECT_TRUE(std::string(items[0].name) == "document");
  8304. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8305. EXPECT_TRUE(items[0].filename == "2MB_data");
  8306. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8307. EXPECT_TRUE(items[1].name == "hello");
  8308. EXPECT_TRUE(items[1].content == "world");
  8309. EXPECT_TRUE(items[1].filename == "");
  8310. EXPECT_TRUE(items[1].content_type == "");
  8311. } else {
  8312. std::string body;
  8313. content_reader([&](const char *data, size_t data_length) {
  8314. body.append(data, data_length);
  8315. return true;
  8316. });
  8317. }
  8318. });
  8319. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8320. auto se = detail::scope_exit([&] {
  8321. svr.stop();
  8322. t.join();
  8323. ASSERT_FALSE(svr.is_running());
  8324. });
  8325. svr.wait_until_ready();
  8326. {
  8327. std::string data(1024 * 1024 * 2, '.');
  8328. std::stringstream buffer;
  8329. buffer << data;
  8330. Client cli("https://localhost:8080");
  8331. cli.enable_server_certificate_verification(false);
  8332. UploadFormDataItems items{
  8333. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8334. {"hello", "world", "", ""},
  8335. };
  8336. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8337. ASSERT_TRUE(res);
  8338. ASSERT_EQ(StatusCode::OK_200, res->status);
  8339. }
  8340. }
  8341. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8342. std::string data(1024 * 1024 * 2, '&');
  8343. std::stringstream buffer;
  8344. buffer << data;
  8345. Client cli("https://localhost:8080");
  8346. UploadFormDataItems items{
  8347. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8348. {"hello", "world", "", ""},
  8349. };
  8350. for (const char &c : " \t\r\n") {
  8351. auto res =
  8352. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8353. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8354. ASSERT_FALSE(res);
  8355. }
  8356. }
  8357. TEST(MultipartFormDataTest, PutFormData) {
  8358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8359. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8360. const ContentReader &content_reader) {
  8361. if (req.is_multipart_form_data()) {
  8362. std::vector<FormData> items;
  8363. content_reader(
  8364. [&](const FormData &file) {
  8365. items.push_back(file);
  8366. return true;
  8367. },
  8368. [&](const char *data, size_t data_length) {
  8369. items.back().content.append(data, data_length);
  8370. return true;
  8371. });
  8372. EXPECT_TRUE(std::string(items[0].name) == "document");
  8373. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8374. EXPECT_TRUE(items[0].filename == "2MB_data");
  8375. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8376. EXPECT_TRUE(items[1].name == "hello");
  8377. EXPECT_TRUE(items[1].content == "world");
  8378. EXPECT_TRUE(items[1].filename == "");
  8379. EXPECT_TRUE(items[1].content_type == "");
  8380. } else {
  8381. std::string body;
  8382. content_reader([&](const char *data, size_t data_length) {
  8383. body.append(data, data_length);
  8384. return true;
  8385. });
  8386. }
  8387. });
  8388. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. {
  8396. std::string data(1024 * 1024 * 2, '&');
  8397. std::stringstream buffer;
  8398. buffer << data;
  8399. Client cli("https://localhost:8080");
  8400. cli.enable_server_certificate_verification(false);
  8401. UploadFormDataItems items{
  8402. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8403. {"hello", "world", "", ""},
  8404. };
  8405. auto res = cli.Put("/put", items);
  8406. ASSERT_TRUE(res);
  8407. ASSERT_EQ(StatusCode::OK_200, res->status);
  8408. }
  8409. }
  8410. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8412. svr.Put("/put_customboundary",
  8413. [&](const Request &req, const Response & /*res*/,
  8414. const ContentReader &content_reader) {
  8415. if (req.is_multipart_form_data()) {
  8416. std::vector<FormData> items;
  8417. content_reader(
  8418. [&](const FormData &file) {
  8419. items.push_back(file);
  8420. return true;
  8421. },
  8422. [&](const char *data, size_t data_length) {
  8423. items.back().content.append(data, data_length);
  8424. return true;
  8425. });
  8426. EXPECT_TRUE(std::string(items[0].name) == "document");
  8427. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8428. EXPECT_TRUE(items[0].filename == "2MB_data");
  8429. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8430. EXPECT_TRUE(items[1].name == "hello");
  8431. EXPECT_TRUE(items[1].content == "world");
  8432. EXPECT_TRUE(items[1].filename == "");
  8433. EXPECT_TRUE(items[1].content_type == "");
  8434. } else {
  8435. std::string body;
  8436. content_reader([&](const char *data, size_t data_length) {
  8437. body.append(data, data_length);
  8438. return true;
  8439. });
  8440. }
  8441. });
  8442. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8443. auto se = detail::scope_exit([&] {
  8444. svr.stop();
  8445. t.join();
  8446. ASSERT_FALSE(svr.is_running());
  8447. });
  8448. svr.wait_until_ready();
  8449. {
  8450. std::string data(1024 * 1024 * 2, '&');
  8451. std::stringstream buffer;
  8452. buffer << data;
  8453. Client cli("https://localhost:8080");
  8454. cli.enable_server_certificate_verification(false);
  8455. UploadFormDataItems items{
  8456. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8457. {"hello", "world", "", ""},
  8458. };
  8459. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8460. ASSERT_TRUE(res);
  8461. ASSERT_EQ(StatusCode::OK_200, res->status);
  8462. }
  8463. }
  8464. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8465. std::string data(1024 * 1024 * 2, '&');
  8466. std::stringstream buffer;
  8467. buffer << data;
  8468. Client cli("https://localhost:8080");
  8469. cli.enable_server_certificate_verification(false);
  8470. UploadFormDataItems items{
  8471. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8472. {"hello", "world", "", ""},
  8473. };
  8474. for (const char &c : " \t\r\n") {
  8475. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8476. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8477. ASSERT_FALSE(res);
  8478. }
  8479. }
  8480. TEST(MultipartFormDataTest, AlternateFilename) {
  8481. auto handled = false;
  8482. Server svr;
  8483. svr.Post("/test", [&](const Request &req, Response &res) {
  8484. ASSERT_EQ(2u, req.form.files.size());
  8485. ASSERT_EQ(1u, req.form.fields.size());
  8486. // Test files
  8487. const auto &file1 = req.form.get_file("file1");
  8488. ASSERT_EQ("file1", file1.name);
  8489. ASSERT_EQ("A.txt", file1.filename);
  8490. ASSERT_EQ("text/plain", file1.content_type);
  8491. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8492. const auto &file2 = req.form.get_file("file2");
  8493. ASSERT_EQ("file2", file2.name);
  8494. ASSERT_EQ("a.html", file2.filename);
  8495. ASSERT_EQ("text/html", file2.content_type);
  8496. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8497. file2.content);
  8498. // Test text field
  8499. const auto &text = req.form.get_field("text");
  8500. ASSERT_EQ("text default", text);
  8501. res.set_content("ok", "text/plain");
  8502. handled = true;
  8503. });
  8504. thread t = thread([&] { svr.listen(HOST, PORT); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. t.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. ASSERT_TRUE(handled);
  8510. });
  8511. svr.wait_until_ready();
  8512. auto req = "POST /test HTTP/1.1\r\n"
  8513. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8514. "Content-Length: 399\r\n"
  8515. "\r\n"
  8516. "----------\r\n"
  8517. "Content-Disposition: form-data; name=\"text\"\r\n"
  8518. "\r\n"
  8519. "text default\r\n"
  8520. "----------\r\n"
  8521. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8522. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8523. "Content-Type: text/plain\r\n"
  8524. "\r\n"
  8525. "Content of a.txt.\r\n"
  8526. "\r\n"
  8527. "----------\r\n"
  8528. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8529. "\"a.html\"\r\n"
  8530. "Content-Type: text/html\r\n"
  8531. "\r\n"
  8532. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8533. "\r\n"
  8534. "------------\r\n";
  8535. ASSERT_TRUE(send_request(1, req));
  8536. }
  8537. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8538. auto handled = false;
  8539. Server svr;
  8540. svr.Post("/test", [&](const Request &req, Response &) {
  8541. ASSERT_EQ(2u, req.form.fields.size());
  8542. const auto &text1 = req.form.get_field("text1");
  8543. ASSERT_EQ("text1", text1);
  8544. const auto &text2 = req.form.get_field("text2");
  8545. ASSERT_EQ("text2", text2);
  8546. handled = true;
  8547. });
  8548. thread t = thread([&] { svr.listen(HOST, PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. t.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. ASSERT_TRUE(handled);
  8554. });
  8555. svr.wait_until_ready();
  8556. auto req = "POST /test HTTP/1.1\r\n"
  8557. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8558. "Content-Length: 146\r\n"
  8559. "\r\n----------\r\n"
  8560. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8561. "\r\n"
  8562. "text1"
  8563. "\r\n----------\r\n"
  8564. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8565. "\r\n"
  8566. "text2"
  8567. "\r\n------------";
  8568. std::string response;
  8569. ASSERT_TRUE(send_request(1, req, &response));
  8570. ASSERT_EQ("200", response.substr(9, 3));
  8571. }
  8572. TEST(MultipartFormDataTest, ContentLength) {
  8573. auto handled = false;
  8574. Server svr;
  8575. svr.Post("/test", [&](const Request &req, Response &) {
  8576. ASSERT_EQ(2u, req.form.fields.size());
  8577. const auto &text1 = req.form.get_field("text1");
  8578. ASSERT_EQ("text1", text1);
  8579. const auto &text2 = req.form.get_field("text2");
  8580. ASSERT_EQ("text2", text2);
  8581. handled = true;
  8582. });
  8583. thread t = thread([&] { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. t.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. ASSERT_TRUE(handled);
  8589. });
  8590. svr.wait_until_ready();
  8591. auto req = "POST /test HTTP/1.1\r\n"
  8592. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8593. "Content-Length: 167\r\n"
  8594. "\r\n----------\r\n"
  8595. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8596. "Content-Length: 5\r\n"
  8597. "\r\n"
  8598. "text1"
  8599. "\r\n----------\r\n"
  8600. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8601. "\r\n"
  8602. "text2"
  8603. "\r\n------------\r\n";
  8604. std::string response;
  8605. ASSERT_TRUE(send_request(1, req, &response));
  8606. ASSERT_EQ("200", response.substr(9, 3));
  8607. }
  8608. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8609. auto handled = false;
  8610. Server svr;
  8611. svr.Post("/test", [&](const Request &req, Response &) {
  8612. ASSERT_EQ(2u, req.form.fields.size());
  8613. const auto &text1 = req.form.get_field("text1");
  8614. ASSERT_EQ("text1", text1);
  8615. // TODO: Add header access for text fields if needed
  8616. const auto &text2 = req.form.get_field("text2");
  8617. ASSERT_EQ("text2", text2);
  8618. // TODO: Header access for text fields needs to be implemented
  8619. // auto &headers = it->second.headers;
  8620. // ASSERT_EQ(3U, headers.size());
  8621. // auto custom_header = headers.find("x-whatever");
  8622. // ASSERT_TRUE(custom_header != headers.end());
  8623. // ASSERT_NE("customvalue", custom_header->second);
  8624. // ASSERT_EQ("CustomValue", custom_header->second);
  8625. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8626. handled = true;
  8627. });
  8628. thread t = thread([&] { svr.listen(HOST, PORT); });
  8629. auto se = detail::scope_exit([&] {
  8630. svr.stop();
  8631. t.join();
  8632. ASSERT_FALSE(svr.is_running());
  8633. ASSERT_TRUE(handled);
  8634. });
  8635. svr.wait_until_ready();
  8636. auto req = "POST /test HTTP/1.1\r\n"
  8637. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8638. "Content-Length: 232\r\n"
  8639. "\r\n----------\r\n"
  8640. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8641. "Content-Length: 5\r\n"
  8642. "X-Test: 1\r\n"
  8643. "\r\n"
  8644. "text1"
  8645. "\r\n----------\r\n"
  8646. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8647. "Content-Type: text/plain\r\n"
  8648. "X-Whatever: CustomValue\r\n"
  8649. "\r\n"
  8650. "text2"
  8651. "\r\n------------\r\n"
  8652. "That should be disregarded. Not even read";
  8653. std::string response;
  8654. ASSERT_TRUE(send_request(1, req, &response));
  8655. ASSERT_EQ("200", response.substr(9, 3));
  8656. }
  8657. #endif
  8658. TEST(MultipartFormDataTest, LargeHeader) {
  8659. auto handled = false;
  8660. Server svr;
  8661. svr.Post("/test", [&](const Request &req, Response &) {
  8662. ASSERT_EQ(1u, req.form.fields.size());
  8663. const auto &text = req.form.get_field("name1");
  8664. ASSERT_EQ("text1", text);
  8665. handled = true;
  8666. });
  8667. thread t = thread([&] { svr.listen(HOST, PORT); });
  8668. auto se = detail::scope_exit([&] {
  8669. svr.stop();
  8670. t.join();
  8671. ASSERT_FALSE(svr.is_running());
  8672. ASSERT_TRUE(handled);
  8673. });
  8674. svr.wait_until_ready();
  8675. auto boundary = std::string("cpp-httplib-multipart-data");
  8676. std::string content = "--" + boundary +
  8677. "\r\n"
  8678. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8679. "\r\n"
  8680. "text1\r\n"
  8681. "--" +
  8682. boundary + "--\r\n";
  8683. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8684. "Content-Type: multipart/form-data;boundary=" +
  8685. boundary +
  8686. "\r\n"
  8687. "Content-Length: " +
  8688. std::to_string(content.size()) +
  8689. "\r\n"
  8690. "Dummy-Header: ";
  8691. std::string header_suffix = "\r\n"
  8692. "\r\n";
  8693. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8694. size_t header_dummy_size =
  8695. read_buff_size -
  8696. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8697. auto header_dummy = std::string(header_dummy_size, '@');
  8698. auto req = header_prefix + header_dummy + header_suffix + content;
  8699. std::string response;
  8700. ASSERT_TRUE(send_request(1, req, &response));
  8701. ASSERT_EQ("200", response.substr(9, 3));
  8702. }
  8703. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8704. static constexpr unsigned int number_of_tasks{1000000};
  8705. std::atomic_uint count{0};
  8706. std::unique_ptr<TaskQueue> task_queue{
  8707. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8708. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8709. auto queued = task_queue->enqueue(
  8710. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8711. EXPECT_TRUE(queued);
  8712. }
  8713. EXPECT_NO_THROW(task_queue->shutdown());
  8714. EXPECT_EQ(number_of_tasks, count.load());
  8715. }
  8716. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8717. static constexpr unsigned int number_of_tasks{1000000};
  8718. static constexpr unsigned int qlimit{2};
  8719. unsigned int queued_count{0};
  8720. std::atomic_uint count{0};
  8721. std::unique_ptr<TaskQueue> task_queue{
  8722. new ThreadPool{/*num_threads=*/1, qlimit}};
  8723. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8724. if (task_queue->enqueue(
  8725. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8726. queued_count++;
  8727. }
  8728. }
  8729. EXPECT_NO_THROW(task_queue->shutdown());
  8730. EXPECT_EQ(queued_count, count.load());
  8731. EXPECT_TRUE(queued_count <= number_of_tasks);
  8732. EXPECT_TRUE(queued_count >= qlimit);
  8733. }
  8734. TEST(TaskQueueTest, MaxQueuedRequests) {
  8735. static constexpr unsigned int qlimit{3};
  8736. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8737. std::condition_variable sem_cv;
  8738. std::mutex sem_mtx;
  8739. int credits = 0;
  8740. bool queued;
  8741. /* Fill up the queue with tasks that will block until we give them credits to
  8742. * complete. */
  8743. for (unsigned int n = 0; n <= qlimit;) {
  8744. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8745. std::unique_lock<std::mutex> lock(sem_mtx);
  8746. while (credits <= 0) {
  8747. sem_cv.wait(lock);
  8748. }
  8749. /* Consume the credit and signal the test code if they are all gone. */
  8750. if (--credits == 0) { sem_cv.notify_one(); }
  8751. });
  8752. if (n < qlimit) {
  8753. /* The first qlimit enqueues must succeed. */
  8754. EXPECT_TRUE(queued);
  8755. } else {
  8756. /* The last one will succeed only when the worker thread
  8757. * starts and dequeues the first blocking task. Although
  8758. * not necessary for the correctness of this test, we sleep for
  8759. * a short while to avoid busy waiting. */
  8760. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8761. }
  8762. if (queued) { n++; }
  8763. }
  8764. /* Further enqueues must fail since the queue is full. */
  8765. for (auto i = 0; i < 4; i++) {
  8766. queued = task_queue->enqueue([] {});
  8767. EXPECT_FALSE(queued);
  8768. }
  8769. /* Give the credits to allow the previous tasks to complete. */
  8770. {
  8771. std::unique_lock<std::mutex> lock(sem_mtx);
  8772. credits += qlimit + 1;
  8773. }
  8774. sem_cv.notify_all();
  8775. /* Wait for all the credits to be consumed. */
  8776. {
  8777. std::unique_lock<std::mutex> lock(sem_mtx);
  8778. while (credits > 0) {
  8779. sem_cv.wait(lock);
  8780. }
  8781. }
  8782. /* Check that we are able again to enqueue at least qlimit tasks. */
  8783. for (unsigned int i = 0; i < qlimit; i++) {
  8784. queued = task_queue->enqueue([] {});
  8785. EXPECT_TRUE(queued);
  8786. }
  8787. EXPECT_NO_THROW(task_queue->shutdown());
  8788. }
  8789. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8790. Server svr;
  8791. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8792. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8793. });
  8794. svr.Get("/hello", [](const Request &req, Response &res) {
  8795. res.set_content(req.get_param_value("key"), "text/plain");
  8796. });
  8797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8798. auto se = detail::scope_exit([&] {
  8799. svr.stop();
  8800. thread.join();
  8801. ASSERT_FALSE(svr.is_running());
  8802. });
  8803. svr.wait_until_ready();
  8804. {
  8805. Client cli(HOST, PORT);
  8806. cli.set_follow_location(true);
  8807. auto res = cli.Get("/");
  8808. ASSERT_TRUE(res);
  8809. EXPECT_EQ(StatusCode::OK_200, res->status);
  8810. EXPECT_EQ("val&key2=val2", res->body);
  8811. }
  8812. }
  8813. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8814. Server svr;
  8815. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8816. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8817. });
  8818. svr.Get("/hello", [](const Request &req, Response &res) {
  8819. res.set_content(req.get_param_value("key"), "text/plain");
  8820. });
  8821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8822. auto se = detail::scope_exit([&] {
  8823. svr.stop();
  8824. thread.join();
  8825. ASSERT_FALSE(svr.is_running());
  8826. });
  8827. svr.wait_until_ready();
  8828. {
  8829. Client cli(HOST, PORT);
  8830. cli.set_follow_location(true);
  8831. auto res = cli.Get("/");
  8832. ASSERT_TRUE(res);
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8835. }
  8836. }
  8837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8838. TEST(RedirectTest, Issue2185_Online) {
  8839. SSLClient client("github.com");
  8840. client.set_follow_location(true);
  8841. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8842. "Coollab-Windows.zip");
  8843. ASSERT_TRUE(res);
  8844. EXPECT_EQ(StatusCode::OK_200, res->status);
  8845. EXPECT_EQ(9920427U, res->body.size());
  8846. }
  8847. #endif
  8848. TEST(VulnerabilityTest, CRLFInjection) {
  8849. Server svr;
  8850. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8851. res.set_content("Hello 1", "text/plain");
  8852. });
  8853. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8854. res.set_content("Hello 2", "text/plain");
  8855. });
  8856. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8857. res.set_content("Hello 3", "text/plain");
  8858. });
  8859. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8860. res.set_content("Hello 4", "text/plain");
  8861. });
  8862. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8863. for (const auto &x : req.headers) {
  8864. auto key = x.first;
  8865. EXPECT_STRNE("evil", key.c_str());
  8866. }
  8867. });
  8868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8869. auto se = detail::scope_exit([&] {
  8870. svr.stop();
  8871. thread.join();
  8872. ASSERT_FALSE(svr.is_running());
  8873. });
  8874. svr.wait_until_ready();
  8875. {
  8876. Client cli(HOST, PORT);
  8877. cli.Post("/test1", "A=B",
  8878. "application/x-www-form-urlencoded\r\nevil: hello1");
  8879. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8880. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8881. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8882. }
  8883. }
  8884. TEST(PathParamsTest, StaticMatch) {
  8885. const auto pattern = "/users/all";
  8886. detail::PathParamsMatcher matcher(pattern);
  8887. Request request;
  8888. request.path = "/users/all";
  8889. ASSERT_TRUE(matcher.match(request));
  8890. std::unordered_map<std::string, std::string> expected_params = {};
  8891. EXPECT_EQ(request.path_params, expected_params);
  8892. }
  8893. TEST(PathParamsTest, StaticMismatch) {
  8894. const auto pattern = "/users/all";
  8895. detail::PathParamsMatcher matcher(pattern);
  8896. Request request;
  8897. request.path = "/users/1";
  8898. ASSERT_FALSE(matcher.match(request));
  8899. }
  8900. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8901. const auto pattern = "/users/:id/subscriptions";
  8902. detail::PathParamsMatcher matcher(pattern);
  8903. Request request;
  8904. request.path = "/users/42/subscriptions";
  8905. ASSERT_TRUE(matcher.match(request));
  8906. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8907. EXPECT_EQ(request.path_params, expected_params);
  8908. }
  8909. TEST(PathParamsTest, SingleParamInTheEnd) {
  8910. const auto pattern = "/users/:id";
  8911. detail::PathParamsMatcher matcher(pattern);
  8912. Request request;
  8913. request.path = "/users/24";
  8914. ASSERT_TRUE(matcher.match(request));
  8915. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8916. EXPECT_EQ(request.path_params, expected_params);
  8917. }
  8918. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8919. const auto pattern = "/users/:id/";
  8920. detail::PathParamsMatcher matcher(pattern);
  8921. Request request;
  8922. request.path = "/users/42/";
  8923. ASSERT_TRUE(matcher.match(request));
  8924. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8925. EXPECT_EQ(request.path_params, expected_params);
  8926. }
  8927. TEST(PathParamsTest, EmptyParam) {
  8928. const auto pattern = "/users/:id/";
  8929. detail::PathParamsMatcher matcher(pattern);
  8930. Request request;
  8931. request.path = "/users//";
  8932. ASSERT_TRUE(matcher.match(request));
  8933. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8934. EXPECT_EQ(request.path_params, expected_params);
  8935. }
  8936. TEST(PathParamsTest, FragmentMismatch) {
  8937. const auto pattern = "/users/:id/";
  8938. detail::PathParamsMatcher matcher(pattern);
  8939. Request request;
  8940. request.path = "/admins/24/";
  8941. ASSERT_FALSE(matcher.match(request));
  8942. }
  8943. TEST(PathParamsTest, ExtraFragments) {
  8944. const auto pattern = "/users/:id";
  8945. detail::PathParamsMatcher matcher(pattern);
  8946. Request request;
  8947. request.path = "/users/42/subscriptions";
  8948. ASSERT_FALSE(matcher.match(request));
  8949. }
  8950. TEST(PathParamsTest, MissingTrailingParam) {
  8951. const auto pattern = "/users/:id";
  8952. detail::PathParamsMatcher matcher(pattern);
  8953. Request request;
  8954. request.path = "/users";
  8955. ASSERT_FALSE(matcher.match(request));
  8956. }
  8957. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8958. const auto pattern = "/users/:id/subscriptions";
  8959. detail::PathParamsMatcher matcher(pattern);
  8960. Request request;
  8961. request.path = "/users/subscriptions";
  8962. ASSERT_FALSE(matcher.match(request));
  8963. }
  8964. TEST(PathParamsTest, MultipleParams) {
  8965. const auto pattern = "/users/:userid/subscriptions/:subid";
  8966. detail::PathParamsMatcher matcher(pattern);
  8967. Request request;
  8968. request.path = "/users/42/subscriptions/2";
  8969. ASSERT_TRUE(matcher.match(request));
  8970. std::unordered_map<std::string, std::string> expected_params = {
  8971. {"userid", "42"}, {"subid", "2"}};
  8972. EXPECT_EQ(request.path_params, expected_params);
  8973. }
  8974. TEST(PathParamsTest, SequenceOfParams) {
  8975. const auto pattern = "/values/:x/:y/:z";
  8976. detail::PathParamsMatcher matcher(pattern);
  8977. Request request;
  8978. request.path = "/values/1/2/3";
  8979. ASSERT_TRUE(matcher.match(request));
  8980. std::unordered_map<std::string, std::string> expected_params = {
  8981. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8982. EXPECT_EQ(request.path_params, expected_params);
  8983. }
  8984. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8985. const auto pattern = "/prefix:suffix";
  8986. detail::PathParamsMatcher matcher(pattern);
  8987. Request request;
  8988. request.path = "/prefix:suffix";
  8989. ASSERT_TRUE(matcher.match(request));
  8990. const std::unordered_map<std::string, std::string> expected_params = {};
  8991. EXPECT_EQ(request.path_params, expected_params);
  8992. }
  8993. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8994. // If ipv6 regex working, regex match codepath is taken.
  8995. // else port will default to 80 in Client impl
  8996. int clientImplMagicPort = 80;
  8997. int port = 4321;
  8998. // above ports must be different to avoid false negative
  8999. EXPECT_NE(clientImplMagicPort, port);
  9000. std::string ipV6TestURL = "http://[ff06::c3]";
  9001. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9002. CLIENT_PRIVATE_KEY_FILE);
  9003. EXPECT_EQ(cli.port(), port);
  9004. }
  9005. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9006. auto file_path = "./www/dir/index.html";
  9007. auto dir_path = "./www/dir";
  9008. detail::FileStat stat_file(file_path);
  9009. EXPECT_TRUE(stat_file.is_file());
  9010. EXPECT_FALSE(stat_file.is_dir());
  9011. detail::FileStat stat_dir(dir_path);
  9012. EXPECT_FALSE(stat_dir.is_file());
  9013. EXPECT_TRUE(stat_dir.is_dir());
  9014. }
  9015. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9016. // IPv4 with default HTTP port (80)
  9017. EXPECT_EQ("example.com",
  9018. detail::make_host_and_port_string("example.com", 80, false));
  9019. // IPv4 with default HTTPS port (443)
  9020. EXPECT_EQ("example.com",
  9021. detail::make_host_and_port_string("example.com", 443, true));
  9022. // IPv4 with non-default HTTP port
  9023. EXPECT_EQ("example.com:8080",
  9024. detail::make_host_and_port_string("example.com", 8080, false));
  9025. // IPv4 with non-default HTTPS port
  9026. EXPECT_EQ("example.com:8443",
  9027. detail::make_host_and_port_string("example.com", 8443, true));
  9028. // IPv6 with default HTTP port (80)
  9029. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9030. // IPv6 with default HTTPS port (443)
  9031. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9032. // IPv6 with non-default HTTP port
  9033. EXPECT_EQ("[::1]:8080",
  9034. detail::make_host_and_port_string("::1", 8080, false));
  9035. // IPv6 with non-default HTTPS port
  9036. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9037. // IPv6 full address with default port
  9038. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9039. detail::make_host_and_port_string(
  9040. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9041. // IPv6 full address with non-default port
  9042. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9043. detail::make_host_and_port_string(
  9044. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9045. // IPv6 localhost with non-default port
  9046. EXPECT_EQ("[::1]:3000",
  9047. detail::make_host_and_port_string("::1", 3000, false));
  9048. // IPv6 with zone ID (link-local address) with default port
  9049. EXPECT_EQ("[fe80::1%eth0]",
  9050. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9051. // IPv6 with zone ID (link-local address) with non-default port
  9052. EXPECT_EQ("[fe80::1%eth0]:8080",
  9053. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9054. // Edge case: Port 443 with is_ssl=false (should add port)
  9055. EXPECT_EQ("example.com:443",
  9056. detail::make_host_and_port_string("example.com", 443, false));
  9057. // Edge case: Port 80 with is_ssl=true (should add port)
  9058. EXPECT_EQ("example.com:80",
  9059. detail::make_host_and_port_string("example.com", 80, true));
  9060. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9061. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9062. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9063. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9064. // Security fix: Already bracketed IPv6 should not get double brackets
  9065. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9066. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9067. EXPECT_EQ("[::1]:8080",
  9068. detail::make_host_and_port_string("[::1]", 8080, false));
  9069. EXPECT_EQ("[2001:db8::1]:8080",
  9070. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9071. EXPECT_EQ("[fe80::1%eth0]",
  9072. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9073. EXPECT_EQ("[fe80::1%eth0]:8080",
  9074. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9075. // Edge case: Empty host (should return as-is)
  9076. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9077. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9078. // This is a known limitation but shouldn't crash
  9079. EXPECT_EQ("[host:name]",
  9080. detail::make_host_and_port_string("host:name", 80, false));
  9081. // Port number edge cases (no validation, but should not crash)
  9082. EXPECT_EQ("example.com:0",
  9083. detail::make_host_and_port_string("example.com", 0, false));
  9084. EXPECT_EQ("example.com:-1",
  9085. detail::make_host_and_port_string("example.com", -1, false));
  9086. EXPECT_EQ("example.com:65535",
  9087. detail::make_host_and_port_string("example.com", 65535, false));
  9088. EXPECT_EQ("example.com:65536",
  9089. detail::make_host_and_port_string("example.com", 65536, false));
  9090. }
  9091. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9092. Server svr;
  9093. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9094. EXPECT_EQ(res.status, 400);
  9095. });
  9096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9097. auto se = detail::scope_exit([&] {
  9098. svr.stop();
  9099. thread.join();
  9100. ASSERT_FALSE(svr.is_running());
  9101. });
  9102. svr.wait_until_ready();
  9103. Client cli(HOST, PORT);
  9104. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9105. }
  9106. TEST(InvalidHeaderCharsTest, is_field_name) {
  9107. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9108. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9109. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9110. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9111. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9112. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9113. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9114. EXPECT_FALSE(detail::fields::is_field_name(""));
  9115. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9116. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9117. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9118. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9119. }
  9120. TEST(InvalidHeaderCharsTest, is_field_value) {
  9121. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9122. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9123. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9124. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9125. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9126. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9127. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9128. EXPECT_TRUE(detail::fields::is_field_value(""));
  9129. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9130. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9131. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9132. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9133. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9134. }
  9135. TEST(InvalidHeaderCharsTest, OnServer) {
  9136. Server svr;
  9137. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9138. std::string header = "Not Set";
  9139. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9140. res.set_header(header, "value");
  9141. res.set_content("Page Content Page Content", "text/plain");
  9142. });
  9143. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9144. std::string header = "Not Set";
  9145. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9146. res.set_header("X-Test", header);
  9147. res.set_content("Page Content Page Content", "text/plain");
  9148. });
  9149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9150. auto se = detail::scope_exit([&] {
  9151. svr.stop();
  9152. thread.join();
  9153. ASSERT_FALSE(svr.is_running());
  9154. });
  9155. svr.wait_until_ready();
  9156. Client cli(HOST, PORT);
  9157. {
  9158. auto res = cli.Get(
  9159. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9160. ASSERT_TRUE(res);
  9161. EXPECT_EQ("Page Content Page Content", res->body);
  9162. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9163. }
  9164. {
  9165. auto res = cli.Get(
  9166. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9167. ASSERT_TRUE(res);
  9168. EXPECT_EQ("Page Content Page Content", res->body);
  9169. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9170. }
  9171. }
  9172. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9173. auto handled = false;
  9174. Server svr;
  9175. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9176. thread t = thread([&] { svr.listen(HOST, PORT); });
  9177. auto se = detail::scope_exit([&] {
  9178. svr.stop();
  9179. t.join();
  9180. ASSERT_FALSE(svr.is_running());
  9181. ASSERT_FALSE(handled);
  9182. });
  9183. svr.wait_until_ready();
  9184. auto req = "POST /test HTTP/1.1\r\n"
  9185. "Content-Length: x\r\n"
  9186. "\r\n";
  9187. std::string response;
  9188. ASSERT_TRUE(send_request(1, req, &response));
  9189. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9190. response.substr(0, response.find("\r\n")));
  9191. }
  9192. #ifndef _WIN32
  9193. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9194. static constexpr char reject[] = "Unauthorized";
  9195. static constexpr char accept[] = "Upload accepted";
  9196. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9197. Server svr;
  9198. svr.set_expect_100_continue_handler(
  9199. [](const Request & /*req*/, Response &res) {
  9200. res.status = StatusCode::Unauthorized_401;
  9201. res.set_content(reject, "text/plain");
  9202. return res.status;
  9203. });
  9204. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9205. res.set_content(accept, "text/plain");
  9206. });
  9207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9208. auto se = detail::scope_exit([&] {
  9209. svr.stop();
  9210. thread.join();
  9211. ASSERT_FALSE(svr.is_running());
  9212. });
  9213. svr.wait_until_ready();
  9214. {
  9215. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9216. curl_easy_init(), &curl_easy_cleanup};
  9217. ASSERT_NE(curl, nullptr);
  9218. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9219. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9220. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9221. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9222. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9223. &curl_slist_free_all};
  9224. ASSERT_NE(list, nullptr);
  9225. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9226. struct read_data {
  9227. size_t read_size;
  9228. size_t total_size;
  9229. } data = {0, total_size};
  9230. using read_callback_t =
  9231. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9232. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9233. void *userdata) -> size_t {
  9234. read_data *data = (read_data *)userdata;
  9235. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9236. std::fill_n(ptr, size * nmemb, 'A');
  9237. data->read_size += size * nmemb;
  9238. return size * nmemb;
  9239. };
  9240. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9241. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9242. std::vector<char> buffer;
  9243. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9244. using write_callback_t =
  9245. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9246. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9247. void *userdata) -> size_t {
  9248. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9249. buffer->reserve(buffer->size() + size * nmemb + 1);
  9250. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9251. return size * nmemb;
  9252. };
  9253. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9254. {
  9255. const auto res = curl_easy_perform(curl.get());
  9256. ASSERT_EQ(res, CURLE_OK);
  9257. }
  9258. {
  9259. auto response_code = long{};
  9260. const auto res =
  9261. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9262. ASSERT_EQ(res, CURLE_OK);
  9263. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9264. }
  9265. {
  9266. auto dl = curl_off_t{};
  9267. const auto res =
  9268. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9269. ASSERT_EQ(res, CURLE_OK);
  9270. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9271. }
  9272. {
  9273. buffer.push_back('\0');
  9274. ASSERT_STRCASEEQ(buffer.data(), reject);
  9275. }
  9276. }
  9277. }
  9278. #endif
  9279. template <typename S, typename C>
  9280. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9281. svr.Get("/stream", [&](const Request &, Response &res) {
  9282. auto data = new std::string("01234567890123456789");
  9283. res.set_content_provider(
  9284. data->size(), "text/plain",
  9285. [&, data](size_t offset, size_t length, DataSink &sink) {
  9286. const size_t DATA_CHUNK_SIZE = 4;
  9287. const auto &d = *data;
  9288. std::this_thread::sleep_for(std::chrono::seconds(1));
  9289. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9290. return true;
  9291. },
  9292. [data](bool success) {
  9293. EXPECT_FALSE(success);
  9294. delete data;
  9295. });
  9296. });
  9297. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9298. auto i = new size_t(0);
  9299. res.set_content_provider(
  9300. "text/plain",
  9301. [i](size_t, DataSink &sink) {
  9302. if (*i < 5) {
  9303. std::this_thread::sleep_for(std::chrono::seconds(1));
  9304. sink.write("abcd", 4);
  9305. (*i)++;
  9306. } else {
  9307. sink.done();
  9308. }
  9309. return true;
  9310. },
  9311. [i](bool success) {
  9312. EXPECT_FALSE(success);
  9313. delete i;
  9314. });
  9315. });
  9316. svr.Get("/chunked", [&](const Request &, Response &res) {
  9317. auto i = new size_t(0);
  9318. res.set_chunked_content_provider(
  9319. "text/plain",
  9320. [i](size_t, DataSink &sink) {
  9321. if (*i < 5) {
  9322. std::this_thread::sleep_for(std::chrono::seconds(1));
  9323. sink.os << "abcd";
  9324. (*i)++;
  9325. } else {
  9326. sink.done();
  9327. }
  9328. return true;
  9329. },
  9330. [i](bool success) {
  9331. EXPECT_FALSE(success);
  9332. delete i;
  9333. });
  9334. });
  9335. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9336. auto se = detail::scope_exit([&] {
  9337. svr.stop();
  9338. listen_thread.join();
  9339. ASSERT_FALSE(svr.is_running());
  9340. });
  9341. svr.wait_until_ready();
  9342. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9343. {
  9344. auto start = std::chrono::steady_clock::now();
  9345. auto res = cli.Get("/stream");
  9346. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9347. std::chrono::steady_clock::now() - start)
  9348. .count();
  9349. ASSERT_FALSE(res);
  9350. EXPECT_EQ(Error::Read, res.error());
  9351. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9352. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9353. }
  9354. {
  9355. auto start = std::chrono::steady_clock::now();
  9356. auto res = cli.Get("/stream_without_length");
  9357. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9358. std::chrono::steady_clock::now() - start)
  9359. .count();
  9360. ASSERT_FALSE(res);
  9361. EXPECT_EQ(Error::Read, res.error());
  9362. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9363. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9364. }
  9365. {
  9366. auto start = std::chrono::steady_clock::now();
  9367. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9368. EXPECT_EQ("abcd", string(data, data_length));
  9369. return true;
  9370. });
  9371. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9372. std::chrono::steady_clock::now() - start)
  9373. .count();
  9374. ASSERT_FALSE(res);
  9375. EXPECT_EQ(Error::Read, res.error());
  9376. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9377. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9378. }
  9379. }
  9380. TEST(MaxTimeoutTest, ContentStream) {
  9381. time_t timeout = 2000;
  9382. time_t threshold = 200;
  9383. Server svr;
  9384. Client cli("localhost", PORT);
  9385. max_timeout_test(svr, cli, timeout, threshold);
  9386. }
  9387. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9388. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9389. time_t timeout = 2000;
  9390. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9392. SSLClient cli("localhost", PORT);
  9393. cli.enable_server_certificate_verification(false);
  9394. max_timeout_test(svr, cli, timeout, threshold);
  9395. }
  9396. #endif
  9397. class EventDispatcher {
  9398. public:
  9399. EventDispatcher() {}
  9400. bool wait_event(DataSink *sink) {
  9401. unique_lock<mutex> lk(m_);
  9402. int id = id_;
  9403. // Wait with timeout to prevent hanging if client disconnects
  9404. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9405. [&] { return cid_ == id; })) {
  9406. return false; // Timeout occurred
  9407. }
  9408. sink->write(message_.data(), message_.size());
  9409. return true;
  9410. }
  9411. void send_event(const string &message) {
  9412. lock_guard<mutex> lk(m_);
  9413. cid_ = id_++;
  9414. message_ = message;
  9415. cv_.notify_all();
  9416. }
  9417. private:
  9418. mutex m_;
  9419. condition_variable cv_;
  9420. atomic_int id_{0};
  9421. atomic_int cid_{-1};
  9422. string message_;
  9423. };
  9424. TEST(ClientInThreadTest, Issue2068) {
  9425. EventDispatcher ed;
  9426. Server svr;
  9427. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9428. res.set_chunked_content_provider("text/event-stream",
  9429. [&](size_t /*offset*/, DataSink &sink) {
  9430. return ed.wait_event(&sink);
  9431. });
  9432. });
  9433. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9434. svr.wait_until_ready();
  9435. thread event_thread([&] {
  9436. int id = 0;
  9437. while (svr.is_running()) {
  9438. this_thread::sleep_for(chrono::milliseconds(500));
  9439. std::stringstream ss;
  9440. ss << "data: " << id << "\n\n";
  9441. ed.send_event(ss.str());
  9442. id++;
  9443. }
  9444. });
  9445. auto se = detail::scope_exit([&] {
  9446. svr.stop();
  9447. listen_thread.join();
  9448. event_thread.join();
  9449. ASSERT_FALSE(svr.is_running());
  9450. });
  9451. {
  9452. auto client = detail::make_unique<Client>(HOST, PORT);
  9453. client->set_read_timeout(std::chrono::minutes(10));
  9454. std::atomic<bool> stop{false};
  9455. std::thread t([&] {
  9456. client->Get("/event1",
  9457. [&](const char *, size_t) -> bool { return !stop; });
  9458. });
  9459. std::this_thread::sleep_for(std::chrono::seconds(2));
  9460. stop = true;
  9461. client->stop();
  9462. t.join();
  9463. // Reset client after thread has finished
  9464. client.reset();
  9465. }
  9466. }
  9467. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9468. Server svr;
  9469. svr.Get("/", [](const Request &req, Response &res) {
  9470. EXPECT_EQ(2U, req.trailers.size());
  9471. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9472. // Denied
  9473. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9474. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9475. // Accepted
  9476. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9477. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9478. EXPECT_TRUE(req.has_trailer("X-World"));
  9479. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9480. res.set_content("ok", "text/plain");
  9481. });
  9482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9483. auto se = detail::scope_exit([&] {
  9484. svr.stop();
  9485. t.join();
  9486. ASSERT_FALSE(svr.is_running());
  9487. });
  9488. svr.wait_until_ready();
  9489. const std::string req = "GET / HTTP/1.1\r\n"
  9490. "Transfer-Encoding: chunked\r\n"
  9491. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9492. "\r\n"
  9493. "0\r\n"
  9494. "Content-Length: 10\r\n"
  9495. "Host: internal.local\r\n"
  9496. "Content-Type: malicious/content\r\n"
  9497. "Cookie: any\r\n"
  9498. "Set-Cookie: any\r\n"
  9499. "X-Forwarded-For: attacker.com\r\n"
  9500. "X-Real-Ip: 1.1.1.1\r\n"
  9501. "X-Hello: hello\r\n"
  9502. "X-World: world\r\n"
  9503. "\r\n";
  9504. std::string res;
  9505. ASSERT_TRUE(send_request(1, req, &res));
  9506. }
  9507. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9508. Server svr;
  9509. std::string observed_remote_addr;
  9510. std::string observed_xff;
  9511. svr.Get("/ip", [&](const Request &req, Response &res) {
  9512. observed_remote_addr = req.remote_addr;
  9513. observed_xff = req.get_header_value("X-Forwarded-For");
  9514. res.set_content("ok", "text/plain");
  9515. });
  9516. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9517. auto se = detail::scope_exit([&] {
  9518. svr.stop();
  9519. t.join();
  9520. ASSERT_FALSE(svr.is_running());
  9521. });
  9522. svr.wait_until_ready();
  9523. Client cli(HOST, PORT);
  9524. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9525. ASSERT_TRUE(res);
  9526. EXPECT_EQ(StatusCode::OK_200, res->status);
  9527. EXPECT_EQ(observed_xff, "203.0.113.66");
  9528. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9529. observed_remote_addr == "127.0.0.1");
  9530. }
  9531. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9532. Server svr;
  9533. svr.set_trusted_proxies({"203.0.113.66"});
  9534. std::string observed_remote_addr;
  9535. std::string observed_xff;
  9536. svr.Get("/ip", [&](const Request &req, Response &res) {
  9537. observed_remote_addr = req.remote_addr;
  9538. observed_xff = req.get_header_value("X-Forwarded-For");
  9539. res.set_content("ok", "text/plain");
  9540. });
  9541. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9542. auto se = detail::scope_exit([&] {
  9543. svr.stop();
  9544. t.join();
  9545. ASSERT_FALSE(svr.is_running());
  9546. });
  9547. svr.wait_until_ready();
  9548. Client cli(HOST, PORT);
  9549. auto res = cli.Get("/ip");
  9550. ASSERT_TRUE(res);
  9551. EXPECT_EQ(StatusCode::OK_200, res->status);
  9552. EXPECT_EQ(observed_xff, "");
  9553. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9554. observed_remote_addr == "127.0.0.1");
  9555. }
  9556. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9557. Server svr;
  9558. svr.set_trusted_proxies({"203.0.113.66"});
  9559. std::string observed_remote_addr;
  9560. std::string observed_xff;
  9561. svr.Get("/ip", [&](const Request &req, Response &res) {
  9562. observed_remote_addr = req.remote_addr;
  9563. observed_xff = req.get_header_value("X-Forwarded-For");
  9564. res.set_content("ok", "text/plain");
  9565. });
  9566. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9567. auto se = detail::scope_exit([&] {
  9568. svr.stop();
  9569. t.join();
  9570. ASSERT_FALSE(svr.is_running());
  9571. });
  9572. svr.wait_until_ready();
  9573. Client cli(HOST, PORT);
  9574. auto res =
  9575. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9576. ASSERT_TRUE(res);
  9577. EXPECT_EQ(StatusCode::OK_200, res->status);
  9578. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9579. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9580. }
  9581. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9582. Server svr;
  9583. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9584. std::string observed_remote_addr;
  9585. std::string observed_xff;
  9586. svr.Get("/ip", [&](const Request &req, Response &res) {
  9587. observed_remote_addr = req.remote_addr;
  9588. observed_xff = req.get_header_value("X-Forwarded-For");
  9589. res.set_content("ok", "text/plain");
  9590. });
  9591. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. Client cli(HOST, PORT);
  9599. auto res = cli.Get(
  9600. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9601. ASSERT_TRUE(res);
  9602. EXPECT_EQ(StatusCode::OK_200, res->status);
  9603. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9604. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9605. }
  9606. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9607. Server svr;
  9608. svr.set_trusted_proxies({"192.0.2.45"});
  9609. std::string observed_remote_addr;
  9610. std::string observed_xff;
  9611. svr.Get("/ip", [&](const Request &req, Response &res) {
  9612. observed_remote_addr = req.remote_addr;
  9613. observed_xff = req.get_header_value("X-Forwarded-For");
  9614. res.set_content("ok", "text/plain");
  9615. });
  9616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop();
  9619. t.join();
  9620. ASSERT_FALSE(svr.is_running());
  9621. });
  9622. svr.wait_until_ready();
  9623. Client cli(HOST, PORT);
  9624. auto res =
  9625. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9626. ASSERT_TRUE(res);
  9627. EXPECT_EQ(StatusCode::OK_200, res->status);
  9628. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9629. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9630. }
  9631. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9632. Server svr;
  9633. svr.set_trusted_proxies({"192.0.2.45"});
  9634. std::string observed_remote_addr;
  9635. std::string observed_xff;
  9636. svr.Get("/ip", [&](const Request &req, Response &res) {
  9637. observed_remote_addr = req.remote_addr;
  9638. observed_xff = req.get_header_value("X-Forwarded-For");
  9639. res.set_content("ok", "text/plain");
  9640. });
  9641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9642. auto se = detail::scope_exit([&] {
  9643. svr.stop();
  9644. t.join();
  9645. ASSERT_FALSE(svr.is_running());
  9646. });
  9647. svr.wait_until_ready();
  9648. Client cli(HOST, PORT);
  9649. auto res = cli.Get(
  9650. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9651. ASSERT_TRUE(res);
  9652. EXPECT_EQ(StatusCode::OK_200, res->status);
  9653. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9654. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9655. }
  9656. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9657. Server svr;
  9658. svr.set_trusted_proxies({"192.0.2.45"});
  9659. std::string observed_remote_addr;
  9660. std::string observed_xff;
  9661. svr.Get("/ip", [&](const Request &req, Response &res) {
  9662. observed_remote_addr = req.remote_addr;
  9663. observed_xff = req.get_header_value("X-Forwarded-For");
  9664. res.set_content("ok", "text/plain");
  9665. });
  9666. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. t.join();
  9670. ASSERT_FALSE(svr.is_running());
  9671. });
  9672. svr.wait_until_ready();
  9673. Client cli(HOST, PORT);
  9674. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9675. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9676. ASSERT_TRUE(res);
  9677. EXPECT_EQ(StatusCode::OK_200, res->status);
  9678. // Header parser trims surrounding whitespace of the header value
  9679. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9680. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9681. }
  9682. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9683. Server svr;
  9684. svr.Post("/post", [&](const Request &req, Response &res) {
  9685. res.set_content(req.body, "text/plain");
  9686. });
  9687. svr.Put("/put", [&](const Request &req, Response &res) {
  9688. res.set_content(req.body, "text/plain");
  9689. });
  9690. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9691. res.set_content(req.body, "text/plain");
  9692. });
  9693. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9694. res.set_content(req.body, "text/plain");
  9695. });
  9696. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9697. auto se = detail::scope_exit([&] {
  9698. svr.stop();
  9699. t.join();
  9700. ASSERT_FALSE(svr.is_running());
  9701. });
  9702. svr.wait_until_ready();
  9703. std::string resp;
  9704. // POST without Content-Length
  9705. ASSERT_TRUE(send_request(5,
  9706. "POST /post HTTP/1.1\r\n"
  9707. "Host: localhost\r\n"
  9708. "Connection: close\r\n"
  9709. "\r\n",
  9710. &resp));
  9711. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9712. // PUT without Content-Length
  9713. resp.clear();
  9714. ASSERT_TRUE(send_request(5,
  9715. "PUT /put HTTP/1.1\r\n"
  9716. "Host: localhost\r\n"
  9717. "Connection: close\r\n"
  9718. "\r\n",
  9719. &resp));
  9720. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9721. // PATCH without Content-Length
  9722. resp.clear();
  9723. ASSERT_TRUE(send_request(5,
  9724. "PATCH /patch HTTP/1.1\r\n"
  9725. "Host: localhost\r\n"
  9726. "Connection: close\r\n"
  9727. "\r\n",
  9728. &resp));
  9729. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9730. // DELETE without Content-Length
  9731. resp.clear();
  9732. ASSERT_TRUE(send_request(5,
  9733. "DELETE /delete HTTP/1.1\r\n"
  9734. "Host: localhost\r\n"
  9735. "Connection: close\r\n"
  9736. "\r\n",
  9737. &resp));
  9738. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9739. }
  9740. //==============================================================================
  9741. // open_stream() Tests
  9742. //==============================================================================
  9743. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9744. std::string result;
  9745. char buf[8192];
  9746. ssize_t n;
  9747. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9748. result.append(buf, static_cast<size_t>(n));
  9749. }
  9750. return result;
  9751. }
  9752. // Mock stream for unit tests
  9753. class MockStream : public Stream {
  9754. public:
  9755. std::string data;
  9756. size_t pos = 0;
  9757. ssize_t error_after = -1; // -1 = no error
  9758. explicit MockStream(const std::string &d, ssize_t err = -1)
  9759. : data(d), error_after(err) {}
  9760. bool is_readable() const override { return true; }
  9761. bool wait_readable() const override { return true; }
  9762. bool wait_writable() const override { return true; }
  9763. ssize_t read(char *ptr, size_t size) override {
  9764. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9765. if (pos >= data.size()) return 0;
  9766. size_t limit =
  9767. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9768. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9769. std::memcpy(ptr, data.data() + pos, to_read);
  9770. pos += to_read;
  9771. return static_cast<ssize_t>(to_read);
  9772. }
  9773. ssize_t write(const char *, size_t) override { return -1; }
  9774. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9775. ip = "127.0.0.1";
  9776. port = 0;
  9777. }
  9778. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9779. ip = "127.0.0.1";
  9780. port = 0;
  9781. }
  9782. socket_t socket() const override { return INVALID_SOCKET; }
  9783. time_t duration() const override { return 0; }
  9784. };
  9785. TEST(StreamHandleTest, Basic) {
  9786. ClientImpl::StreamHandle handle;
  9787. EXPECT_FALSE(handle.is_valid());
  9788. handle.response = detail::make_unique<Response>();
  9789. handle.error = Error::Connection;
  9790. EXPECT_FALSE(handle.is_valid());
  9791. handle.error = Error::Success;
  9792. EXPECT_TRUE(handle.is_valid());
  9793. }
  9794. TEST(BodyReaderTest, Basic) {
  9795. MockStream stream("Hello, World!");
  9796. detail::BodyReader reader;
  9797. reader.stream = &stream;
  9798. reader.content_length = 13;
  9799. char buf[32];
  9800. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9801. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9802. EXPECT_TRUE(reader.eof);
  9803. }
  9804. TEST(BodyReaderTest, NoStream) {
  9805. detail::BodyReader reader;
  9806. char buf[32];
  9807. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9808. EXPECT_EQ(Error::Connection, reader.last_error);
  9809. }
  9810. TEST(BodyReaderTest, Error) {
  9811. MockStream stream("Hello, World!", 5);
  9812. detail::BodyReader reader;
  9813. reader.stream = &stream;
  9814. reader.content_length = 13;
  9815. char buf[32];
  9816. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9817. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9818. EXPECT_EQ(Error::Read, reader.last_error);
  9819. }
  9820. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9821. // Mock-based StreamHandle tests relying on private internals are removed.
  9822. class OpenStreamTest : public ::testing::Test {
  9823. protected:
  9824. void SetUp() override {
  9825. svr_.Get("/hello", [](const Request &, Response &res) {
  9826. res.set_content("Hello World!", "text/plain");
  9827. });
  9828. svr_.Get("/large", [](const Request &, Response &res) {
  9829. res.set_content(std::string(10000, 'X'), "text/plain");
  9830. });
  9831. svr_.Get("/chunked", [](const Request &, Response &res) {
  9832. res.set_chunked_content_provider("text/plain",
  9833. [](size_t offset, DataSink &sink) {
  9834. if (offset < 15) {
  9835. sink.write("chunk", 5);
  9836. return true;
  9837. }
  9838. sink.done();
  9839. return true;
  9840. });
  9841. });
  9842. svr_.Get("/compressible", [](const Request &, Response &res) {
  9843. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9844. DataSink &sink) {
  9845. if (offset < 100 * 1024) {
  9846. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9847. sink.write(chunk.data(), chunk.size());
  9848. return true;
  9849. }
  9850. sink.done();
  9851. return true;
  9852. });
  9853. });
  9854. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9855. [](const Request & /*req*/, Response &res) {
  9856. auto i = new int(0);
  9857. res.set_header("Trailer", "Content-Length, X-Allowed");
  9858. res.set_chunked_content_provider(
  9859. "text/plain",
  9860. [i](size_t /*offset*/, DataSink &sink) {
  9861. switch (*i) {
  9862. case 0: sink.os << "123"; break;
  9863. case 1: sink.os << "456"; break;
  9864. case 2: sink.os << "789"; break;
  9865. case 3: {
  9866. sink.done_with_trailer(
  9867. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9868. } break;
  9869. }
  9870. (*i)++;
  9871. return true;
  9872. },
  9873. [i](bool success) {
  9874. EXPECT_TRUE(success);
  9875. delete i;
  9876. });
  9877. });
  9878. // Echo headers endpoint for header-related tests
  9879. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9880. std::string body;
  9881. for (const auto &h : req.headers) {
  9882. body.append(h.first);
  9883. body.push_back(':');
  9884. body.append(h.second);
  9885. body.push_back('\n');
  9886. }
  9887. res.set_content(body, "text/plain");
  9888. });
  9889. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9890. std::string body;
  9891. for (const auto &h : req.headers) {
  9892. body.append(h.first);
  9893. body.push_back(':');
  9894. body.append(h.second);
  9895. body.push_back('\n');
  9896. }
  9897. res.set_content(body, "text/plain");
  9898. });
  9899. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9900. svr_.wait_until_ready();
  9901. }
  9902. void TearDown() override {
  9903. svr_.stop();
  9904. if (thread_.joinable()) thread_.join();
  9905. }
  9906. Server svr_;
  9907. std::thread thread_;
  9908. };
  9909. TEST_F(OpenStreamTest, Basic) {
  9910. Client cli("127.0.0.1", 8787);
  9911. auto handle = cli.open_stream("GET", "/hello");
  9912. EXPECT_TRUE(handle.is_valid());
  9913. EXPECT_EQ("Hello World!", read_all(handle));
  9914. }
  9915. TEST_F(OpenStreamTest, SmallBuffer) {
  9916. Client cli("127.0.0.1", 8787);
  9917. auto handle = cli.open_stream("GET", "/hello");
  9918. std::string result;
  9919. char buf[4];
  9920. ssize_t n;
  9921. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9922. result.append(buf, static_cast<size_t>(n));
  9923. EXPECT_EQ("Hello World!", result);
  9924. }
  9925. TEST_F(OpenStreamTest, DefaultHeaders) {
  9926. Client cli("127.0.0.1", 8787);
  9927. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9928. {
  9929. auto handle = cli.open_stream("GET", "/echo-headers");
  9930. ASSERT_TRUE(handle.is_valid());
  9931. auto body = read_all(handle);
  9932. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  9933. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  9934. std::string::npos);
  9935. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  9936. }
  9937. // open_stream POST with body and no explicit content_type should NOT add
  9938. // text/plain Content-Type (behavior differs from non-streaming path), but
  9939. // should include Content-Length
  9940. {
  9941. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  9942. ASSERT_TRUE(handle.is_valid());
  9943. auto body = read_all(handle);
  9944. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  9945. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  9946. }
  9947. // open_stream POST with explicit Content-Type should preserve it
  9948. {
  9949. auto handle = cli.open_stream("POST", "/echo-headers", {},
  9950. {{"Content-Type", "application/custom"}},
  9951. "{}", "application/custom");
  9952. ASSERT_TRUE(handle.is_valid());
  9953. auto body = read_all(handle);
  9954. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  9955. }
  9956. // User-specified User-Agent must not be overwritten for stream API
  9957. {
  9958. auto handle = cli.open_stream("GET", "/echo-headers", {},
  9959. {{"User-Agent", "MyAgent/1.2"}});
  9960. ASSERT_TRUE(handle.is_valid());
  9961. auto body = read_all(handle);
  9962. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  9963. }
  9964. }
  9965. TEST_F(OpenStreamTest, Large) {
  9966. Client cli("127.0.0.1", 8787);
  9967. auto handle = cli.open_stream("GET", "/large");
  9968. EXPECT_EQ(10000u, read_all(handle).size());
  9969. }
  9970. TEST_F(OpenStreamTest, ConnectionError) {
  9971. Client cli("127.0.0.1", 9999);
  9972. auto handle = cli.open_stream("GET", "/hello");
  9973. EXPECT_FALSE(handle.is_valid());
  9974. }
  9975. TEST_F(OpenStreamTest, Chunked) {
  9976. Client cli("127.0.0.1", 8787);
  9977. auto handle = cli.open_stream("GET", "/chunked");
  9978. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  9979. "Transfer-Encoding") == "chunked");
  9980. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  9981. }
  9982. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  9983. Client cli("127.0.0.1", 8787);
  9984. auto handle =
  9985. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  9986. ASSERT_TRUE(handle.is_valid());
  9987. // Consume body to allow trailers to be received/parsed
  9988. auto body = read_all(handle);
  9989. // Explicitly parse trailers (ensure trailers are available for assertion)
  9990. handle.parse_trailers_if_needed();
  9991. EXPECT_EQ(std::string("123456789"), body);
  9992. // The response should include a Trailer header declaring both names
  9993. ASSERT_TRUE(handle.response);
  9994. EXPECT_TRUE(handle.response->has_header("Trailer"));
  9995. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  9996. handle.response->get_header_value("Trailer"));
  9997. // Prohibited trailer must not be present
  9998. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  9999. // Allowed trailer should be present
  10000. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10001. EXPECT_EQ(std::string("yes"),
  10002. handle.response->get_trailer_value("X-Allowed"));
  10003. // Verify trailers are NOT present as regular headers
  10004. EXPECT_EQ(std::string(""),
  10005. handle.response->get_header_value("Content-Length"));
  10006. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10007. }
  10008. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10009. TEST_F(OpenStreamTest, Gzip) {
  10010. Client cli("127.0.0.1", 8787);
  10011. auto handle = cli.open_stream("GET", "/compressible", {},
  10012. {{"Accept-Encoding", "gzip"}});
  10013. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10014. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10015. }
  10016. #endif
  10017. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10018. TEST_F(OpenStreamTest, Brotli) {
  10019. Client cli("127.0.0.1", 8787);
  10020. auto handle =
  10021. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10022. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10023. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10024. }
  10025. #endif
  10026. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10027. TEST_F(OpenStreamTest, Zstd) {
  10028. Client cli("127.0.0.1", 8787);
  10029. auto handle = cli.open_stream("GET", "/compressible", {},
  10030. {{"Accept-Encoding", "zstd"}});
  10031. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10032. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10033. }
  10034. #endif
  10035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10036. class SSLOpenStreamTest : public ::testing::Test {
  10037. protected:
  10038. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10039. void SetUp() override {
  10040. svr_.Get("/hello", [](const Request &, Response &res) {
  10041. res.set_content("Hello SSL World!", "text/plain");
  10042. });
  10043. svr_.Get("/chunked", [](const Request &, Response &res) {
  10044. res.set_chunked_content_provider("text/plain",
  10045. [](size_t offset, DataSink &sink) {
  10046. if (offset < 15) {
  10047. sink.write("chunk", 5);
  10048. return true;
  10049. }
  10050. sink.done();
  10051. return true;
  10052. });
  10053. });
  10054. svr_.Post("/echo", [](const Request &req, Response &res) {
  10055. res.set_content(req.body, req.get_header_value("Content-Type"));
  10056. });
  10057. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10058. std::string body = req.body;
  10059. res.set_chunked_content_provider(
  10060. "text/plain", [body](size_t offset, DataSink &sink) {
  10061. if (offset < body.size()) {
  10062. sink.write(body.data() + offset, body.size() - offset);
  10063. }
  10064. sink.done();
  10065. return true;
  10066. });
  10067. });
  10068. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10069. svr_.wait_until_ready();
  10070. }
  10071. void TearDown() override {
  10072. svr_.stop();
  10073. if (thread_.joinable()) thread_.join();
  10074. }
  10075. SSLServer svr_;
  10076. std::thread thread_;
  10077. };
  10078. TEST_F(SSLOpenStreamTest, Basic) {
  10079. SSLClient cli("127.0.0.1", 8788);
  10080. cli.enable_server_certificate_verification(false);
  10081. auto handle = cli.open_stream("GET", "/hello");
  10082. ASSERT_TRUE(handle.is_valid());
  10083. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10084. }
  10085. TEST_F(SSLOpenStreamTest, Chunked) {
  10086. SSLClient cli("127.0.0.1", 8788);
  10087. cli.enable_server_certificate_verification(false);
  10088. auto handle = cli.open_stream("GET", "/chunked");
  10089. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10090. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10091. "Transfer-Encoding") == "chunked");
  10092. auto body = read_all(handle);
  10093. EXPECT_EQ("chunkchunkchunk", body);
  10094. }
  10095. TEST_F(SSLOpenStreamTest, Post) {
  10096. SSLClient cli("127.0.0.1", 8788);
  10097. cli.enable_server_certificate_verification(false);
  10098. auto handle =
  10099. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10100. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10101. EXPECT_EQ(200, handle.response->status);
  10102. auto body = read_all(handle);
  10103. EXPECT_EQ("Hello SSL POST", body);
  10104. }
  10105. TEST_F(SSLOpenStreamTest, PostChunked) {
  10106. SSLClient cli("127.0.0.1", 8788);
  10107. cli.enable_server_certificate_verification(false);
  10108. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10109. "Chunked SSL Data", "text/plain");
  10110. ASSERT_TRUE(handle.is_valid());
  10111. EXPECT_EQ(200, handle.response->status);
  10112. auto body = read_all(handle);
  10113. EXPECT_EQ("Chunked SSL Data", body);
  10114. }
  10115. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10116. //==============================================================================
  10117. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10118. // results for various scenarios.
  10119. //==============================================================================
  10120. TEST(ParityTest, GetVsOpenStream) {
  10121. Server svr;
  10122. const std::string path = "/parity";
  10123. const std::string content = "Parity test content: hello world";
  10124. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10125. res.set_content(content, "text/plain");
  10126. });
  10127. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10128. auto se = detail::scope_exit([&] {
  10129. svr.stop();
  10130. t.join();
  10131. ASSERT_FALSE(svr.is_running());
  10132. });
  10133. svr.wait_until_ready();
  10134. Client cli(HOST, PORT);
  10135. // Non-stream path
  10136. auto r1 = cli.Get(path);
  10137. ASSERT_TRUE(r1);
  10138. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10139. // Stream path
  10140. auto h = cli.open_stream("GET", path);
  10141. ASSERT_TRUE(h.is_valid());
  10142. EXPECT_EQ(r1->body, read_all(h));
  10143. }
  10144. // Helper to compress data with provided compressor type T
  10145. template <typename Compressor>
  10146. static std::string compress_payload_for_parity(const std::string &in) {
  10147. std::string out;
  10148. Compressor compressor;
  10149. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10150. [&](const char *data, size_t n) {
  10151. out.append(data, n);
  10152. return true;
  10153. });
  10154. EXPECT_TRUE(ok);
  10155. return out;
  10156. }
  10157. // Helper function for compression parity tests
  10158. template <typename Compressor>
  10159. static void test_compression_parity(const std::string &original,
  10160. const std::string &path,
  10161. const std::string &encoding) {
  10162. const std::string compressed =
  10163. compress_payload_for_parity<Compressor>(original);
  10164. Server svr;
  10165. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10166. res.set_content(compressed, "application/octet-stream");
  10167. res.set_header("Content-Encoding", encoding);
  10168. });
  10169. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10170. auto se = detail::scope_exit([&] {
  10171. svr.stop();
  10172. t.join();
  10173. ASSERT_FALSE(svr.is_running());
  10174. });
  10175. svr.wait_until_ready();
  10176. Client cli("localhost", 1234);
  10177. // Non-streaming
  10178. {
  10179. auto res = cli.Get(path);
  10180. ASSERT_TRUE(res);
  10181. EXPECT_EQ(StatusCode::OK_200, res->status);
  10182. EXPECT_EQ(original, res->body);
  10183. }
  10184. // Streaming
  10185. {
  10186. auto h = cli.open_stream("GET", path);
  10187. ASSERT_TRUE(h.is_valid());
  10188. EXPECT_EQ(original, read_all(h));
  10189. }
  10190. }
  10191. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10192. TEST(ParityTest, Gzip) {
  10193. test_compression_parity<detail::gzip_compressor>(
  10194. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10195. }
  10196. #endif
  10197. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10198. TEST(ParityTest, Brotli) {
  10199. test_compression_parity<detail::brotli_compressor>(
  10200. "Hello, brotli parity test payload", "/parity-br", "br");
  10201. }
  10202. #endif
  10203. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10204. TEST(ParityTest, Zstd) {
  10205. test_compression_parity<detail::zstd_compressor>(
  10206. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10207. }
  10208. #endif
  10209. //==============================================================================
  10210. // New Stream API Tests
  10211. //==============================================================================
  10212. inline std::string read_body(httplib::stream::Result &result) {
  10213. std::string body;
  10214. while (result.next()) {
  10215. body.append(result.data(), result.size());
  10216. }
  10217. return body;
  10218. }
  10219. TEST(ClientConnectionTest, Basic) {
  10220. httplib::ClientConnection conn;
  10221. EXPECT_FALSE(conn.is_open());
  10222. conn.sock = 1;
  10223. EXPECT_TRUE(conn.is_open());
  10224. httplib::ClientConnection conn2(std::move(conn));
  10225. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10226. conn2.sock = INVALID_SOCKET;
  10227. }
  10228. // Unified test server for all stream::* tests
  10229. class StreamApiTest : public ::testing::Test {
  10230. protected:
  10231. void SetUp() override {
  10232. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10233. res.set_content("Hello World!", "text/plain");
  10234. });
  10235. svr_.Get("/echo-params",
  10236. [](const httplib::Request &req, httplib::Response &res) {
  10237. std::string r;
  10238. for (const auto &p : req.params) {
  10239. if (!r.empty()) r += "&";
  10240. r += p.first + "=" + p.second;
  10241. }
  10242. res.set_content(r, "text/plain");
  10243. });
  10244. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10245. res.set_content(req.body, req.get_header_value("Content-Type"));
  10246. });
  10247. svr_.Post("/echo-headers",
  10248. [](const httplib::Request &req, httplib::Response &res) {
  10249. std::string r;
  10250. for (const auto &h : req.headers)
  10251. r += h.first + ": " + h.second + "\n";
  10252. res.set_content(r, "text/plain");
  10253. });
  10254. svr_.Post("/echo-params",
  10255. [](const httplib::Request &req, httplib::Response &res) {
  10256. std::string r = "params:";
  10257. for (const auto &p : req.params)
  10258. r += p.first + "=" + p.second + ";";
  10259. res.set_content(r + " body:" + req.body, "text/plain");
  10260. });
  10261. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10262. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10263. });
  10264. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10265. res.set_content("PUT:" + req.body, "text/plain");
  10266. });
  10267. svr_.Patch("/echo",
  10268. [](const httplib::Request &req, httplib::Response &res) {
  10269. res.set_content("PATCH:" + req.body, "text/plain");
  10270. });
  10271. svr_.Delete(
  10272. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10273. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10274. "text/plain");
  10275. });
  10276. svr_.Get("/head-test",
  10277. [](const httplib::Request &, httplib::Response &res) {
  10278. res.set_content("body for HEAD", "text/plain");
  10279. });
  10280. svr_.Options("/options",
  10281. [](const httplib::Request &, httplib::Response &res) {
  10282. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10283. });
  10284. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10285. svr_.wait_until_ready();
  10286. }
  10287. void TearDown() override {
  10288. svr_.stop();
  10289. if (thread_.joinable()) thread_.join();
  10290. }
  10291. httplib::Server svr_;
  10292. std::thread thread_;
  10293. };
  10294. // stream::Get tests
  10295. TEST_F(StreamApiTest, GetBasic) {
  10296. httplib::Client cli("localhost", 8790);
  10297. auto result = httplib::stream::Get(cli, "/hello");
  10298. ASSERT_TRUE(result.is_valid());
  10299. EXPECT_EQ(200, result.status());
  10300. EXPECT_EQ("Hello World!", read_body(result));
  10301. }
  10302. TEST_F(StreamApiTest, GetWithParams) {
  10303. httplib::Client cli("localhost", 8790);
  10304. httplib::Params params{{"foo", "bar"}};
  10305. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10306. ASSERT_TRUE(result.is_valid());
  10307. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10308. }
  10309. TEST_F(StreamApiTest, GetConnectionError) {
  10310. httplib::Client cli("localhost", 9999);
  10311. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10312. }
  10313. TEST_F(StreamApiTest, Get404) {
  10314. httplib::Client cli("localhost", 8790);
  10315. auto result = httplib::stream::Get(cli, "/nonexistent");
  10316. EXPECT_TRUE(result.is_valid());
  10317. EXPECT_EQ(404, result.status());
  10318. }
  10319. // stream::Post tests
  10320. TEST_F(StreamApiTest, PostBasic) {
  10321. httplib::Client cli("localhost", 8790);
  10322. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10323. "application/json");
  10324. ASSERT_TRUE(result.is_valid());
  10325. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10326. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10327. }
  10328. TEST_F(StreamApiTest, PostWithHeaders) {
  10329. httplib::Client cli("localhost", 8790);
  10330. httplib::Headers headers{{"X-Custom", "value"}};
  10331. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10332. "text/plain");
  10333. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10334. }
  10335. TEST_F(StreamApiTest, PostWithParams) {
  10336. httplib::Client cli("localhost", 8790);
  10337. httplib::Params params{{"k", "v"}};
  10338. auto result =
  10339. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10340. auto body = read_body(result);
  10341. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10342. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10343. }
  10344. TEST_F(StreamApiTest, PostLarge) {
  10345. httplib::Client cli("localhost", 8790);
  10346. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10347. size_t total = 0;
  10348. while (result.next()) {
  10349. total += result.size();
  10350. }
  10351. EXPECT_EQ(100u * 1024u, total);
  10352. }
  10353. // stream::Put/Patch tests
  10354. TEST_F(StreamApiTest, PutAndPatch) {
  10355. httplib::Client cli("localhost", 8790);
  10356. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10357. EXPECT_EQ("PUT:test", read_body(put));
  10358. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10359. EXPECT_EQ("PATCH:test", read_body(patch));
  10360. }
  10361. // stream::Delete tests
  10362. TEST_F(StreamApiTest, Delete) {
  10363. httplib::Client cli("localhost", 8790);
  10364. auto del1 = httplib::stream::Delete(cli, "/resource");
  10365. EXPECT_EQ("Deleted", read_body(del1));
  10366. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10367. EXPECT_EQ("Deleted:data", read_body(del2));
  10368. }
  10369. // stream::Head/Options tests
  10370. TEST_F(StreamApiTest, HeadAndOptions) {
  10371. httplib::Client cli("localhost", 8790);
  10372. auto head = httplib::stream::Head(cli, "/head-test");
  10373. EXPECT_TRUE(head.is_valid());
  10374. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10375. auto opts = httplib::stream::Options(cli, "/options");
  10376. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10377. }
  10378. // SSL stream::* tests
  10379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10380. class SSLStreamApiTest : public ::testing::Test {
  10381. protected:
  10382. void SetUp() override {
  10383. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10384. res.set_content("Hello SSL!", "text/plain");
  10385. });
  10386. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10387. res.set_content(req.body, "text/plain");
  10388. });
  10389. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10390. svr_.wait_until_ready();
  10391. }
  10392. void TearDown() override {
  10393. svr_.stop();
  10394. if (thread_.joinable()) thread_.join();
  10395. }
  10396. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10397. std::thread thread_;
  10398. };
  10399. TEST_F(SSLStreamApiTest, GetAndPost) {
  10400. httplib::SSLClient cli("127.0.0.1", 8803);
  10401. cli.enable_server_certificate_verification(false);
  10402. auto get = httplib::stream::Get(cli, "/hello");
  10403. EXPECT_EQ("Hello SSL!", read_body(get));
  10404. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10405. EXPECT_EQ("test", read_body(post));
  10406. }
  10407. #endif
  10408. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10409. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10410. // BodyReader
  10411. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10412. // Test that read timeout during streaming is detected
  10413. // Use a large content-length response where server delays mid-stream
  10414. Server svr;
  10415. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10416. // Send a large response with delay in the middle
  10417. res.set_content_provider(
  10418. 1000, // content_length
  10419. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10420. if (offset < 100) {
  10421. // Send first 100 bytes immediately
  10422. std::string data(100, 'A');
  10423. sink.write(data.c_str(), data.size());
  10424. return true;
  10425. }
  10426. // Then delay longer than client timeout
  10427. std::this_thread::sleep_for(std::chrono::seconds(3));
  10428. std::string data(900, 'B');
  10429. sink.write(data.c_str(), data.size());
  10430. return true;
  10431. });
  10432. });
  10433. auto port = 8091;
  10434. std::thread t([&]() { svr.listen("localhost", port); });
  10435. svr.wait_until_ready();
  10436. Client cli("localhost", port);
  10437. cli.set_read_timeout(1, 0); // 1 second timeout
  10438. auto handle = cli.open_stream("GET", "/slow-stream");
  10439. ASSERT_TRUE(handle.is_valid());
  10440. char buf[256];
  10441. ssize_t total = 0;
  10442. ssize_t n;
  10443. bool got_error = false;
  10444. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10445. total += n;
  10446. }
  10447. if (n < 0) {
  10448. got_error = true;
  10449. // Should be timeout or read error
  10450. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10451. handle.get_read_error() == Error::Read)
  10452. << "Actual error: " << to_string(handle.get_read_error());
  10453. }
  10454. // Either we got an error, or we got less data than expected
  10455. EXPECT_TRUE(got_error || total < 1000)
  10456. << "Expected timeout but got all " << total << " bytes";
  10457. svr.stop();
  10458. t.join();
  10459. }
  10460. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10461. // Test connection closed detection via BodyReader
  10462. Server svr;
  10463. std::atomic<bool> close_now{false};
  10464. svr.Get("/will-close", [&](const Request &, Response &res) {
  10465. res.set_content_provider(
  10466. 10000, // Large content_length that we won't fully send
  10467. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10468. if (offset < 100) {
  10469. std::string data(100, 'X');
  10470. sink.write(data.c_str(), data.size());
  10471. return true;
  10472. }
  10473. // Wait for signal then abort
  10474. while (!close_now) {
  10475. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10476. }
  10477. return false; // Abort - server will close connection
  10478. });
  10479. });
  10480. auto port = 8092;
  10481. std::thread t([&]() { svr.listen("localhost", port); });
  10482. svr.wait_until_ready();
  10483. Client cli("localhost", port);
  10484. auto handle = cli.open_stream("GET", "/will-close");
  10485. ASSERT_TRUE(handle.is_valid());
  10486. char buf[256];
  10487. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10488. EXPECT_GT(n, 0) << "First read should succeed";
  10489. // Signal server to close
  10490. close_now = true;
  10491. // Keep reading until error or EOF
  10492. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10493. // Keep reading
  10494. }
  10495. // Should get an error since content_length wasn't satisfied
  10496. if (n < 0) {
  10497. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10498. handle.get_read_error() == Error::Read)
  10499. << "Actual error: " << to_string(handle.get_read_error());
  10500. }
  10501. svr.stop();
  10502. t.join();
  10503. }
  10504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10505. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10506. // Test that read timeout during SSL streaming is detected
  10507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10508. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10509. res.set_content_provider(
  10510. 1000, "text/plain",
  10511. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10512. if (offset < 100) {
  10513. std::string data(100, 'A');
  10514. sink.write(data.c_str(), data.size());
  10515. return true;
  10516. }
  10517. std::this_thread::sleep_for(std::chrono::seconds(3));
  10518. std::string data(900, 'B');
  10519. sink.write(data.c_str(), data.size());
  10520. return true;
  10521. });
  10522. });
  10523. auto port = 8093;
  10524. std::thread t([&]() { svr.listen("localhost", port); });
  10525. svr.wait_until_ready();
  10526. SSLClient cli("localhost", port);
  10527. cli.enable_server_certificate_verification(false);
  10528. cli.set_read_timeout(1, 0); // 1 second timeout
  10529. auto handle = cli.open_stream("GET", "/slow-stream");
  10530. ASSERT_TRUE(handle.is_valid());
  10531. char buf[256];
  10532. ssize_t total = 0;
  10533. ssize_t n;
  10534. bool got_error = false;
  10535. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10536. total += n;
  10537. }
  10538. if (n < 0) {
  10539. got_error = true;
  10540. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10541. handle.get_read_error() == Error::Read)
  10542. << "Actual error: " << to_string(handle.get_read_error());
  10543. }
  10544. EXPECT_TRUE(got_error || total < 1000)
  10545. << "Expected timeout but got all " << total << " bytes";
  10546. svr.stop();
  10547. t.join();
  10548. }
  10549. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10550. // Test SSL connection closed detection
  10551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10552. std::atomic<bool> close_now{false};
  10553. svr.Get("/will-close", [&](const Request &, Response &res) {
  10554. res.set_content_provider(
  10555. 10000, "text/plain",
  10556. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10557. if (offset < 100) {
  10558. std::string data(100, 'X');
  10559. sink.write(data.c_str(), data.size());
  10560. return true;
  10561. }
  10562. while (!close_now) {
  10563. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10564. }
  10565. return false;
  10566. });
  10567. });
  10568. auto port = 8094;
  10569. std::thread t([&]() { svr.listen("localhost", port); });
  10570. svr.wait_until_ready();
  10571. SSLClient cli("localhost", port);
  10572. cli.enable_server_certificate_verification(false);
  10573. auto handle = cli.open_stream("GET", "/will-close");
  10574. ASSERT_TRUE(handle.is_valid());
  10575. char buf[256];
  10576. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10577. EXPECT_GT(n, 0);
  10578. // Signal server to close
  10579. close_now = true;
  10580. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10581. // Keep reading
  10582. }
  10583. if (n < 0) {
  10584. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10585. handle.get_read_error() == Error::Read)
  10586. << "Actual error: " << to_string(handle.get_read_error());
  10587. }
  10588. svr.stop();
  10589. t.join();
  10590. }
  10591. #endif
  10592. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10593. using namespace httplib;
  10594. // Create a test file
  10595. const char *fname = "etag_testfile.txt";
  10596. const char *content = "etag-content";
  10597. {
  10598. std::ofstream ofs(fname);
  10599. ofs << content;
  10600. ASSERT_TRUE(ofs.good());
  10601. }
  10602. Server svr;
  10603. svr.set_mount_point("/static", ".");
  10604. auto t = std::thread([&]() { svr.listen("localhost", 8087); });
  10605. svr.wait_until_ready();
  10606. Client cli("localhost", 8087);
  10607. // First request: should get 200 with ETag header
  10608. auto res1 = cli.Get("/static/etag_testfile.txt");
  10609. ASSERT_TRUE(res1);
  10610. ASSERT_EQ(200, res1->status);
  10611. ASSERT_TRUE(res1->has_header("ETag"));
  10612. std::string etag = res1->get_header_value("ETag");
  10613. EXPECT_FALSE(etag.empty());
  10614. // Verify ETag format: W/"hex-hex"
  10615. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10616. EXPECT_EQ('W', etag[0]);
  10617. EXPECT_EQ('/', etag[1]);
  10618. EXPECT_EQ('"', etag[2]);
  10619. EXPECT_EQ('"', etag.back());
  10620. // Exact match: expect 304 Not Modified
  10621. Headers h2 = {{"If-None-Match", etag}};
  10622. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10623. ASSERT_TRUE(res2);
  10624. EXPECT_EQ(304, res2->status);
  10625. // Wildcard match: expect 304 Not Modified
  10626. Headers h3 = {{"If-None-Match", "*"}};
  10627. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10628. ASSERT_TRUE(res3);
  10629. EXPECT_EQ(304, res3->status);
  10630. // Non-matching ETag: expect 200
  10631. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10632. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10633. ASSERT_TRUE(res4);
  10634. EXPECT_EQ(200, res4->status);
  10635. // Multiple ETags with one matching: expect 304
  10636. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10637. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10638. ASSERT_TRUE(res5);
  10639. EXPECT_EQ(304, res5->status);
  10640. svr.stop();
  10641. t.join();
  10642. std::remove(fname);
  10643. }
  10644. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10645. using namespace httplib;
  10646. Server svr;
  10647. svr.set_mount_point("/static", ".");
  10648. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10649. svr.wait_until_ready();
  10650. Client cli("localhost", 8090);
  10651. // Send If-None-Match: * to a non-existent file
  10652. Headers h = {{"If-None-Match", "*"}};
  10653. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10654. ASSERT_TRUE(res);
  10655. EXPECT_EQ(404, res->status);
  10656. svr.stop();
  10657. t.join();
  10658. }
  10659. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10660. using namespace httplib;
  10661. // Create a test file
  10662. const char *fname = "ims_testfile.txt";
  10663. const char *content = "if-modified-since-test";
  10664. {
  10665. std::ofstream ofs(fname);
  10666. ofs << content;
  10667. ASSERT_TRUE(ofs.good());
  10668. }
  10669. Server svr;
  10670. svr.set_mount_point("/static", ".");
  10671. auto t = std::thread([&]() { svr.listen("localhost", 8088); });
  10672. svr.wait_until_ready();
  10673. Client cli("localhost", 8088);
  10674. // First request: should get 200 with Last-Modified header
  10675. auto res1 = cli.Get("/static/ims_testfile.txt");
  10676. ASSERT_TRUE(res1);
  10677. ASSERT_EQ(200, res1->status);
  10678. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10679. std::string last_modified = res1->get_header_value("Last-Modified");
  10680. EXPECT_FALSE(last_modified.empty());
  10681. // If-Modified-Since with same time: expect 304
  10682. Headers h2 = {{"If-Modified-Since", last_modified}};
  10683. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10684. ASSERT_TRUE(res2);
  10685. EXPECT_EQ(304, res2->status);
  10686. // If-Modified-Since with future time: expect 304
  10687. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10688. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10689. ASSERT_TRUE(res3);
  10690. EXPECT_EQ(304, res3->status);
  10691. // If-Modified-Since with past time: expect 200
  10692. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10693. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10694. ASSERT_TRUE(res4);
  10695. EXPECT_EQ(200, res4->status);
  10696. // If-None-Match takes precedence over If-Modified-Since
  10697. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10698. ASSERT_TRUE(res1->has_header("ETag"));
  10699. std::string etag = res1->get_header_value("ETag");
  10700. Headers h5 = {{"If-None-Match", etag},
  10701. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10702. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10703. ASSERT_TRUE(res5);
  10704. EXPECT_EQ(304, res5->status);
  10705. svr.stop();
  10706. t.join();
  10707. std::remove(fname);
  10708. }
  10709. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10710. using namespace httplib;
  10711. Server svr;
  10712. // Endpoint that returns compressible content
  10713. svr.Get("/compressible", [](const Request &, Response &res) {
  10714. // Return a large enough body to trigger compression
  10715. std::string body(1000, 'a');
  10716. res.set_content(body, "text/plain");
  10717. });
  10718. auto t = std::thread([&]() { svr.listen("localhost", 8089); });
  10719. svr.wait_until_ready();
  10720. Client cli("localhost", 8089);
  10721. // Request with gzip support: should get Vary header when compressed
  10722. cli.set_compress(true);
  10723. auto res1 = cli.Get("/compressible");
  10724. ASSERT_TRUE(res1);
  10725. EXPECT_EQ(200, res1->status);
  10726. // If Content-Encoding is set, Vary should also be set
  10727. if (res1->has_header("Content-Encoding")) {
  10728. EXPECT_TRUE(res1->has_header("Vary"));
  10729. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10730. }
  10731. // Request without Accept-Encoding header: should not have compression
  10732. Headers h_no_compress;
  10733. auto res2 = cli.Get("/compressible", h_no_compress);
  10734. ASSERT_TRUE(res2);
  10735. EXPECT_EQ(200, res2->status);
  10736. // Verify Vary header is present when compression is applied
  10737. // (the exact behavior depends on server configuration)
  10738. svr.stop();
  10739. t.join();
  10740. }
  10741. TEST(ETagTest, IfRangeWithETag) {
  10742. using namespace httplib;
  10743. // Create a test file with known content
  10744. const char *fname = "if_range_testfile.txt";
  10745. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10746. {
  10747. std::ofstream ofs(fname);
  10748. ofs << content;
  10749. ASSERT_TRUE(ofs.good());
  10750. }
  10751. Server svr;
  10752. svr.set_mount_point("/static", ".");
  10753. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10754. svr.wait_until_ready();
  10755. Client cli("localhost", 8090);
  10756. // First request: get ETag
  10757. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10758. ASSERT_TRUE(res1);
  10759. ASSERT_EQ(200, res1->status);
  10760. ASSERT_TRUE(res1->has_header("ETag"));
  10761. std::string etag = res1->get_header_value("ETag");
  10762. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10763. // Since our server generates weak ETags (W/"..."), If-Range with our
  10764. // ETag should NOT result in partial content - it should return full content.
  10765. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10766. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10767. ASSERT_TRUE(res2);
  10768. // Weak ETag in If-Range -> full content (200), not partial (206)
  10769. EXPECT_EQ(200, res2->status);
  10770. EXPECT_EQ(content, res2->body);
  10771. EXPECT_FALSE(res2->has_header("Content-Range"));
  10772. // Range request with non-matching If-Range (ETag): should get 200 (full
  10773. // content)
  10774. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10775. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10776. ASSERT_TRUE(res3);
  10777. EXPECT_EQ(200, res3->status);
  10778. EXPECT_EQ(content, res3->body);
  10779. EXPECT_FALSE(res3->has_header("Content-Range"));
  10780. // Range request with strong ETag (hypothetical - our server doesn't generate
  10781. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10782. // should return full content)
  10783. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10784. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10785. ASSERT_TRUE(res4);
  10786. EXPECT_EQ(200, res4->status);
  10787. EXPECT_EQ(content, res4->body);
  10788. EXPECT_FALSE(res4->has_header("Content-Range"));
  10789. svr.stop();
  10790. t.join();
  10791. std::remove(fname);
  10792. }
  10793. TEST(ETagTest, IfRangeWithDate) {
  10794. using namespace httplib;
  10795. // Create a test file
  10796. const char *fname = "if_range_date_testfile.txt";
  10797. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10798. {
  10799. std::ofstream ofs(fname);
  10800. ofs << content;
  10801. ASSERT_TRUE(ofs.good());
  10802. }
  10803. Server svr;
  10804. svr.set_mount_point("/static", ".");
  10805. auto t = std::thread([&]() { svr.listen("localhost", 8091); });
  10806. svr.wait_until_ready();
  10807. Client cli("localhost", 8091);
  10808. // First request: get Last-Modified
  10809. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10810. ASSERT_TRUE(res1);
  10811. ASSERT_EQ(200, res1->status);
  10812. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10813. std::string last_modified = res1->get_header_value("Last-Modified");
  10814. // Range request with matching If-Range (date): should get 206
  10815. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10816. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10817. ASSERT_TRUE(res2);
  10818. EXPECT_EQ(206, res2->status);
  10819. EXPECT_EQ("FGHIJ", res2->body);
  10820. // Range request with old If-Range date: should get 200 (full content)
  10821. Headers h3 = {{"Range", "bytes=5-9"},
  10822. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10823. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10824. ASSERT_TRUE(res3);
  10825. EXPECT_EQ(200, res3->status);
  10826. EXPECT_EQ(content, res3->body);
  10827. // Range request with future If-Range date: should get 206
  10828. Headers h4 = {{"Range", "bytes=0-4"},
  10829. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10830. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10831. ASSERT_TRUE(res4);
  10832. EXPECT_EQ(206, res4->status);
  10833. EXPECT_EQ("ABCDE", res4->body);
  10834. svr.stop();
  10835. t.join();
  10836. std::remove(fname);
  10837. }
  10838. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10839. using namespace httplib;
  10840. const char *fname = "etag_malformed.txt";
  10841. const char *content = "malformed-etag";
  10842. {
  10843. std::ofstream ofs(fname);
  10844. ofs << content;
  10845. ASSERT_TRUE(ofs.good());
  10846. }
  10847. Server svr;
  10848. svr.set_mount_point("/static", ".");
  10849. auto t = std::thread([&]() { svr.listen("localhost", 8092); });
  10850. svr.wait_until_ready();
  10851. Client cli("localhost", 8092);
  10852. // baseline: should get 200 and an ETag
  10853. auto res1 = cli.Get("/static/etag_malformed.txt");
  10854. ASSERT_TRUE(res1);
  10855. ASSERT_EQ(200, res1->status);
  10856. ASSERT_TRUE(res1->has_header("ETag"));
  10857. // Malformed ETag value (missing quotes) should be treated as non-matching
  10858. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10859. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10860. ASSERT_TRUE(res_bad);
  10861. EXPECT_EQ(200, res_bad->status);
  10862. // Whitespace-only header value should be considered invalid / non-matching
  10863. Headers h_space = {{"If-None-Match", " "}};
  10864. auto res_space = cli.Get("/static/etag_malformed.txt", h_space);
  10865. ASSERT_TRUE(res_space);
  10866. EXPECT_EQ(200, res_space->status);
  10867. svr.stop();
  10868. t.join();
  10869. std::remove(fname);
  10870. }
  10871. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10872. using namespace httplib;
  10873. const char *fname = "ims_invalid_format.txt";
  10874. const char *content = "ims-bad-format";
  10875. {
  10876. std::ofstream ofs(fname);
  10877. ofs << content;
  10878. ASSERT_TRUE(ofs.good());
  10879. }
  10880. Server svr;
  10881. svr.set_mount_point("/static", ".");
  10882. auto t = std::thread([&]() { svr.listen("localhost", 8093); });
  10883. svr.wait_until_ready();
  10884. Client cli("localhost", 8093);
  10885. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10886. ASSERT_TRUE(res1);
  10887. ASSERT_EQ(200, res1->status);
  10888. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10889. // If-Modified-Since with invalid format should not result in 304
  10890. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  10891. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  10892. ASSERT_TRUE(res_bad);
  10893. EXPECT_EQ(200, res_bad->status);
  10894. // If-Range with invalid date format should be treated as mismatch -> full
  10895. // content (200)
  10896. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  10897. {"If-Range", "invalid-date"}};
  10898. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  10899. ASSERT_TRUE(res_ifrange);
  10900. EXPECT_EQ(200, res_ifrange->status);
  10901. svr.stop();
  10902. t.join();
  10903. std::remove(fname);
  10904. }
  10905. TEST(ETagTest, IfRangeWithMalformedETag) {
  10906. using namespace httplib;
  10907. const char *fname = "ifrange_malformed.txt";
  10908. const std::string content = "0123456789";
  10909. {
  10910. std::ofstream ofs(fname);
  10911. ofs << content;
  10912. ASSERT_TRUE(ofs.good());
  10913. }
  10914. Server svr;
  10915. svr.set_mount_point("/static", ".");
  10916. auto t = std::thread([&]() { svr.listen("localhost", 8094); });
  10917. svr.wait_until_ready();
  10918. Client cli("localhost", 8094);
  10919. // First request: get ETag
  10920. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  10921. ASSERT_TRUE(res1);
  10922. ASSERT_EQ(200, res1->status);
  10923. ASSERT_TRUE(res1->has_header("ETag"));
  10924. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  10925. // full content (200)
  10926. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  10927. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  10928. ASSERT_TRUE(res2);
  10929. EXPECT_EQ(200, res2->status);
  10930. EXPECT_EQ(content, res2->body);
  10931. svr.stop();
  10932. t.join();
  10933. std::remove(fname);
  10934. }
  10935. TEST(ETagTest, ExtremeLargeDateValues) {
  10936. using namespace httplib;
  10937. const char *fname = "ims_extreme_date.txt";
  10938. const char *content = "ims-extreme-date";
  10939. {
  10940. std::ofstream ofs(fname);
  10941. ofs << content;
  10942. ASSERT_TRUE(ofs.good());
  10943. }
  10944. Server svr;
  10945. svr.set_mount_point("/static", ".");
  10946. auto t = std::thread([&]() { svr.listen("localhost", 8095); });
  10947. svr.wait_until_ready();
  10948. Client cli("localhost", 8095);
  10949. auto res1 = cli.Get(std::string("/static/") + fname);
  10950. ASSERT_TRUE(res1);
  10951. ASSERT_EQ(200, res1->status);
  10952. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10953. // Extremely large year that may overflow date parsing routines.
  10954. Headers h_large_date = {
  10955. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  10956. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  10957. ASSERT_TRUE(res_bad);
  10958. // Expect server to treat this as invalid/mismatch and return full content
  10959. EXPECT_EQ(200, res_bad->status);
  10960. // If-Range with extremely large date should be treated as mismatch -> full
  10961. // content (200)
  10962. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  10963. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  10964. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  10965. ASSERT_TRUE(res_ifrange);
  10966. EXPECT_EQ(200, res_ifrange->status);
  10967. svr.stop();
  10968. t.join();
  10969. std::remove(fname);
  10970. }
  10971. TEST(ETagTest, NegativeFileModificationTime) {
  10972. using namespace httplib;
  10973. const char *fname = "ims_negative_mtime.txt";
  10974. const std::string content = "negative-mtime";
  10975. {
  10976. std::ofstream ofs(fname);
  10977. ofs << content;
  10978. ASSERT_TRUE(ofs.good());
  10979. }
  10980. // Try to set file mtime to a negative value. This may fail on some
  10981. // platforms/filesystems; if it fails, the test will still verify server
  10982. // behaves safely by performing a regular conditional request.
  10983. #if defined(__APPLE__) || defined(__linux__)
  10984. bool set_negative = false;
  10985. do {
  10986. struct timeval times[2];
  10987. // access time: now
  10988. times[0].tv_sec = time(nullptr);
  10989. times[0].tv_usec = 0;
  10990. // modification time: negative (e.g., -1)
  10991. times[1].tv_sec = -1;
  10992. times[1].tv_usec = 0;
  10993. if (utimes(fname, times) == 0) { set_negative = true; }
  10994. } while (0);
  10995. #else
  10996. bool set_negative = false;
  10997. #endif
  10998. Server svr;
  10999. svr.set_mount_point("/static", ".");
  11000. auto t = std::thread([&]() { svr.listen("localhost", 8096); });
  11001. svr.wait_until_ready();
  11002. Client cli("localhost", 8096);
  11003. auto res1 = cli.Get(std::string("/static/") + fname);
  11004. ASSERT_TRUE(res1);
  11005. ASSERT_EQ(200, res1->status);
  11006. bool has_last_modified = res1->has_header("Last-Modified");
  11007. std::string last_modified;
  11008. if (has_last_modified) {
  11009. last_modified = res1->get_header_value("Last-Modified");
  11010. }
  11011. if (set_negative) {
  11012. // If we successfully set a negative mtime, ensure server returns a
  11013. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11014. // with an old date and ensure server handles it without crash.
  11015. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11016. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11017. ASSERT_TRUE(res2);
  11018. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11019. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11020. } else {
  11021. // Could not set negative mtime on this platform; fall back to verifying
  11022. // that normal invalid/malformed dates are treated safely (non-304).
  11023. Headers h_bad_date = {
  11024. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11025. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11026. ASSERT_TRUE(res_bad);
  11027. EXPECT_EQ(200, res_bad->status);
  11028. }
  11029. svr.stop();
  11030. t.join();
  11031. std::remove(fname);
  11032. }