test.cc 439 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) {
  74. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  75. return;
  76. #else
  77. throw std::runtime_error("File not found: " + path);
  78. #endif
  79. }
  80. fs.seekg(0, std::ios_base::end);
  81. auto size = fs.tellg();
  82. fs.seekg(0);
  83. out.resize(static_cast<size_t>(size));
  84. fs.read(&out[0], static_cast<std::streamsize>(size));
  85. }
  86. void performance_test(const char *host) {
  87. Server svr;
  88. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  89. res.set_content("Benchmark Response", "text/plain");
  90. });
  91. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  92. auto se = detail::scope_exit([&] {
  93. svr.stop();
  94. listen_thread.join();
  95. ASSERT_FALSE(svr.is_running());
  96. });
  97. svr.wait_until_ready();
  98. Client cli(host, PORT);
  99. // Warm-up request to establish connection and resolve DNS
  100. auto warmup_res = cli.Get("/benchmark");
  101. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  102. // Run multiple trials and collect timings
  103. const int num_trials = 20;
  104. std::vector<int64_t> timings;
  105. timings.reserve(num_trials);
  106. for (int i = 0; i < num_trials; i++) {
  107. auto start = std::chrono::high_resolution_clock::now();
  108. auto res = cli.Get("/benchmark");
  109. auto end = std::chrono::high_resolution_clock::now();
  110. auto elapsed =
  111. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  112. .count();
  113. // Assertions after timing measurement to avoid overhead
  114. ASSERT_TRUE(res);
  115. EXPECT_EQ(StatusCode::OK_200, res->status);
  116. timings.push_back(elapsed);
  117. }
  118. // Calculate 25th percentile (lower quartile)
  119. std::sort(timings.begin(), timings.end());
  120. auto p25 = timings[num_trials / 4];
  121. // Format timings for output
  122. std::ostringstream timings_str;
  123. timings_str << "[";
  124. for (size_t i = 0; i < timings.size(); i++) {
  125. if (i > 0) timings_str << ", ";
  126. timings_str << timings[i];
  127. }
  128. timings_str << "]";
  129. // Localhost HTTP GET should be fast even in CI environments
  130. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  131. << "ms (Issue #1777). Timings: " << timings_str.str();
  132. }
  133. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  134. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  135. class UnixSocketTest : public ::testing::Test {
  136. protected:
  137. void TearDown() override { std::remove(pathname_.c_str()); }
  138. void client_GET(const std::string &addr) {
  139. httplib::Client cli{addr};
  140. cli.set_address_family(AF_UNIX);
  141. ASSERT_TRUE(cli.is_valid());
  142. const auto &result = cli.Get(pattern_);
  143. ASSERT_TRUE(result) << "error: " << result.error();
  144. const auto &resp = result.value();
  145. EXPECT_EQ(resp.status, StatusCode::OK_200);
  146. EXPECT_EQ(resp.body, content_);
  147. }
  148. const std::string pathname_{"./httplib-server.sock"};
  149. const std::string pattern_{"/hi"};
  150. const std::string content_{"Hello World!"};
  151. };
  152. TEST_F(UnixSocketTest, pathname) {
  153. httplib::Server svr;
  154. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. }
  169. #if defined(__linux__) || \
  170. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  171. TEST_F(UnixSocketTest, PeerPid) {
  172. httplib::Server svr;
  173. std::string remote_port_val;
  174. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  175. res.set_content(content_, "text/plain");
  176. remote_port_val = std::to_string(req.remote_port);
  177. });
  178. std::thread t{[&] {
  179. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  180. }};
  181. auto se = detail::scope_exit([&] {
  182. svr.stop();
  183. t.join();
  184. ASSERT_FALSE(svr.is_running());
  185. });
  186. svr.wait_until_ready();
  187. ASSERT_TRUE(svr.is_running());
  188. client_GET(pathname_);
  189. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  190. }
  191. #endif
  192. #ifdef __linux__
  193. TEST_F(UnixSocketTest, abstract) {
  194. constexpr char svr_path[]{"\x00httplib-server.sock"};
  195. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  196. httplib::Server svr;
  197. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  198. res.set_content(content_, "text/plain");
  199. });
  200. std::thread t{[&] {
  201. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  202. }};
  203. auto se = detail::scope_exit([&] {
  204. svr.stop();
  205. t.join();
  206. ASSERT_FALSE(svr.is_running());
  207. });
  208. svr.wait_until_ready();
  209. ASSERT_TRUE(svr.is_running());
  210. client_GET(abstract_addr);
  211. }
  212. #endif
  213. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  214. httplib::Server svr;
  215. std::string received_host_header;
  216. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  217. // Capture the Host header sent by the client
  218. auto host_iter = req.headers.find("Host");
  219. if (host_iter != req.headers.end()) {
  220. received_host_header = host_iter->second;
  221. }
  222. res.set_content(content_, "text/plain");
  223. });
  224. std::thread t{[&] {
  225. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  226. }};
  227. auto se = detail::scope_exit([&] {
  228. svr.stop();
  229. t.join();
  230. ASSERT_FALSE(svr.is_running());
  231. });
  232. svr.wait_until_ready();
  233. ASSERT_TRUE(svr.is_running());
  234. // Test that Host header is automatically set to "localhost" for Unix socket
  235. // connections
  236. httplib::Client cli{pathname_};
  237. cli.set_address_family(AF_UNIX);
  238. ASSERT_TRUE(cli.is_valid());
  239. const auto &result = cli.Get(pattern_);
  240. ASSERT_TRUE(result) << "error: " << result.error();
  241. const auto &resp = result.value();
  242. EXPECT_EQ(resp.status, StatusCode::OK_200);
  243. EXPECT_EQ(resp.body, content_);
  244. // Verify that Host header was automatically set to "localhost"
  245. EXPECT_EQ(received_host_header, "localhost");
  246. }
  247. #ifndef _WIN32
  248. TEST(SocketStream, wait_writable_UNIX) {
  249. int fds[2];
  250. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  251. const auto asSocketStream = [&](socket_t fd,
  252. std::function<bool(Stream &)> func) {
  253. return detail::process_client_socket(
  254. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  255. };
  256. asSocketStream(fds[0], [&](Stream &s0) {
  257. EXPECT_EQ(s0.socket(), fds[0]);
  258. EXPECT_TRUE(s0.wait_writable());
  259. EXPECT_EQ(0, close(fds[1]));
  260. EXPECT_FALSE(s0.wait_writable());
  261. return true;
  262. });
  263. EXPECT_EQ(0, close(fds[0]));
  264. }
  265. TEST(SocketStream, wait_writable_INET) {
  266. sockaddr_in addr;
  267. memset(&addr, 0, sizeof(addr));
  268. addr.sin_family = AF_INET;
  269. addr.sin_port = htons(PORT + 1);
  270. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  271. int disconnected_svr_sock = -1;
  272. std::thread svr{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, listen(s, 1));
  277. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  281. std::thread cli{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, close(s));
  286. }};
  287. cli.join();
  288. svr.join();
  289. ASSERT_NE(disconnected_svr_sock, -1);
  290. const auto asSocketStream = [&](socket_t fd,
  291. std::function<bool(Stream &)> func) {
  292. return detail::process_client_socket(
  293. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  294. };
  295. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  296. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  297. EXPECT_FALSE(ss.wait_writable());
  298. return true;
  299. });
  300. ASSERT_EQ(0, close(disconnected_svr_sock));
  301. }
  302. #endif // #ifndef _WIN32
  303. TEST(ClientTest, MoveConstructible) {
  304. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  305. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  306. }
  307. TEST(ClientTest, MoveAssignable) {
  308. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  309. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  310. }
  311. #ifdef _WIN32
  312. TEST(StartupTest, WSAStartup) {
  313. WSADATA wsaData;
  314. int ret = WSAStartup(0x0002, &wsaData);
  315. ASSERT_EQ(0, ret);
  316. }
  317. #endif
  318. TEST(DecodePathTest, PercentCharacter) {
  319. EXPECT_EQ(
  320. decode_path_component(
  321. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  322. U8("descrip=Gastos áéíóúñÑ 6"));
  323. }
  324. TEST(DecodePathTest, PercentCharacterNUL) {
  325. string expected;
  326. expected.push_back('x');
  327. expected.push_back('\0');
  328. expected.push_back('x');
  329. EXPECT_EQ(decode_path_component("x%00x"), expected);
  330. }
  331. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'()";
  333. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  334. }
  335. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  336. string reservedCharacters = ";,/?:@&=+$";
  337. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  338. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  339. }
  340. TEST(ClientQueryOrder, PreserveOrder) {
  341. // This test reproduces Issue #2259: client may reorder query parameters
  342. // when sending a GET request. The expected behavior is that the client
  343. // preserves the original query string order when the caller supplied it
  344. // as part of the path.
  345. Server svr;
  346. svr.Get("/", [&](const Request &req, Response &res) {
  347. // Echo back the raw target so the test can assert ordering
  348. res.set_content(req.target, "text/plain");
  349. });
  350. std::thread t{[&] { svr.listen(HOST, PORT); }};
  351. auto se = detail::scope_exit([&] {
  352. svr.stop();
  353. t.join();
  354. ASSERT_FALSE(svr.is_running());
  355. });
  356. svr.wait_until_ready();
  357. Client cli(HOST, PORT);
  358. ASSERT_TRUE(cli.is_valid());
  359. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  360. auto res = cli.Get(original);
  361. ASSERT_TRUE(res);
  362. // Expect the echoed target to exactly match the original path (order
  363. // preserved)
  364. EXPECT_EQ(res->body, original);
  365. }
  366. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  367. string chineseCharacters = U8("中国語");
  368. string russianCharacters = U8("дом");
  369. string brazilianCharacters = U8("óculos");
  370. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  371. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  372. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  373. "%D0%B4%D0%BE%D0%BC");
  374. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  375. }
  376. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  377. string unescapedCharacters = "-_.!~*'()";
  378. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  379. }
  380. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  381. string reservedCharacters = ";,/?:@&=+$";
  382. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  383. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  384. }
  385. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  386. string chineseCharacters = U8("中国語");
  387. string russianCharacters = U8("дом");
  388. string brazilianCharacters = U8("óculos");
  389. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  390. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  391. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  392. "%D0%B4%D0%BE%D0%BC");
  393. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  394. }
  395. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  396. // Issue #2082 use case: encoding path component with ampersand
  397. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  398. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  399. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  400. }
  401. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  402. string unescapedCharacters = "-_.!~*'()";
  403. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  404. }
  405. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  406. string reservedCharacters = ";,/?:@&=+$#";
  407. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  408. }
  409. TEST(EncodeUriTest, TestUTF8Characters) {
  410. string chineseCharacters = U8("中国語");
  411. string russianCharacters = U8("дом");
  412. string brazilianCharacters = U8("óculos");
  413. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  414. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  415. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriTest, TestCompleteUri) {
  419. string uri =
  420. "https://example.com/path/to/resource?query=value&param=test#fragment";
  421. EXPECT_EQ(
  422. httplib::encode_uri(uri),
  423. "https://example.com/path/to/resource?query=value&param=test#fragment");
  424. }
  425. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  426. string uri =
  427. "https://example.com/path with spaces/file name.html?q=hello world";
  428. EXPECT_EQ(httplib::encode_uri(uri),
  429. "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world");
  431. }
  432. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  433. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  434. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  435. }
  436. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  441. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  442. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  443. string encodedBrazilian = "%C3%B3culos";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  445. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  446. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  447. }
  448. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  449. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  451. "Piri Tommy Villiers - on & on");
  452. }
  453. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  454. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  455. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  456. }
  457. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  458. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  459. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  460. }
  461. TEST(DecodeUriTest, TestUTF8Characters) {
  462. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  463. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  464. string encodedBrazilian = "%C3%B3culos";
  465. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  466. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  467. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  468. }
  469. TEST(DecodeUriTest, TestCompleteUri) {
  470. string encodedUri = "https://example.com/path%20with%20spaces/"
  471. "file%20name.html?q=hello%20world";
  472. EXPECT_EQ(
  473. httplib::decode_uri(encodedUri),
  474. "https://example.com/path with spaces/file name.html?q=hello world");
  475. }
  476. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  477. string original =
  478. "https://example.com/path with spaces/file name.html?q=hello world";
  479. string encoded = httplib::encode_uri(original);
  480. string decoded = httplib::decode_uri(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  484. string original = "Piri Tommy Villiers - on & on";
  485. string encoded = httplib::encode_uri_component(original);
  486. string decoded = httplib::decode_uri_component(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(TrimTests, TrimStringTests) {
  490. EXPECT_EQ("abc", detail::trim_copy("abc"));
  491. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  492. EXPECT_TRUE(detail::trim_copy("").empty());
  493. }
  494. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  495. // Simple case without quality values
  496. std::vector<std::string> result1;
  497. EXPECT_TRUE(detail::parse_accept_header(
  498. "text/html,application/json,text/plain", result1));
  499. EXPECT_EQ(result1.size(), 3U);
  500. EXPECT_EQ(result1[0], "text/html");
  501. EXPECT_EQ(result1[1], "application/json");
  502. EXPECT_EQ(result1[2], "text/plain");
  503. // With quality values
  504. std::vector<std::string> result2;
  505. EXPECT_TRUE(detail::parse_accept_header(
  506. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  507. EXPECT_EQ(result2.size(), 3U);
  508. EXPECT_EQ(result2[0], "application/json"); // highest q value
  509. EXPECT_EQ(result2[1], "text/html");
  510. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  511. }
  512. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  513. // Mixed with and without quality values
  514. std::vector<std::string> result;
  515. EXPECT_TRUE(detail::parse_accept_header(
  516. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  517. EXPECT_EQ(result.size(), 3U);
  518. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  519. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  520. EXPECT_EQ(result[2], "application/json"); // q=0.5
  521. }
  522. TEST(ParseAcceptHeaderTest, EdgeCases) {
  523. // Empty header
  524. std::vector<std::string> empty_result;
  525. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  526. EXPECT_TRUE(empty_result.empty());
  527. // Single type
  528. std::vector<std::string> single_result;
  529. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  530. EXPECT_EQ(single_result.size(), 1U);
  531. EXPECT_EQ(single_result[0], "application/json");
  532. // Wildcard types
  533. std::vector<std::string> wildcard_result;
  534. EXPECT_TRUE(detail::parse_accept_header(
  535. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  536. EXPECT_EQ(wildcard_result.size(), 3U);
  537. EXPECT_EQ(wildcard_result[0], "application/json");
  538. EXPECT_EQ(wildcard_result[1], "text/*");
  539. EXPECT_EQ(wildcard_result[2], "*/*");
  540. }
  541. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  542. // Common browser Accept header
  543. std::vector<std::string> browser_result;
  544. EXPECT_TRUE(
  545. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  546. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  547. browser_result));
  548. EXPECT_EQ(browser_result.size(), 6U);
  549. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  550. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  551. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  552. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  553. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  554. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  555. // API client header
  556. std::vector<std::string> api_result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  559. api_result));
  560. EXPECT_EQ(api_result.size(), 3U);
  561. EXPECT_EQ(api_result[0], "application/json");
  562. EXPECT_EQ(api_result[1], "application/xml");
  563. EXPECT_EQ(api_result[2], "text/plain");
  564. }
  565. TEST(ParseAcceptHeaderTest, SpecialCases) {
  566. // Quality value with 3 decimal places
  567. std::vector<std::string> decimal_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  570. EXPECT_EQ(decimal_result.size(), 2U);
  571. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  572. EXPECT_EQ(decimal_result[1], "text/html");
  573. // Zero quality (should still be included but with lowest priority)
  574. std::vector<std::string> zero_q_result;
  575. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  576. zero_q_result));
  577. EXPECT_EQ(zero_q_result.size(), 2U);
  578. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  579. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  580. // No spaces around commas
  581. std::vector<std::string> no_space_result;
  582. EXPECT_TRUE(detail::parse_accept_header(
  583. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  584. no_space_result));
  585. EXPECT_EQ(no_space_result.size(), 3U);
  586. EXPECT_EQ(no_space_result[0], "text/html");
  587. EXPECT_EQ(no_space_result[1], "application/json");
  588. EXPECT_EQ(no_space_result[2], "text/plain");
  589. }
  590. TEST(ParseAcceptHeaderTest, InvalidCases) {
  591. std::vector<std::string> result;
  592. // Invalid quality value (> 1.0)
  593. EXPECT_FALSE(
  594. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  595. // Invalid quality value (< 0.0)
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  598. // Invalid quality value (not a number)
  599. EXPECT_FALSE(detail::parse_accept_header(
  600. "text/html;q=invalid,application/json", result));
  601. // Empty quality value
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=,application/json", result));
  604. // Invalid media type format (no slash and not wildcard)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("invalidtype,application/json", result));
  607. // Empty media type
  608. result.clear();
  609. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  610. // Only commas
  611. result.clear();
  612. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  613. // Valid cases should still work
  614. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "*/*");
  617. EXPECT_TRUE(detail::parse_accept_header("*", result));
  618. EXPECT_EQ(result.size(), 1U);
  619. EXPECT_EQ(result[0], "*");
  620. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "text/*");
  623. }
  624. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  625. Server svr;
  626. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  627. EXPECT_EQ(req.accept_content_types.size(), 3U);
  628. EXPECT_EQ(req.accept_content_types[0], "application/json");
  629. EXPECT_EQ(req.accept_content_types[1], "text/html");
  630. EXPECT_EQ(req.accept_content_types[2], "*/*");
  631. res.set_content("ok", "text/plain");
  632. });
  633. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  634. EXPECT_TRUE(false);
  635. res.set_content("bad request", "text/plain");
  636. });
  637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  638. auto se = detail::scope_exit([&] {
  639. svr.stop();
  640. listen_thread.join();
  641. ASSERT_FALSE(svr.is_running());
  642. });
  643. svr.wait_until_ready();
  644. Client cli("localhost", PORT);
  645. {
  646. auto res =
  647. cli.Get("/accept_ok",
  648. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::OK_200, res->status);
  651. }
  652. {
  653. auto res = cli.Get("/accept_bad_request",
  654. {{"Accept", "text/html;q=abc,application/json"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  657. }
  658. }
  659. TEST(DivideTest, DivideStringTests) {
  660. auto divide = [](const std::string &str, char d) {
  661. std::string lhs;
  662. std::string rhs;
  663. detail::divide(str, d,
  664. [&](const char *lhs_data, std::size_t lhs_size,
  665. const char *rhs_data, std::size_t rhs_size) {
  666. lhs.assign(lhs_data, lhs_size);
  667. rhs.assign(rhs_data, rhs_size);
  668. });
  669. return std::make_pair(std::move(lhs), std::move(rhs));
  670. };
  671. {
  672. const auto res = divide("", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide("=", '=');
  678. EXPECT_EQ(res.first, "");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide(" ", '=');
  683. EXPECT_EQ(res.first, " ");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("a=", '=');
  693. EXPECT_EQ(res.first, "a");
  694. EXPECT_EQ(res.second, "");
  695. }
  696. {
  697. const auto res = divide("=b", '=');
  698. EXPECT_EQ(res.first, "");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b");
  705. }
  706. {
  707. const auto res = divide("a=b=", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=");
  710. }
  711. {
  712. const auto res = divide("a=b=c", '=');
  713. EXPECT_EQ(res.first, "a");
  714. EXPECT_EQ(res.second, "b=c");
  715. }
  716. }
  717. TEST(SplitTest, ParseQueryString) {
  718. string s = "key1=val1&key2=val2&key3=val3";
  719. Params dic;
  720. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  721. [&](const char *b, const char *e) {
  722. string key, val;
  723. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  724. if (key.empty()) {
  725. key.assign(b2, e2);
  726. } else {
  727. val.assign(b2, e2);
  728. }
  729. });
  730. dic.emplace(key, val);
  731. });
  732. EXPECT_EQ("val1", dic.find("key1")->second);
  733. EXPECT_EQ("val2", dic.find("key2")->second);
  734. EXPECT_EQ("val3", dic.find("key3")->second);
  735. }
  736. TEST(SplitTest, ParseInvalidQueryTests) {
  737. {
  738. string s = " ";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. {
  744. string s = " = =";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. }
  750. TEST(ParseQueryTest, ParseQueryString) {
  751. {
  752. std::string s = "key1=val1&key2=val2&key3=val3";
  753. Params dic;
  754. detail::parse_query_text(s, dic);
  755. EXPECT_EQ("val1", dic.find("key1")->second);
  756. EXPECT_EQ("val2", dic.find("key2")->second);
  757. EXPECT_EQ("val3", dic.find("key3")->second);
  758. }
  759. {
  760. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  761. Params dic;
  762. detail::parse_query_text(s, dic);
  763. EXPECT_EQ("", dic.find("key1")->second);
  764. EXPECT_EQ("val1", dic.find("key2")->second);
  765. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  766. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  767. }
  768. }
  769. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  770. Params dic;
  771. EXPECT_EQ(detail::params_to_query_str(dic), "");
  772. dic.emplace("key1", "val1");
  773. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  774. dic.emplace("key2", "val2");
  775. dic.emplace("key3", "val3");
  776. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  777. }
  778. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  779. string content_type = "multipart/form-data; boundary=something";
  780. string boundary;
  781. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  782. EXPECT_TRUE(ret);
  783. EXPECT_EQ(boundary, "something");
  784. }
  785. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  786. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  787. string boundary;
  788. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  789. EXPECT_TRUE(ret);
  790. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  791. }
  792. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  793. string content_type =
  794. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  795. string boundary;
  796. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  797. EXPECT_TRUE(ret);
  798. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  799. }
  800. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  801. string content_type =
  802. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  803. string boundary;
  804. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  805. EXPECT_TRUE(ret);
  806. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  807. }
  808. TEST(GetHeaderValueTest, DefaultValue) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  811. EXPECT_STREQ("text/plain", val);
  812. }
  813. TEST(GetHeaderValueTest, DefaultValueInt) {
  814. Headers headers = {{"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  816. EXPECT_EQ(100ull, val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValue) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  824. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  826. EXPECT_STREQ("text/html", val);
  827. }
  828. TEST(GetHeaderValueTest, SetContent) {
  829. Response res;
  830. res.set_content("html", "text/html");
  831. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  832. res.set_content("text", "text/plain");
  833. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  834. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  835. }
  836. TEST(GetHeaderValueTest, RegularValueInt) {
  837. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  839. EXPECT_EQ(100ull, val);
  840. }
  841. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  842. Headers headers = {{"Content-Length", "x"}};
  843. auto is_invalid_value = false;
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  845. is_invalid_value);
  846. EXPECT_EQ(0ull, val);
  847. EXPECT_TRUE(is_invalid_value);
  848. }
  849. TEST(GetHeaderValueTest, Range) {
  850. {
  851. Headers headers = {make_range_header({{1, -1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=1-", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{-1, 1}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=-1", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=1-10, 100-200", val);
  874. }
  875. {
  876. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  878. EXPECT_STREQ("bytes=0-0, -1", val);
  879. }
  880. }
  881. TEST(ParseHeaderValueTest, Range) {
  882. {
  883. Ranges ranges;
  884. auto ret = detail::parse_range_header("bytes=1-", ranges);
  885. EXPECT_TRUE(ret);
  886. EXPECT_EQ(1u, ranges.size());
  887. EXPECT_EQ(1u, ranges[0].first);
  888. EXPECT_EQ(-1, ranges[0].second);
  889. }
  890. {
  891. Ranges ranges;
  892. auto ret = detail::parse_range_header("bytes=-1", ranges);
  893. EXPECT_TRUE(ret);
  894. EXPECT_EQ(1u, ranges.size());
  895. EXPECT_EQ(-1, ranges[0].first);
  896. EXPECT_EQ(1u, ranges[0].second);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(1u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  909. EXPECT_FALSE(ret);
  910. }
  911. {
  912. Ranges ranges;
  913. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  914. EXPECT_TRUE(ret);
  915. EXPECT_EQ(2u, ranges.size());
  916. EXPECT_EQ(1u, ranges[0].first);
  917. EXPECT_EQ(10u, ranges[0].second);
  918. EXPECT_EQ(100u, ranges[1].first);
  919. EXPECT_EQ(-1, ranges[1].second);
  920. }
  921. {
  922. Ranges ranges;
  923. auto ret =
  924. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  925. EXPECT_TRUE(ret);
  926. EXPECT_EQ(3u, ranges.size());
  927. EXPECT_EQ(1u, ranges[0].first);
  928. EXPECT_EQ(10u, ranges[0].second);
  929. EXPECT_EQ(100u, ranges[1].first);
  930. EXPECT_EQ(200u, ranges[1].second);
  931. EXPECT_EQ(300u, ranges[2].first);
  932. EXPECT_EQ(400u, ranges[2].second);
  933. }
  934. {
  935. Ranges ranges;
  936. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  949. EXPECT_TRUE(ranges.empty());
  950. }
  951. }
  952. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  953. Request req;
  954. req.set_header("Accept-Encoding", "gzip");
  955. Response res;
  956. res.set_header("Content-Type", "text/plain");
  957. auto ret = detail::encoding_type(req, res);
  958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #else
  961. EXPECT_TRUE(ret == detail::EncodingType::None);
  962. #endif
  963. }
  964. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  972. #elif CPPHTTPLIB_ZLIB_SUPPORT
  973. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  974. #elif CPPHTTPLIB_ZSTD_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  976. #else
  977. EXPECT_TRUE(ret == detail::EncodingType::None);
  978. #endif
  979. }
  980. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  981. Request req;
  982. req.set_header("Accept-Encoding",
  983. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  984. Response res;
  985. res.set_header("Content-Type", "text/plain");
  986. auto ret = detail::encoding_type(req, res);
  987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  988. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  989. #elif CPPHTTPLIB_ZLIB_SUPPORT
  990. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  991. #elif CPPHTTPLIB_ZSTD_SUPPORT
  992. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  993. #else
  994. EXPECT_TRUE(ret == detail::EncodingType::None);
  995. #endif
  996. }
  997. TEST(BufferStreamTest, read) {
  998. detail::BufferStream strm1;
  999. Stream &strm = strm1;
  1000. EXPECT_EQ(5, strm.write("hello"));
  1001. char buf[512];
  1002. EXPECT_EQ(2, strm.read(buf, 2));
  1003. EXPECT_EQ('h', buf[0]);
  1004. EXPECT_EQ('e', buf[1]);
  1005. EXPECT_EQ(2, strm.read(buf, 2));
  1006. EXPECT_EQ('l', buf[0]);
  1007. EXPECT_EQ('l', buf[1]);
  1008. EXPECT_EQ(1, strm.read(buf, 1));
  1009. EXPECT_EQ('o', buf[0]);
  1010. EXPECT_EQ(0, strm.read(buf, 1));
  1011. }
  1012. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1013. auto host = "www.httpwatch.com";
  1014. auto ip = hosted_at(host);
  1015. EXPECT_EQ("23.96.13.243", ip);
  1016. std::vector<std::string> addrs;
  1017. hosted_at(host, addrs);
  1018. EXPECT_EQ(1u, addrs.size());
  1019. }
  1020. #if 0 // It depends on each test environment...
  1021. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1022. auto host = "www.youtube.com";
  1023. std::vector<std::string> addrs;
  1024. hosted_at(host, addrs);
  1025. EXPECT_EQ(20u, addrs.size());
  1026. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1027. EXPECT_TRUE(it != addrs.end());
  1028. }
  1029. #endif
  1030. class ChunkedEncodingTest : public ::testing::Test {
  1031. protected:
  1032. ChunkedEncodingTest()
  1033. : cli_(HOST, PORT)
  1034. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1035. ,
  1036. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1037. #endif
  1038. {
  1039. cli_.set_connection_timeout(2);
  1040. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1041. cli_.enable_server_certificate_verification(false);
  1042. #endif
  1043. }
  1044. virtual void SetUp() {
  1045. read_file("./image.jpg", image_data_);
  1046. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1047. res.set_content("Hello World!", "text/plain");
  1048. });
  1049. svr_.Get(
  1050. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1051. res.set_chunked_content_provider(
  1052. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1053. size_t remaining = image_data_.size() - offset;
  1054. if (remaining == 0) {
  1055. sink.done();
  1056. } else {
  1057. constexpr size_t CHUNK_SIZE = 1024;
  1058. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1059. sink.write(&image_data_[offset], send_size);
  1060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1061. }
  1062. return true;
  1063. });
  1064. });
  1065. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1066. svr_.wait_until_ready();
  1067. }
  1068. virtual void TearDown() {
  1069. svr_.stop();
  1070. if (!request_threads_.empty()) {
  1071. std::this_thread::sleep_for(std::chrono::seconds(1));
  1072. for (auto &t : request_threads_) {
  1073. t.join();
  1074. }
  1075. }
  1076. t_.join();
  1077. }
  1078. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1079. SSLClient cli_;
  1080. SSLServer svr_;
  1081. #else
  1082. Client cli_;
  1083. Server svr_;
  1084. #endif
  1085. thread t_;
  1086. std::vector<thread> request_threads_;
  1087. std::string image_data_;
  1088. };
  1089. TEST_F(ChunkedEncodingTest, NormalGet) {
  1090. auto res = cli_.Get("/chunked");
  1091. ASSERT_TRUE(res);
  1092. std::string out;
  1093. read_file("./image.jpg", out);
  1094. EXPECT_EQ(StatusCode::OK_200, res->status);
  1095. EXPECT_EQ(out, res->body);
  1096. }
  1097. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1098. std::string body;
  1099. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1100. body.append(data, data_length);
  1101. return true;
  1102. });
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get(
  1112. "/chunked",
  1113. [&](const Response &response) {
  1114. EXPECT_EQ(StatusCode::OK_200, response.status);
  1115. return true;
  1116. },
  1117. [&](const char *data, size_t data_length) {
  1118. body.append(data, data_length);
  1119. return true;
  1120. });
  1121. ASSERT_TRUE(res);
  1122. std::string out;
  1123. read_file("./image.jpg", out);
  1124. EXPECT_EQ(StatusCode::OK_200, res->status);
  1125. EXPECT_EQ(out, body);
  1126. }
  1127. TEST(RangeTest, FromHTTPBin_Online) {
  1128. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1129. auto host = "httpcan.org";
  1130. auto path = std::string{"/range/32"};
  1131. #else
  1132. auto host = "nghttp2.org";
  1133. auto path = std::string{"/httpbin/range/32"};
  1134. #endif
  1135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1136. auto port = 443;
  1137. SSLClient cli(host, port);
  1138. #else
  1139. auto port = 80;
  1140. Client cli(host, port);
  1141. #endif
  1142. cli.set_connection_timeout(5);
  1143. {
  1144. auto res = cli.Get(path);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{1, -1}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{1, 10}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("bcdefghijk", res->body);
  1161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 31}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. Headers headers = {make_range_header({{0, -1}})};
  1172. auto res = cli.Get(path, headers);
  1173. ASSERT_TRUE(res);
  1174. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. }
  1177. {
  1178. Headers headers = {make_range_header({{0, 32}})};
  1179. auto res = cli.Get(path, headers);
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1182. }
  1183. }
  1184. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1185. auto host = "unresolvableaddress.local";
  1186. auto path = std::string{"/"};
  1187. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1188. auto port = 443;
  1189. SSLClient cli(host, port);
  1190. #else
  1191. auto port = 80;
  1192. Client cli(host, port);
  1193. #endif
  1194. cli.set_connection_timeout(1);
  1195. {
  1196. auto res = cli.Get(path);
  1197. ASSERT_FALSE(res);
  1198. }
  1199. std::this_thread::sleep_for(std::chrono::seconds(8));
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost) {
  1202. auto host = "-abcde.com";
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. auto port = 443;
  1205. SSLClient cli(host, port);
  1206. #else
  1207. auto port = 80;
  1208. Client cli(host, port);
  1209. #endif
  1210. cli.set_connection_timeout(std::chrono::seconds(2));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Connection, res.error());
  1214. }
  1215. TEST(ConnectionErrorTest, InvalidHost2) {
  1216. auto host = "httpcan.org/";
  1217. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1218. SSLClient cli(host);
  1219. #else
  1220. Client cli(host);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. stringstream s;
  1238. s << "error code: " << res.error();
  1239. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1240. }
  1241. TEST(ConnectionErrorTest, InvalidPort) {
  1242. auto host = "localhost";
  1243. auto port = 44380;
  1244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1245. SSLClient cli(host, port);
  1246. #else
  1247. Client cli(host, port);
  1248. #endif
  1249. cli.set_connection_timeout(std::chrono::seconds(2));
  1250. auto res = cli.Get("/");
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_TRUE(Error::Connection == res.error() ||
  1253. Error::ConnectionTimeout == res.error());
  1254. }
  1255. TEST(ConnectionErrorTest, Timeout_Online) {
  1256. auto host = "google.com";
  1257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1258. auto port = 44380;
  1259. SSLClient cli(host, port);
  1260. #else
  1261. auto port = 8080;
  1262. Client cli(host, port);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. // only probe one address type so that the error reason
  1266. // correlates to the timed-out IPv4, not the unsupported
  1267. // IPv6 connection attempt
  1268. cli.set_address_family(AF_INET);
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1272. }
  1273. TEST(CancelTest, NoCancel_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpcan.org";
  1276. auto path = std::string{"/range/32"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/32"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1290. ASSERT_TRUE(res);
  1291. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1292. EXPECT_EQ(StatusCode::OK_200, res->status);
  1293. }
  1294. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1295. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1296. auto host = "httpcan.org";
  1297. auto path = std::string{"/range/32"};
  1298. #else
  1299. auto host = "nghttp2.org";
  1300. auto path = std::string{"/httpbin/range/32"};
  1301. #endif
  1302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1303. auto port = 443;
  1304. SSLClient cli(host, port);
  1305. #else
  1306. auto port = 80;
  1307. Client cli(host, port);
  1308. #endif
  1309. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1310. cli.set_connection_timeout(std::chrono::seconds(5));
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_EQ(Error::Canceled, res.error());
  1313. }
  1314. TEST(CancelTest, WithCancelLargePayload_Online) {
  1315. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1316. auto host = "httpcan.org";
  1317. auto path = std::string{"/range/65536"};
  1318. #else
  1319. auto host = "nghttp2.org";
  1320. auto path = std::string{"/httpbin/range/65536"};
  1321. #endif
  1322. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1323. auto port = 443;
  1324. SSLClient cli(host, port);
  1325. #else
  1326. auto port = 80;
  1327. Client cli(host, port);
  1328. #endif
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. uint32_t count = 0;
  1331. auto res =
  1332. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, NoCancelPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return true; });
  1353. ASSERT_TRUE(res);
  1354. EXPECT_EQ("Hello World!", res->body);
  1355. EXPECT_EQ(StatusCode::OK_200, res->status);
  1356. }
  1357. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1358. Server svr;
  1359. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1360. res.set_content("Hello World!", "text/plain");
  1361. });
  1362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1363. auto se = detail::scope_exit([&] {
  1364. svr.stop();
  1365. thread.join();
  1366. ASSERT_FALSE(svr.is_running());
  1367. });
  1368. svr.wait_until_ready();
  1369. Client cli(HOST, PORT);
  1370. cli.set_connection_timeout(std::chrono::seconds(5));
  1371. auto res =
  1372. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1373. "application/json", [](uint64_t, uint64_t) { return false; });
  1374. ASSERT_TRUE(!res);
  1375. EXPECT_EQ(Error::Canceled, res.error());
  1376. }
  1377. TEST(CancelTest, WithCancelLargePayloadPost) {
  1378. Server svr;
  1379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content(LARGE_DATA, "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, NoCancelPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content("Hello World!", "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return true; });
  1414. ASSERT_TRUE(res);
  1415. EXPECT_EQ("Hello World!", res->body);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1419. Server svr;
  1420. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1421. res.set_content("Hello World!", "text/plain");
  1422. });
  1423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1424. auto se = detail::scope_exit([&] {
  1425. svr.stop();
  1426. thread.join();
  1427. ASSERT_FALSE(svr.is_running());
  1428. });
  1429. svr.wait_until_ready();
  1430. Client cli(HOST, PORT);
  1431. cli.set_connection_timeout(std::chrono::seconds(5));
  1432. auto res =
  1433. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1434. "application/json", [](uint64_t, uint64_t) { return false; });
  1435. ASSERT_TRUE(!res);
  1436. EXPECT_EQ(Error::Canceled, res.error());
  1437. }
  1438. TEST(CancelTest, WithCancelLargePayloadPut) {
  1439. Server svr;
  1440. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content(LARGE_DATA, "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1480. Server svr;
  1481. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1500. Server svr;
  1501. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, NoCancelDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content("Hello World!", "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return true; });
  1536. ASSERT_TRUE(res);
  1537. EXPECT_EQ("Hello World!", res->body);
  1538. EXPECT_EQ(StatusCode::OK_200, res->status);
  1539. }
  1540. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1541. Server svr;
  1542. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1543. res.set_content("Hello World!", "text/plain");
  1544. });
  1545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1546. auto se = detail::scope_exit([&] {
  1547. svr.stop();
  1548. thread.join();
  1549. ASSERT_FALSE(svr.is_running());
  1550. });
  1551. svr.wait_until_ready();
  1552. Client cli(HOST, PORT);
  1553. cli.set_connection_timeout(std::chrono::seconds(5));
  1554. auto res =
  1555. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1556. "application/json", [](uint64_t, uint64_t) { return false; });
  1557. ASSERT_TRUE(!res);
  1558. EXPECT_EQ(Error::Canceled, res.error());
  1559. }
  1560. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1561. Server svr;
  1562. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1563. res.set_content(LARGE_DATA, "text/plain");
  1564. });
  1565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1566. auto se = detail::scope_exit([&] {
  1567. svr.stop();
  1568. thread.join();
  1569. ASSERT_FALSE(svr.is_running());
  1570. });
  1571. svr.wait_until_ready();
  1572. Client cli(HOST, PORT);
  1573. cli.set_connection_timeout(std::chrono::seconds(5));
  1574. auto res =
  1575. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1576. "application/json", [](uint64_t, uint64_t) { return false; });
  1577. ASSERT_TRUE(!res);
  1578. EXPECT_EQ(Error::Canceled, res.error());
  1579. }
  1580. static std::string remove_whitespace(const std::string &input) {
  1581. std::string output;
  1582. output.reserve(input.size());
  1583. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1584. [](unsigned char c) { return !std::isspace(c); });
  1585. return output;
  1586. }
  1587. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1588. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1589. auto host = "httpcan.org";
  1590. auto path = std::string{"/basic-auth/hello/world"};
  1591. #else
  1592. auto host = "nghttp2.org";
  1593. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1594. #endif
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. auto port = 443;
  1597. SSLClient cli(host, port);
  1598. #else
  1599. auto port = 80;
  1600. Client cli(host, port);
  1601. #endif
  1602. {
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1606. }
  1607. {
  1608. auto res =
  1609. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1610. ASSERT_TRUE(res);
  1611. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1612. remove_whitespace(res->body));
  1613. EXPECT_EQ(StatusCode::OK_200, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("hello", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1620. remove_whitespace(res->body));
  1621. EXPECT_EQ(StatusCode::OK_200, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("hello", "bad");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. {
  1630. cli.set_basic_auth("bad", "world");
  1631. auto res = cli.Get(path);
  1632. ASSERT_TRUE(res);
  1633. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1634. }
  1635. }
  1636. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1637. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1638. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1639. auto host = "httpcan.org";
  1640. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1641. auto paths = std::vector<std::string>{
  1642. "/digest-auth/auth/hello/world/MD5",
  1643. "/digest-auth/auth/hello/world/SHA-256",
  1644. "/digest-auth/auth/hello/world/SHA-512",
  1645. };
  1646. #else
  1647. auto host = "nghttp2.org";
  1648. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1649. auto paths = std::vector<std::string>{
  1650. "/httpbin/digest-auth/auth/hello/world/MD5",
  1651. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1652. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1653. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1654. };
  1655. #endif
  1656. auto port = 443;
  1657. SSLClient cli(host, port);
  1658. {
  1659. auto res = cli.Get(unauth_path);
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1662. }
  1663. {
  1664. cli.set_digest_auth("hello", "world");
  1665. for (const auto &path : paths) {
  1666. auto res = cli.Get(path.c_str());
  1667. ASSERT_TRUE(res);
  1668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1669. std::string algo(path.substr(path.rfind('/') + 1));
  1670. EXPECT_EQ(
  1671. remove_whitespace("{\"algorithm\":\"" + algo +
  1672. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1673. remove_whitespace(res->body));
  1674. #else
  1675. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1676. remove_whitespace(res->body));
  1677. #endif
  1678. EXPECT_EQ(StatusCode::OK_200, res->status);
  1679. }
  1680. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1681. cli.set_digest_auth("hello", "bad");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1686. }
  1687. #endif
  1688. }
  1689. }
  1690. #endif
  1691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1692. auto host = "google.com";
  1693. auto another_host = "example.com";
  1694. auto wrong_ip = "0.0.0.0";
  1695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1696. SSLClient cli(host);
  1697. #else
  1698. Client cli(host);
  1699. #endif
  1700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1701. auto res = cli.Get("/");
  1702. ASSERT_TRUE(res);
  1703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1704. }
  1705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1706. auto host = "google.com";
  1707. auto wrong_ip = "0.0.0.0";
  1708. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1709. SSLClient cli(host);
  1710. #else
  1711. Client cli(host);
  1712. #endif
  1713. cli.set_hostname_addr_map({{host, wrong_ip}});
  1714. auto res = cli.Get("/");
  1715. ASSERT_TRUE(!res);
  1716. EXPECT_EQ(Error::Connection, res.error());
  1717. }
  1718. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1719. auto host = "nghttp2.org";
  1720. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1721. SSLClient cli(host);
  1722. #else
  1723. Client cli(host);
  1724. #endif
  1725. cli.set_follow_location(true);
  1726. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. TEST(RedirectTest, Redirect_Online) {
  1731. auto host = "nghttp2.org";
  1732. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1733. SSLClient cli(host);
  1734. #else
  1735. Client cli(host);
  1736. #endif
  1737. cli.set_follow_location(true);
  1738. auto res = cli.Get("/httpbin/redirect/3");
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::OK_200, res->status);
  1741. }
  1742. TEST(RelativeRedirectTest, Redirect_Online) {
  1743. auto host = "nghttp2.org";
  1744. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1745. SSLClient cli(host);
  1746. #else
  1747. Client cli(host);
  1748. #endif
  1749. cli.set_follow_location(true);
  1750. auto res = cli.Get("/httpbin/relative-redirect/3");
  1751. ASSERT_TRUE(res);
  1752. EXPECT_EQ(StatusCode::OK_200, res->status);
  1753. }
  1754. TEST(TooManyRedirectTest, Redirect_Online) {
  1755. auto host = "nghttp2.org";
  1756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1757. SSLClient cli(host);
  1758. #else
  1759. Client cli(host);
  1760. #endif
  1761. cli.set_follow_location(true);
  1762. auto res = cli.Get("/httpbin/redirect/21");
  1763. ASSERT_TRUE(!res);
  1764. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1765. }
  1766. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1767. TEST(YahooRedirectTest, Redirect_Online) {
  1768. Client cli("yahoo.com");
  1769. auto res = cli.Get("/");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1772. cli.set_follow_location(true);
  1773. res = cli.Get("/");
  1774. ASSERT_TRUE(res);
  1775. EXPECT_EQ(StatusCode::OK_200, res->status);
  1776. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1777. }
  1778. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1779. #define REDIR_HOST "httpbingo.org"
  1780. #define REDIR_PATH "/redirect-to"
  1781. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1782. SSLClient cli(REDIR_HOST);
  1783. cli.set_follow_location(true);
  1784. auto res =
  1785. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(StatusCode::OK_200, res->status);
  1788. }
  1789. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1790. SSLClient cli(REDIR_HOST);
  1791. cli.set_follow_location(true);
  1792. Params params;
  1793. params.emplace("url", "http://example.com");
  1794. params.emplace("status_code", "302");
  1795. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1796. ASSERT_TRUE(res);
  1797. EXPECT_EQ(StatusCode::OK_200, res->status);
  1798. }
  1799. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1800. SSLClient cli(REDIR_HOST);
  1801. cli.set_follow_location(true);
  1802. Params params;
  1803. params.emplace("url", "http://example.com");
  1804. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(UrlWithSpace, Redirect_Online) {
  1809. SSLClient cli("edge.forgecdn.net");
  1810. cli.set_follow_location(true);
  1811. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1812. ASSERT_TRUE(res);
  1813. EXPECT_EQ(StatusCode::OK_200, res->status);
  1814. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1815. }
  1816. #endif
  1817. #if !defined(_WIN32) && !defined(_WIN64)
  1818. TEST(ReceiveSignals, Signal) {
  1819. auto setupSignalHandlers = []() {
  1820. struct sigaction act;
  1821. sigemptyset(&act.sa_mask);
  1822. act.sa_flags = SA_SIGINFO;
  1823. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1824. switch (sig) {
  1825. case SIGINT:
  1826. default: break;
  1827. }
  1828. };
  1829. ::sigaction(SIGINT, &act, nullptr);
  1830. };
  1831. Server svr;
  1832. int port = 0;
  1833. auto thread = std::thread([&]() {
  1834. setupSignalHandlers();
  1835. port = svr.bind_to_any_port(HOST);
  1836. svr.listen_after_bind();
  1837. });
  1838. auto se = detail::scope_exit([&] {
  1839. svr.stop();
  1840. thread.join();
  1841. ASSERT_FALSE(svr.is_running());
  1842. });
  1843. svr.wait_until_ready();
  1844. ASSERT_TRUE(svr.is_running());
  1845. pthread_kill(thread.native_handle(), SIGINT);
  1846. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1847. ASSERT_TRUE(svr.is_running());
  1848. }
  1849. #endif
  1850. TEST(RedirectToDifferentPort, Redirect) {
  1851. Server svr1;
  1852. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1853. res.set_content("Hello World!", "text/plain");
  1854. });
  1855. int svr1_port = 0;
  1856. auto thread1 = std::thread([&]() {
  1857. svr1_port = svr1.bind_to_any_port(HOST);
  1858. svr1.listen_after_bind();
  1859. });
  1860. Server svr2;
  1861. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1862. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1863. });
  1864. int svr2_port = 0;
  1865. auto thread2 = std::thread([&]() {
  1866. svr2_port = svr2.bind_to_any_port(HOST);
  1867. svr2.listen_after_bind();
  1868. });
  1869. auto se = detail::scope_exit([&] {
  1870. svr2.stop();
  1871. thread2.join();
  1872. svr1.stop();
  1873. thread1.join();
  1874. ASSERT_FALSE(svr2.is_running());
  1875. ASSERT_FALSE(svr1.is_running());
  1876. });
  1877. svr1.wait_until_ready();
  1878. svr2.wait_until_ready();
  1879. Client cli("localhost", svr2_port);
  1880. cli.set_follow_location(true);
  1881. auto res = cli.Get("/2");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(StatusCode::OK_200, res->status);
  1884. EXPECT_EQ("Hello World!", res->body);
  1885. }
  1886. TEST(RedirectFromPageWithContent, 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. });
  1892. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1893. res.set_content("Hello World!", "text/plain");
  1894. });
  1895. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1896. auto se = detail::scope_exit([&] {
  1897. svr.stop();
  1898. th.join();
  1899. ASSERT_FALSE(svr.is_running());
  1900. });
  1901. svr.wait_until_ready();
  1902. {
  1903. Client cli("localhost", PORT);
  1904. cli.set_follow_location(true);
  1905. std::string body;
  1906. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1907. body.append(data, data_length);
  1908. return true;
  1909. });
  1910. ASSERT_TRUE(res);
  1911. EXPECT_EQ(StatusCode::OK_200, res->status);
  1912. EXPECT_EQ("Hello World!", body);
  1913. }
  1914. {
  1915. Client cli("localhost", PORT);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::Found_302, res->status);
  1923. EXPECT_EQ("___", body);
  1924. }
  1925. }
  1926. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1927. Server svr;
  1928. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1929. res.set_content("___", "text/plain");
  1930. // res.set_redirect("/2");
  1931. res.set_redirect("http://[::1]:1234/2");
  1932. });
  1933. svr.Get("/2", [&](const Request &req, Response &res) {
  1934. auto host_header = req.headers.find("Host");
  1935. ASSERT_TRUE(host_header != req.headers.end());
  1936. EXPECT_EQ("[::1]:1234", host_header->second);
  1937. res.set_content("Hello World!", "text/plain");
  1938. });
  1939. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1940. auto se = detail::scope_exit([&] {
  1941. svr.stop();
  1942. th.join();
  1943. ASSERT_FALSE(svr.is_running());
  1944. });
  1945. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1946. // actually starts anything, so the condition !svr.is_running() will
  1947. // always remain true, and the loop never stops.
  1948. // This basically counts how many milliseconds have passed since the
  1949. // call to svr.listen(), and if after 5 seconds nothing started yet
  1950. // aborts the test.
  1951. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1952. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1953. ASSERT_LT(milliseconds, 5000U);
  1954. }
  1955. {
  1956. Client cli("http://[::1]:1234");
  1957. cli.set_follow_location(true);
  1958. std::string body;
  1959. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1960. body.append(data, data_length);
  1961. return true;
  1962. });
  1963. ASSERT_TRUE(res);
  1964. EXPECT_EQ(StatusCode::OK_200, res->status);
  1965. EXPECT_EQ("Hello World!", body);
  1966. }
  1967. {
  1968. Client cli("http://[::1]:1234");
  1969. std::string body;
  1970. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1971. body.append(data, data_length);
  1972. return true;
  1973. });
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(StatusCode::Found_302, res->status);
  1976. EXPECT_EQ("___", body);
  1977. }
  1978. }
  1979. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1980. Server svr;
  1981. svr.Get("/foo", [](const Request &req, Response &res) {
  1982. auto a = req.params.find("a");
  1983. if (a != req.params.end()) {
  1984. res.set_content((*a).second, "text/plain");
  1985. res.status = StatusCode::OK_200;
  1986. } else {
  1987. res.status = StatusCode::BadRequest_400;
  1988. }
  1989. });
  1990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. {
  1998. Client cli(HOST, PORT);
  1999. cli.set_path_encode(false);
  2000. auto res = cli.Get("/foo?a=explicitly+encoded");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::OK_200, res->status);
  2003. // This expects it back with a space, as the `+` won't have been
  2004. // url-encoded, and server-side the params get decoded turning `+`
  2005. // into spaces.
  2006. EXPECT_EQ("explicitly encoded", res->body);
  2007. }
  2008. }
  2009. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2010. Server svr;
  2011. svr.Get("/", [](const Request &req, Response &) {
  2012. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2013. });
  2014. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2015. auto se = detail::scope_exit([&] {
  2016. svr.stop();
  2017. thread.join();
  2018. ASSERT_FALSE(svr.is_running());
  2019. });
  2020. svr.wait_until_ready();
  2021. {
  2022. Client cli(HOST, PORT);
  2023. cli.set_path_encode(false);
  2024. auto res = cli.Get("/?something=%0A");
  2025. ASSERT_TRUE(res);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. }
  2029. TEST(BindServerTest, DISABLED_BindDualStack) {
  2030. Server svr;
  2031. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2032. res.set_content("Hello World!", "text/plain");
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli("127.0.0.1", PORT);
  2043. auto res = cli.Get("/1");
  2044. ASSERT_TRUE(res);
  2045. EXPECT_EQ(StatusCode::OK_200, res->status);
  2046. EXPECT_EQ("Hello World!", res->body);
  2047. }
  2048. {
  2049. Client cli("::1", PORT);
  2050. auto res = cli.Get("/1");
  2051. ASSERT_TRUE(res);
  2052. EXPECT_EQ(StatusCode::OK_200, res->status);
  2053. EXPECT_EQ("Hello World!", res->body);
  2054. }
  2055. }
  2056. TEST(BindServerTest, BindAndListenSeparately) {
  2057. Server svr;
  2058. int port = svr.bind_to_any_port("0.0.0.0");
  2059. ASSERT_TRUE(svr.is_valid());
  2060. ASSERT_TRUE(port > 0);
  2061. svr.stop();
  2062. }
  2063. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2064. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2066. CLIENT_CA_CERT_DIR);
  2067. int port = svr.bind_to_any_port("0.0.0.0");
  2068. ASSERT_TRUE(svr.is_valid());
  2069. ASSERT_TRUE(port > 0);
  2070. svr.stop();
  2071. }
  2072. #endif
  2073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2074. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2075. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2076. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2077. int port = svr.bind_to_any_port("0.0.0.0");
  2078. ASSERT_TRUE(svr.is_valid());
  2079. ASSERT_TRUE(port > 0);
  2080. svr.stop();
  2081. }
  2082. #endif
  2083. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2084. X509 *readCertificate(const std::string &strFileName) {
  2085. std::ifstream inStream(strFileName);
  2086. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2087. std::istreambuf_iterator<char>());
  2088. if (strCertPEM.empty()) return (nullptr);
  2089. BIO *pbCert = BIO_new(BIO_s_mem());
  2090. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2091. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2092. BIO_free(pbCert);
  2093. return (pCert);
  2094. }
  2095. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2096. std::ifstream inStream(strFileName);
  2097. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2098. std::istreambuf_iterator<char>());
  2099. if (strPrivateKeyPEM.empty()) return (nullptr);
  2100. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2101. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2102. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2103. BIO_free(pbPrivKey);
  2104. return (pPrivateKey);
  2105. }
  2106. TEST(BindServerTest, UpdateCerts) {
  2107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2108. int port = svr.bind_to_any_port("0.0.0.0");
  2109. ASSERT_TRUE(svr.is_valid());
  2110. ASSERT_TRUE(port > 0);
  2111. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2112. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2113. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2114. ASSERT_TRUE(cert != nullptr);
  2115. ASSERT_TRUE(ca_cert != nullptr);
  2116. ASSERT_TRUE(key != nullptr);
  2117. X509_STORE *cert_store = X509_STORE_new();
  2118. X509_STORE_add_cert(cert_store, ca_cert);
  2119. svr.update_certs(cert, key, cert_store);
  2120. ASSERT_TRUE(svr.is_valid());
  2121. svr.stop();
  2122. X509_free(cert);
  2123. X509_free(ca_cert);
  2124. EVP_PKEY_free(key);
  2125. }
  2126. #endif
  2127. TEST(ErrorHandlerTest, ContentLength) {
  2128. Server svr;
  2129. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2130. res.status = StatusCode::OK_200;
  2131. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2132. "text/html"); // <= Content-Length still 13
  2133. });
  2134. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2135. res.set_content("Hello World!\n", "text/plain");
  2136. res.status = 524;
  2137. });
  2138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2139. auto se = detail::scope_exit([&] {
  2140. svr.stop();
  2141. thread.join();
  2142. ASSERT_FALSE(svr.is_running());
  2143. });
  2144. svr.wait_until_ready();
  2145. {
  2146. Client cli(HOST, PORT);
  2147. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(StatusCode::OK_200, res->status);
  2150. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2151. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2152. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2153. }
  2154. }
  2155. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2156. TEST(ExceptionTest, WithoutExceptionHandler) {
  2157. Server svr;
  2158. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2159. throw std::runtime_error("exception...");
  2160. });
  2161. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2162. throw std::runtime_error("exception\r\n...");
  2163. });
  2164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2165. auto se = detail::scope_exit([&] {
  2166. svr.stop();
  2167. listen_thread.join();
  2168. ASSERT_FALSE(svr.is_running());
  2169. });
  2170. svr.wait_until_ready();
  2171. Client cli("localhost", PORT);
  2172. {
  2173. auto res = cli.Get("/exception");
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2177. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2178. }
  2179. {
  2180. auto res = cli.Get("/unknown");
  2181. ASSERT_TRUE(res);
  2182. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2183. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2184. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2185. }
  2186. }
  2187. TEST(ExceptionTest, WithExceptionHandler) {
  2188. Server svr;
  2189. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2190. std::exception_ptr ep) {
  2191. EXPECT_FALSE(ep == nullptr);
  2192. try {
  2193. std::rethrow_exception(ep);
  2194. } catch (std::exception &e) {
  2195. EXPECT_EQ("abc", std::string(e.what()));
  2196. } catch (...) {}
  2197. res.status = StatusCode::InternalServerError_500;
  2198. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2199. "text/html"); // <= Content-Length still 13 at this point
  2200. });
  2201. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2202. res.set_content("Hello World!\n", "text/plain");
  2203. throw std::runtime_error("abc");
  2204. });
  2205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2206. auto se = detail::scope_exit([&] {
  2207. svr.stop();
  2208. thread.join();
  2209. ASSERT_FALSE(svr.is_running());
  2210. });
  2211. svr.wait_until_ready();
  2212. for (size_t i = 0; i < 10; i++) {
  2213. Client cli(HOST, PORT);
  2214. for (size_t j = 0; j < 100; j++) {
  2215. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2216. ASSERT_TRUE(res);
  2217. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2218. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2219. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2221. }
  2222. cli.set_keep_alive(true);
  2223. for (size_t j = 0; j < 100; j++) {
  2224. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2225. ASSERT_TRUE(res);
  2226. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2227. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2228. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2229. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2230. }
  2231. }
  2232. }
  2233. TEST(ExceptionTest, AndErrorHandler) {
  2234. Server svr;
  2235. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2236. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2237. });
  2238. svr.set_exception_handler(
  2239. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2240. EXPECT_FALSE(ep == nullptr);
  2241. try {
  2242. std::rethrow_exception(ep);
  2243. } catch (std::exception &e) {
  2244. res.set_content(e.what(), "text/html");
  2245. } catch (...) {}
  2246. res.status = StatusCode::InternalServerError_500;
  2247. });
  2248. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2249. throw std::runtime_error("EXCEPTION");
  2250. });
  2251. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2252. res.set_content("ERROR", "text/html");
  2253. res.status = StatusCode::InternalServerError_500;
  2254. });
  2255. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2256. auto se = detail::scope_exit([&] {
  2257. svr.stop();
  2258. thread.join();
  2259. ASSERT_FALSE(svr.is_running());
  2260. });
  2261. svr.wait_until_ready();
  2262. Client cli(HOST, PORT);
  2263. {
  2264. auto res = cli.Get("/exception");
  2265. ASSERT_TRUE(res);
  2266. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2267. EXPECT_EQ("EXCEPTION", res->body);
  2268. }
  2269. {
  2270. auto res = cli.Get("/error");
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2273. EXPECT_EQ("ERROR", res->body);
  2274. }
  2275. {
  2276. auto res = cli.Get("/invalid");
  2277. ASSERT_TRUE(res);
  2278. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2279. EXPECT_EQ("NOT_FOUND", res->body);
  2280. }
  2281. }
  2282. #endif
  2283. TEST(NoContentTest, ContentLength) {
  2284. Server svr;
  2285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2286. res.status = StatusCode::NoContent_204;
  2287. });
  2288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2289. auto se = detail::scope_exit([&] {
  2290. svr.stop();
  2291. thread.join();
  2292. ASSERT_FALSE(svr.is_running());
  2293. });
  2294. svr.wait_until_ready();
  2295. {
  2296. Client cli(HOST, PORT);
  2297. auto res = cli.Get("/hi");
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2300. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2301. }
  2302. }
  2303. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2306. ASSERT_TRUE(svr.is_valid());
  2307. #else
  2308. Server svr;
  2309. #endif
  2310. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2311. if (req.path == "/routing_handler") {
  2312. res.set_header("PRE_ROUTING", "on");
  2313. res.set_content("Routing Handler", "text/plain");
  2314. return httplib::Server::HandlerResponse::Handled;
  2315. }
  2316. return httplib::Server::HandlerResponse::Unhandled;
  2317. });
  2318. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2319. res.set_content("Error", "text/html");
  2320. });
  2321. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2322. if (req.path == "/routing_handler") {
  2323. res.set_header("POST_ROUTING", "on");
  2324. }
  2325. });
  2326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2327. res.set_content("Hello World!\n", "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. {
  2337. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2338. SSLClient cli(HOST, PORT);
  2339. cli.enable_server_certificate_verification(false);
  2340. #else
  2341. Client cli(HOST, PORT);
  2342. #endif
  2343. auto res = cli.Get("/routing_handler");
  2344. ASSERT_TRUE(res);
  2345. EXPECT_EQ(StatusCode::OK_200, res->status);
  2346. EXPECT_EQ("Routing Handler", res->body);
  2347. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2348. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2349. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2350. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2351. }
  2352. {
  2353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2354. SSLClient cli(HOST, PORT);
  2355. cli.enable_server_certificate_verification(false);
  2356. #else
  2357. Client cli(HOST, PORT);
  2358. #endif
  2359. auto res = cli.Get("/hi");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::OK_200, res->status);
  2362. EXPECT_EQ("Hello World!\n", res->body);
  2363. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2364. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2365. }
  2366. {
  2367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2368. SSLClient cli(HOST, PORT);
  2369. cli.enable_server_certificate_verification(false);
  2370. #else
  2371. Client cli(HOST, PORT);
  2372. #endif
  2373. auto res = cli.Get("/aaa");
  2374. ASSERT_TRUE(res);
  2375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2376. EXPECT_EQ("Error", res->body);
  2377. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2378. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2379. }
  2380. }
  2381. TEST(RequestHandlerTest, PreRequestHandler) {
  2382. auto route_path = "/user/:user";
  2383. Server svr;
  2384. svr.Get("/hi", [](const Request &, Response &res) {
  2385. res.set_content("hi", "text/plain");
  2386. });
  2387. svr.Get(route_path, [](const Request &req, Response &res) {
  2388. res.set_content(req.path_params.at("user"), "text/plain");
  2389. });
  2390. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2391. if (req.matched_route == route_path) {
  2392. auto user = req.path_params.at("user");
  2393. if (user != "john") {
  2394. res.status = StatusCode::Forbidden_403;
  2395. res.set_content("error", "text/html");
  2396. return Server::HandlerResponse::Handled;
  2397. }
  2398. }
  2399. return Server::HandlerResponse::Unhandled;
  2400. });
  2401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2402. auto se = detail::scope_exit([&] {
  2403. svr.stop();
  2404. thread.join();
  2405. ASSERT_FALSE(svr.is_running());
  2406. });
  2407. svr.wait_until_ready();
  2408. Client cli(HOST, PORT);
  2409. {
  2410. auto res = cli.Get("/hi");
  2411. ASSERT_TRUE(res);
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. EXPECT_EQ("hi", res->body);
  2414. }
  2415. {
  2416. auto res = cli.Get("/user/john");
  2417. ASSERT_TRUE(res);
  2418. EXPECT_EQ(StatusCode::OK_200, res->status);
  2419. EXPECT_EQ("john", res->body);
  2420. }
  2421. {
  2422. auto res = cli.Get("/user/invalid-user");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2425. EXPECT_EQ("error", res->body);
  2426. }
  2427. }
  2428. TEST(InvalidFormatTest, StatusCode) {
  2429. Server svr;
  2430. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2431. res.set_content("Hello World!\n", "text/plain");
  2432. res.status = 9999; // Status should be a three-digit code...
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. {
  2442. Client cli(HOST, PORT);
  2443. auto res = cli.Get("/hi");
  2444. ASSERT_FALSE(res);
  2445. }
  2446. }
  2447. TEST(URLFragmentTest, WithFragment) {
  2448. Server svr;
  2449. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2450. EXPECT_TRUE(req.target == "/hi");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. {
  2460. Client cli(HOST, PORT);
  2461. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2462. EXPECT_TRUE(res);
  2463. EXPECT_EQ(StatusCode::OK_200, res->status);
  2464. res = cli.Get("/hi%23key1=val1=key2=val2");
  2465. EXPECT_TRUE(res);
  2466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2467. }
  2468. }
  2469. TEST(HeaderWriter, SetHeaderWriter) {
  2470. Server svr;
  2471. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2472. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2473. return detail::write_headers(strm, hdrs);
  2474. });
  2475. svr.Get("/hi", [](const Request &req, Response &res) {
  2476. auto it = req.headers.find("CustomClientHeader");
  2477. EXPECT_TRUE(it != req.headers.end());
  2478. EXPECT_EQ(it->second, "CustomClientValue");
  2479. res.set_content("Hello World!\n", "text/plain");
  2480. });
  2481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2482. auto se = detail::scope_exit([&] {
  2483. svr.stop();
  2484. thread.join();
  2485. ASSERT_FALSE(svr.is_running());
  2486. });
  2487. svr.wait_until_ready();
  2488. {
  2489. Client cli(HOST, PORT);
  2490. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2491. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2492. return detail::write_headers(strm, hdrs);
  2493. });
  2494. auto res = cli.Get("/hi");
  2495. EXPECT_TRUE(res);
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. auto it = res->headers.find("CustomServerHeader");
  2498. EXPECT_TRUE(it != res->headers.end());
  2499. EXPECT_EQ(it->second, "CustomServerValue");
  2500. }
  2501. }
  2502. class ServerTest : public ::testing::Test {
  2503. protected:
  2504. ServerTest()
  2505. : cli_(HOST, PORT)
  2506. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2507. ,
  2508. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2509. #endif
  2510. {
  2511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2512. cli_.enable_server_certificate_verification(false);
  2513. #endif
  2514. }
  2515. virtual void SetUp() {
  2516. svr_.set_mount_point("/", "./www");
  2517. svr_.set_mount_point("/mount", "./www2");
  2518. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2519. svr_.Get("/hi",
  2520. [&](const Request & /*req*/, Response &res) {
  2521. res.set_content("Hello World!", "text/plain");
  2522. })
  2523. .Get("/file_content",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. res.set_file_content("./www/dir/test.html");
  2526. })
  2527. .Get("/file_content_with_content_type",
  2528. [&](const Request & /*req*/, Response &res) {
  2529. res.set_file_content("./www/file", "text/plain");
  2530. })
  2531. .Get("/invalid_file_content",
  2532. [&](const Request & /*req*/, Response &res) {
  2533. res.set_file_content("./www/dir/invalid_file_path");
  2534. })
  2535. .Get("/http_response_splitting",
  2536. [&](const Request & /*req*/, Response &res) {
  2537. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2538. EXPECT_EQ(0U, res.headers.size());
  2539. EXPECT_FALSE(res.has_header("a"));
  2540. res.set_header("a", "1\nSet-Cookie: a=1");
  2541. EXPECT_EQ(0U, res.headers.size());
  2542. EXPECT_FALSE(res.has_header("a"));
  2543. res.set_header("a", "1\rSet-Cookie: a=1");
  2544. EXPECT_EQ(0U, res.headers.size());
  2545. EXPECT_FALSE(res.has_header("a"));
  2546. res.set_header("a\r\nb", "0");
  2547. EXPECT_EQ(0U, res.headers.size());
  2548. EXPECT_FALSE(res.has_header("a"));
  2549. res.set_header("a\rb", "0");
  2550. EXPECT_EQ(0U, res.headers.size());
  2551. EXPECT_FALSE(res.has_header("a"));
  2552. res.set_header("a\nb", "0");
  2553. EXPECT_EQ(0U, res.headers.size());
  2554. EXPECT_FALSE(res.has_header("a"));
  2555. res.set_redirect("1\r\nSet-Cookie: a=1");
  2556. EXPECT_EQ(0U, res.headers.size());
  2557. EXPECT_FALSE(res.has_header("Location"));
  2558. })
  2559. .Get("/slow",
  2560. [&](const Request & /*req*/, Response &res) {
  2561. std::this_thread::sleep_for(std::chrono::seconds(2));
  2562. res.set_content("slow", "text/plain");
  2563. })
  2564. #if 0
  2565. .Post("/slowpost",
  2566. [&](const Request & /*req*/, Response &res) {
  2567. std::this_thread::sleep_for(std::chrono::seconds(2));
  2568. res.set_content("slow", "text/plain");
  2569. })
  2570. #endif
  2571. .Get("/remote_addr",
  2572. [&](const Request &req, Response &res) {
  2573. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2574. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2575. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2576. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2577. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2578. #endif
  2579. res.set_content(req.remote_addr, "text/plain");
  2580. })
  2581. .Get("/local_addr",
  2582. [&](const Request &req, Response &res) {
  2583. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2584. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2585. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2586. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2587. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2588. #endif
  2589. auto local_addr = req.local_addr;
  2590. auto local_port = std::to_string(req.local_port);
  2591. res.set_content(local_addr.append(":").append(local_port),
  2592. "text/plain");
  2593. })
  2594. .Get("/endwith%",
  2595. [&](const Request & /*req*/, Response &res) {
  2596. res.set_content("Hello World!", "text/plain");
  2597. })
  2598. .Get("/a\\+\\+b",
  2599. [&](const Request &req, Response &res) {
  2600. ASSERT_TRUE(req.has_param("a +b"));
  2601. auto val = req.get_param_value("a +b");
  2602. res.set_content(val, "text/plain");
  2603. })
  2604. .Get("/", [&](const Request & /*req*/,
  2605. Response &res) { res.set_redirect("/hi"); })
  2606. .Post("/1",
  2607. [](const Request & /*req*/, Response &res) {
  2608. res.set_redirect("/2", StatusCode::SeeOther_303);
  2609. })
  2610. .Get("/2",
  2611. [](const Request & /*req*/, Response &res) {
  2612. res.set_content("redirected.", "text/plain");
  2613. res.status = StatusCode::OK_200;
  2614. })
  2615. .Post("/person",
  2616. [&](const Request &req, Response &res) {
  2617. if (req.has_param("name") && req.has_param("note")) {
  2618. persons_[req.get_param_value("name")] =
  2619. req.get_param_value("note");
  2620. } else {
  2621. res.status = StatusCode::BadRequest_400;
  2622. }
  2623. })
  2624. .Put("/person",
  2625. [&](const Request &req, Response &res) {
  2626. if (req.has_param("name") && req.has_param("note")) {
  2627. persons_[req.get_param_value("name")] =
  2628. req.get_param_value("note");
  2629. } else {
  2630. res.status = StatusCode::BadRequest_400;
  2631. }
  2632. })
  2633. .Get("/person/(.*)",
  2634. [&](const Request &req, Response &res) {
  2635. string name = req.matches[1];
  2636. if (persons_.find(name) != persons_.end()) {
  2637. auto note = persons_[name];
  2638. res.set_content(note, "text/plain");
  2639. } else {
  2640. res.status = StatusCode::NotFound_404;
  2641. }
  2642. })
  2643. .Delete("/person",
  2644. [&](const Request &req, Response &res) {
  2645. if (req.has_param("name")) {
  2646. string name = req.get_param_value("name");
  2647. if (persons_.find(name) != persons_.end()) {
  2648. persons_.erase(name);
  2649. res.set_content("DELETED", "text/plain");
  2650. } else {
  2651. res.status = StatusCode::NotFound_404;
  2652. }
  2653. } else {
  2654. res.status = StatusCode::BadRequest_400;
  2655. }
  2656. })
  2657. .Post("/x-www-form-urlencoded-json",
  2658. [&](const Request &req, Response &res) {
  2659. auto json = req.get_param_value("json");
  2660. ASSERT_EQ(JSON_DATA, json);
  2661. res.set_content(json, "appliation/json");
  2662. res.status = StatusCode::OK_200;
  2663. })
  2664. .Get("/streamed-chunked",
  2665. [&](const Request & /*req*/, Response &res) {
  2666. res.set_chunked_content_provider(
  2667. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2668. sink.os << "123";
  2669. sink.os << "456";
  2670. sink.os << "789";
  2671. sink.done();
  2672. return true;
  2673. });
  2674. })
  2675. .Get("/streamed-chunked-with-prohibited-trailer",
  2676. [&](const Request & /*req*/, Response &res) {
  2677. auto i = new int(0);
  2678. // Declare both a prohibited trailer (Content-Length) and an
  2679. // allowed one
  2680. res.set_header("Trailer", "Content-Length, X-Allowed");
  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. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  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-chunked2",
  2702. [&](const Request & /*req*/, Response &res) {
  2703. auto i = new int(0);
  2704. res.set_chunked_content_provider(
  2705. "text/plain",
  2706. [i](size_t /*offset*/, DataSink &sink) {
  2707. switch (*i) {
  2708. case 0: sink.os << "123"; break;
  2709. case 1: sink.os << "456"; break;
  2710. case 2: sink.os << "789"; break;
  2711. case 3: sink.done(); break;
  2712. }
  2713. (*i)++;
  2714. return true;
  2715. },
  2716. [i](bool success) {
  2717. EXPECT_TRUE(success);
  2718. delete i;
  2719. });
  2720. })
  2721. .Get("/streamed-chunked-with-trailer",
  2722. [&](const Request & /*req*/, Response &res) {
  2723. auto i = new int(0);
  2724. res.set_header("Trailer", "Dummy1, Dummy2");
  2725. res.set_chunked_content_provider(
  2726. "text/plain",
  2727. [i](size_t /*offset*/, DataSink &sink) {
  2728. switch (*i) {
  2729. case 0: sink.os << "123"; break;
  2730. case 1: sink.os << "456"; break;
  2731. case 2: sink.os << "789"; break;
  2732. case 3: {
  2733. sink.done_with_trailer(
  2734. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2735. } break;
  2736. }
  2737. (*i)++;
  2738. return true;
  2739. },
  2740. [i](bool success) {
  2741. EXPECT_TRUE(success);
  2742. delete i;
  2743. });
  2744. })
  2745. .Get("/streamed",
  2746. [&](const Request & /*req*/, Response &res) {
  2747. res.set_content_provider(
  2748. 6, "text/plain",
  2749. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2750. sink.os << (offset < 3 ? "a" : "b");
  2751. return true;
  2752. });
  2753. })
  2754. .Get("/streamed-with-range",
  2755. [&](const Request &req, Response &res) {
  2756. auto data = new std::string("abcdefg");
  2757. res.set_content_provider(
  2758. data->size(), "text/plain",
  2759. [data](size_t offset, size_t length, DataSink &sink) {
  2760. size_t DATA_CHUNK_SIZE = 4;
  2761. const auto &d = *data;
  2762. auto out_len =
  2763. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2764. auto ret =
  2765. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2766. EXPECT_TRUE(ret);
  2767. return true;
  2768. },
  2769. [data, &req](bool success) {
  2770. EXPECT_EQ(success, !req.has_param("error"));
  2771. delete data;
  2772. });
  2773. })
  2774. .Get("/streamed-cancel",
  2775. [&](const Request & /*req*/, Response &res) {
  2776. res.set_content_provider(
  2777. size_t(-1), "text/plain",
  2778. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2779. sink.os << "data_chunk";
  2780. return true;
  2781. });
  2782. })
  2783. .Get("/regex-with-delimiter",
  2784. [&](const Request &req, Response & /*res*/) {
  2785. ASSERT_TRUE(req.has_param("key"));
  2786. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2787. })
  2788. .Get("/with-range",
  2789. [&](const Request & /*req*/, Response &res) {
  2790. res.set_content("abcdefg", "text/plain");
  2791. })
  2792. .Get("/test-start-time",
  2793. [&](const Request &req, Response & /*res*/) {
  2794. EXPECT_NE(req.start_time_,
  2795. std::chrono::steady_clock::time_point::min());
  2796. })
  2797. .Get("/with-range-customized-response",
  2798. [&](const Request & /*req*/, Response &res) {
  2799. res.status = StatusCode::BadRequest_400;
  2800. res.set_content(JSON_DATA, "application/json");
  2801. })
  2802. .Post("/chunked",
  2803. [&](const Request &req, Response & /*res*/) {
  2804. EXPECT_EQ(req.body, "dechunked post body");
  2805. })
  2806. .Post("/large-chunked",
  2807. [&](const Request &req, Response & /*res*/) {
  2808. std::string expected(6 * 30 * 1024u, 'a');
  2809. EXPECT_EQ(req.body, expected);
  2810. })
  2811. .Post("/multipart",
  2812. [&](const Request &req, Response & /*res*/) {
  2813. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2814. req.form.get_field_count("text2") +
  2815. req.form.get_field_count("file3") +
  2816. req.form.get_field_count("file4"));
  2817. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2818. req.form.get_file_count("file2"));
  2819. ASSERT_TRUE(!req.form.has_file("???"));
  2820. ASSERT_TRUE(!req.form.has_field("???"));
  2821. ASSERT_TRUE(req.body.empty());
  2822. {
  2823. const auto &text = req.form.get_field("text1");
  2824. EXPECT_EQ("text default", text);
  2825. }
  2826. {
  2827. const auto &text = req.form.get_field("text2");
  2828. EXPECT_EQ("aωb", text);
  2829. }
  2830. {
  2831. const auto &file = req.form.get_file("file1");
  2832. EXPECT_EQ("hello.txt", file.filename);
  2833. EXPECT_EQ("text/plain", file.content_type);
  2834. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2835. }
  2836. {
  2837. const auto &file = req.form.get_file("file2");
  2838. EXPECT_EQ("world.json", file.filename);
  2839. EXPECT_EQ("application/json", file.content_type);
  2840. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2841. }
  2842. {
  2843. const auto &text = req.form.get_field("file3");
  2844. EXPECT_EQ(0u, text.size());
  2845. }
  2846. {
  2847. const auto &text = req.form.get_field("file4");
  2848. EXPECT_EQ(0u, text.size());
  2849. }
  2850. })
  2851. .Post("/multipart/multi_file_values",
  2852. [&](const Request &req, Response & /*res*/) {
  2853. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2854. req.form.get_field_count("multi_text1"));
  2855. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2856. ASSERT_TRUE(!req.form.has_file("???"));
  2857. ASSERT_TRUE(!req.form.has_field("???"));
  2858. ASSERT_TRUE(req.body.empty());
  2859. {
  2860. const auto &text = req.form.get_field("text");
  2861. EXPECT_EQ("default text", text);
  2862. }
  2863. {
  2864. const auto &text1_values = req.form.get_fields("multi_text1");
  2865. EXPECT_EQ(2u, text1_values.size());
  2866. EXPECT_EQ("aaaaa", text1_values[0]);
  2867. EXPECT_EQ("bbbbb", text1_values[1]);
  2868. }
  2869. {
  2870. const auto &file1_values = req.form.get_files("multi_file1");
  2871. EXPECT_EQ(2u, file1_values.size());
  2872. auto file1 = file1_values[0];
  2873. EXPECT_EQ(file1.filename, "hello.txt");
  2874. EXPECT_EQ(file1.content_type, "text/plain");
  2875. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2876. auto file2 = file1_values[1];
  2877. EXPECT_EQ(file2.filename, "world.json");
  2878. EXPECT_EQ(file2.content_type, "application/json");
  2879. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2880. }
  2881. })
  2882. .Post("/empty",
  2883. [&](const Request &req, Response &res) {
  2884. EXPECT_EQ(req.body, "");
  2885. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2886. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2887. res.set_content("empty", "text/plain");
  2888. })
  2889. .Post("/empty-no-content-type",
  2890. [&](const Request &req, Response &res) {
  2891. EXPECT_EQ(req.body, "");
  2892. EXPECT_FALSE(req.has_header("Content-Type"));
  2893. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2894. res.set_content("empty-no-content-type", "text/plain");
  2895. })
  2896. .Post("/path-only",
  2897. [&](const Request &req, Response &res) {
  2898. EXPECT_EQ(req.body, "");
  2899. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2900. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2901. res.set_content("path-only", "text/plain");
  2902. })
  2903. .Post("/path-headers-only",
  2904. [&](const Request &req, Response &res) {
  2905. EXPECT_EQ(req.body, "");
  2906. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2907. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2908. EXPECT_EQ("world", req.get_header_value("hello"));
  2909. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2910. res.set_content("path-headers-only", "text/plain");
  2911. })
  2912. .Post("/post-large",
  2913. [&](const Request &req, Response &res) {
  2914. EXPECT_EQ(req.body, LARGE_DATA);
  2915. res.set_content(req.body, "text/plain");
  2916. })
  2917. .Post("/post-loopback",
  2918. [&](const Request &, Response &res,
  2919. ContentReader const &content_reader) {
  2920. std::string body;
  2921. content_reader([&](const char *data, size_t data_length) {
  2922. body.append(data, data_length);
  2923. return true;
  2924. });
  2925. res.set_content(body, "text/plain");
  2926. })
  2927. .Put("/put-loopback",
  2928. [&](const Request &, Response &res,
  2929. ContentReader const &content_reader) {
  2930. std::string body;
  2931. content_reader([&](const char *data, size_t data_length) {
  2932. body.append(data, data_length);
  2933. return true;
  2934. });
  2935. res.set_content(body, "text/plain");
  2936. })
  2937. .Patch("/patch-loopback",
  2938. [&](const Request &, Response &res,
  2939. ContentReader const &content_reader) {
  2940. std::string body;
  2941. content_reader([&](const char *data, size_t data_length) {
  2942. body.append(data, data_length);
  2943. return true;
  2944. });
  2945. res.set_content(body, "text/plain");
  2946. })
  2947. .Put("/empty-no-content-type",
  2948. [&](const Request &req, Response &res) {
  2949. EXPECT_EQ(req.body, "");
  2950. EXPECT_FALSE(req.has_header("Content-Type"));
  2951. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2952. res.set_content("empty-no-content-type", "text/plain");
  2953. })
  2954. .Put("/put",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "PUT");
  2957. res.set_content(req.body, "text/plain");
  2958. })
  2959. .Put("/put-large",
  2960. [&](const Request &req, Response &res) {
  2961. EXPECT_EQ(req.body, LARGE_DATA);
  2962. res.set_content(req.body, "text/plain");
  2963. })
  2964. .Patch("/patch",
  2965. [&](const Request &req, Response &res) {
  2966. EXPECT_EQ(req.body, "PATCH");
  2967. res.set_content(req.body, "text/plain");
  2968. })
  2969. .Delete("/delete",
  2970. [&](const Request & /*req*/, Response &res) {
  2971. res.set_content("DELETE", "text/plain");
  2972. })
  2973. .Delete("/delete-body",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(req.body, "content");
  2976. res.set_content(req.body, "text/plain");
  2977. })
  2978. .Options(R"(\*)",
  2979. [&](const Request & /*req*/, Response &res) {
  2980. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2981. })
  2982. .Get("/request-target",
  2983. [&](const Request &req, Response & /*res*/) {
  2984. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2985. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2986. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2987. })
  2988. .Get("/long-query-value",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2991. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2992. })
  2993. .Get("/too-long-query-value",
  2994. [&](const Request &req, Response & /*res*/) {
  2995. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2996. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2997. })
  2998. .Get("/array-param",
  2999. [&](const Request &req, Response & /*res*/) {
  3000. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3001. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3002. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3003. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3004. })
  3005. .Post("/validate-no-multiple-headers",
  3006. [&](const Request &req, Response & /*res*/) {
  3007. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3008. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3009. })
  3010. .Post("/content_receiver",
  3011. [&](const Request &req, Response &res,
  3012. const ContentReader &content_reader) {
  3013. if (req.is_multipart_form_data()) {
  3014. std::vector<FormData> items;
  3015. content_reader(
  3016. [&](const FormData &file) {
  3017. items.push_back(file);
  3018. return true;
  3019. },
  3020. [&](const char *data, size_t data_length) {
  3021. items.back().content.append(data, data_length);
  3022. return true;
  3023. });
  3024. EXPECT_EQ(5u, items.size());
  3025. {
  3026. const auto &file = get_file_value(items, "text1");
  3027. EXPECT_TRUE(file.filename.empty());
  3028. EXPECT_EQ("text default", file.content);
  3029. }
  3030. {
  3031. const auto &file = get_file_value(items, "text2");
  3032. EXPECT_TRUE(file.filename.empty());
  3033. EXPECT_EQ("aωb", file.content);
  3034. }
  3035. {
  3036. const auto &file = get_file_value(items, "file1");
  3037. EXPECT_EQ("hello.txt", file.filename);
  3038. EXPECT_EQ("text/plain", file.content_type);
  3039. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3040. }
  3041. {
  3042. const auto &file = get_file_value(items, "file2");
  3043. EXPECT_EQ("world.json", file.filename);
  3044. EXPECT_EQ("application/json", file.content_type);
  3045. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3046. }
  3047. {
  3048. const auto &file = get_file_value(items, "file3");
  3049. EXPECT_TRUE(file.filename.empty());
  3050. EXPECT_EQ("application/octet-stream", file.content_type);
  3051. EXPECT_EQ(0u, file.content.size());
  3052. }
  3053. } else {
  3054. std::string body;
  3055. content_reader([&](const char *data, size_t data_length) {
  3056. EXPECT_EQ(7U, data_length);
  3057. body.append(data, data_length);
  3058. return true;
  3059. });
  3060. EXPECT_EQ(body, "content");
  3061. res.set_content(body, "text/plain");
  3062. }
  3063. })
  3064. .Put("/content_receiver",
  3065. [&](const Request & /*req*/, Response &res,
  3066. const ContentReader &content_reader) {
  3067. std::string body;
  3068. content_reader([&](const char *data, size_t data_length) {
  3069. body.append(data, data_length);
  3070. return true;
  3071. });
  3072. EXPECT_EQ(body, "content");
  3073. res.set_content(body, "text/plain");
  3074. })
  3075. .Patch("/content_receiver",
  3076. [&](const Request & /*req*/, Response &res,
  3077. const ContentReader &content_reader) {
  3078. std::string body;
  3079. content_reader([&](const char *data, size_t data_length) {
  3080. body.append(data, data_length);
  3081. return true;
  3082. });
  3083. EXPECT_EQ(body, "content");
  3084. res.set_content(body, "text/plain");
  3085. })
  3086. .Post("/query-string-and-body",
  3087. [&](const Request &req, Response & /*res*/) {
  3088. ASSERT_TRUE(req.has_param("key"));
  3089. EXPECT_EQ(req.get_param_value("key"), "value");
  3090. EXPECT_EQ(req.body, "content");
  3091. })
  3092. .Get("/last-request",
  3093. [&](const Request &req, Response & /*res*/) {
  3094. EXPECT_EQ("close", req.get_header_value("Connection"));
  3095. })
  3096. .Get(R"(/redirect/(\d+))",
  3097. [&](const Request &req, Response &res) {
  3098. auto num = std::stoi(req.matches[1]) + 1;
  3099. std::string url = "/redirect/" + std::to_string(num);
  3100. res.set_redirect(url);
  3101. })
  3102. .Post("/binary",
  3103. [&](const Request &req, Response &res) {
  3104. EXPECT_EQ(4U, req.body.size());
  3105. EXPECT_EQ("application/octet-stream",
  3106. req.get_header_value("Content-Type"));
  3107. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3108. res.set_content(req.body, "application/octet-stream");
  3109. })
  3110. .Put("/binary",
  3111. [&](const Request &req, Response &res) {
  3112. EXPECT_EQ(4U, req.body.size());
  3113. EXPECT_EQ("application/octet-stream",
  3114. req.get_header_value("Content-Type"));
  3115. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3116. res.set_content(req.body, "application/octet-stream");
  3117. })
  3118. .Patch("/binary",
  3119. [&](const Request &req, Response &res) {
  3120. EXPECT_EQ(4U, req.body.size());
  3121. EXPECT_EQ("application/octet-stream",
  3122. req.get_header_value("Content-Type"));
  3123. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3124. res.set_content(req.body, "application/octet-stream");
  3125. })
  3126. .Delete("/binary",
  3127. [&](const Request &req, Response &res) {
  3128. EXPECT_EQ(4U, req.body.size());
  3129. EXPECT_EQ("application/octet-stream",
  3130. req.get_header_value("Content-Type"));
  3131. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3132. res.set_content(req.body, "application/octet-stream");
  3133. })
  3134. .Get("/issue1772",
  3135. [&](const Request & /*req*/, Response &res) {
  3136. res.status = 401;
  3137. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3138. })
  3139. .Delete("/issue609",
  3140. [](const httplib::Request &, httplib::Response &res,
  3141. const httplib::ContentReader &) {
  3142. res.set_content("ok", "text/plain");
  3143. })
  3144. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3145. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3146. .Get("/compress",
  3147. [&](const Request & /*req*/, Response &res) {
  3148. res.set_content(
  3149. "12345678901234567890123456789012345678901234567890123456789"
  3150. "01234567890123456789012345678901234567890",
  3151. "text/plain");
  3152. })
  3153. .Get("/nocompress",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content(
  3156. "12345678901234567890123456789012345678901234567890123456789"
  3157. "01234567890123456789012345678901234567890",
  3158. "application/octet-stream");
  3159. })
  3160. .Post("/compress-multipart",
  3161. [&](const Request &req, Response & /*res*/) {
  3162. EXPECT_EQ(2u, req.form.fields.size());
  3163. ASSERT_TRUE(!req.form.has_field("???"));
  3164. {
  3165. const auto &text = req.form.get_field("key1");
  3166. EXPECT_EQ("test", text);
  3167. }
  3168. {
  3169. const auto &text = req.form.get_field("key2");
  3170. EXPECT_EQ("--abcdefg123", text);
  3171. }
  3172. })
  3173. #endif
  3174. ;
  3175. persons_["john"] = "programmer";
  3176. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3177. svr_.wait_until_ready();
  3178. }
  3179. virtual void TearDown() {
  3180. svr_.stop();
  3181. if (!request_threads_.empty()) {
  3182. std::this_thread::sleep_for(std::chrono::seconds(1));
  3183. for (auto &t : request_threads_) {
  3184. t.join();
  3185. }
  3186. }
  3187. t_.join();
  3188. }
  3189. map<string, string> persons_;
  3190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3191. SSLClient cli_;
  3192. SSLServer svr_;
  3193. #else
  3194. Client cli_;
  3195. Server svr_;
  3196. #endif
  3197. thread t_;
  3198. std::vector<thread> request_threads_;
  3199. };
  3200. TEST_F(ServerTest, GetMethod200) {
  3201. auto res = cli_.Get("/hi");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ("HTTP/1.1", res->version);
  3204. EXPECT_EQ(StatusCode::OK_200, res->status);
  3205. EXPECT_EQ("OK", res->reason);
  3206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3207. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3208. EXPECT_EQ("Hello World!", res->body);
  3209. }
  3210. TEST_F(ServerTest, GetEmptyFile) {
  3211. auto res = cli_.Get("/empty_file");
  3212. ASSERT_TRUE(res);
  3213. EXPECT_EQ(StatusCode::OK_200, res->status);
  3214. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3215. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3216. EXPECT_EQ("", res->body);
  3217. }
  3218. TEST_F(ServerTest, GetFileContent) {
  3219. auto res = cli_.Get("/file_content");
  3220. ASSERT_TRUE(res);
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3223. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3224. EXPECT_EQ("test.html", res->body);
  3225. }
  3226. TEST_F(ServerTest, GetFileContentWithRange) {
  3227. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3230. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3231. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3232. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3233. EXPECT_EQ("est", res->body);
  3234. }
  3235. TEST_F(ServerTest, GetFileContentWithContentType) {
  3236. auto res = cli_.Get("/file_content_with_content_type");
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ(StatusCode::OK_200, res->status);
  3239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3240. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3241. EXPECT_EQ("file\n", res->body);
  3242. }
  3243. TEST_F(ServerTest, GetInvalidFileContent) {
  3244. auto res = cli_.Get("/invalid_file_content");
  3245. ASSERT_TRUE(res);
  3246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3247. }
  3248. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3249. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3250. ASSERT_TRUE(res);
  3251. EXPECT_EQ("HTTP/1.1", res->version);
  3252. EXPECT_EQ(StatusCode::OK_200, res->status);
  3253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3254. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3255. EXPECT_EQ("Hello World!", res->body);
  3256. }
  3257. TEST_F(ServerTest, GetMethod302) {
  3258. auto res = cli_.Get("/");
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::Found_302, res->status);
  3261. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3262. }
  3263. TEST_F(ServerTest, GetMethod302Redirect) {
  3264. cli_.set_follow_location(true);
  3265. auto res = cli_.Get("/");
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. EXPECT_EQ("Hello World!", res->body);
  3269. EXPECT_EQ("/hi", res->location);
  3270. }
  3271. TEST_F(ServerTest, GetMethod404) {
  3272. auto res = cli_.Get("/invalid");
  3273. ASSERT_TRUE(res);
  3274. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3275. }
  3276. TEST_F(ServerTest, HeadMethod200) {
  3277. auto res = cli_.Head("/hi");
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::OK_200, res->status);
  3280. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3281. EXPECT_TRUE(res->body.empty());
  3282. }
  3283. TEST_F(ServerTest, HeadMethod200Static) {
  3284. auto res = cli_.Head("/mount/dir/index.html");
  3285. ASSERT_TRUE(res);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3288. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3289. EXPECT_TRUE(res->body.empty());
  3290. }
  3291. TEST_F(ServerTest, HeadMethod404) {
  3292. auto res = cli_.Head("/invalid");
  3293. ASSERT_TRUE(res);
  3294. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3295. EXPECT_TRUE(res->body.empty());
  3296. }
  3297. TEST_F(ServerTest, GetMethodPersonJohn) {
  3298. auto res = cli_.Get("/person/john");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3302. EXPECT_EQ("programmer", res->body);
  3303. }
  3304. TEST_F(ServerTest, PostMethod1) {
  3305. auto res = cli_.Get("/person/john1");
  3306. ASSERT_TRUE(res);
  3307. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3308. res = cli_.Post("/person", "name=john1&note=coder",
  3309. "application/x-www-form-urlencoded");
  3310. ASSERT_TRUE(res);
  3311. ASSERT_EQ(StatusCode::OK_200, res->status);
  3312. res = cli_.Get("/person/john1");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::OK_200, res->status);
  3315. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3316. ASSERT_EQ("coder", res->body);
  3317. }
  3318. TEST_F(ServerTest, PostMethod2) {
  3319. auto res = cli_.Get("/person/john2");
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3322. Params params;
  3323. params.emplace("name", "john2");
  3324. params.emplace("note", "coder");
  3325. res = cli_.Post("/person", params);
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::OK_200, res->status);
  3328. res = cli_.Get("/person/john2");
  3329. ASSERT_TRUE(res);
  3330. ASSERT_EQ(StatusCode::OK_200, res->status);
  3331. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. ASSERT_EQ("coder", res->body);
  3333. }
  3334. TEST_F(ServerTest, PutMethod3) {
  3335. auto res = cli_.Get("/person/john3");
  3336. ASSERT_TRUE(res);
  3337. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3338. Params params;
  3339. params.emplace("name", "john3");
  3340. params.emplace("note", "coder");
  3341. res = cli_.Put("/person", params);
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::OK_200, res->status);
  3344. res = cli_.Get("/person/john3");
  3345. ASSERT_TRUE(res);
  3346. ASSERT_EQ(StatusCode::OK_200, res->status);
  3347. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3348. ASSERT_EQ("coder", res->body);
  3349. }
  3350. TEST_F(ServerTest, DeleteMethod1) {
  3351. auto res = cli_.Get("/person/john4");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3354. Params params;
  3355. params.emplace("name", "john4");
  3356. params.emplace("note", "coder");
  3357. res = cli_.Post("/person", params);
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::OK_200, res->status);
  3360. res = cli_.Get("/person/john4");
  3361. ASSERT_TRUE(res);
  3362. ASSERT_EQ(StatusCode::OK_200, res->status);
  3363. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3364. ASSERT_EQ("coder", res->body);
  3365. Params delete_params;
  3366. delete_params.emplace("name", "john4");
  3367. res = cli_.Delete("/person", delete_params);
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("DELETED", res->body);
  3371. res = cli_.Get("/person/john4");
  3372. ASSERT_TRUE(res);
  3373. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3374. }
  3375. TEST_F(ServerTest, DeleteMethod2) {
  3376. auto res = cli_.Get("/person/john5");
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3379. Params params;
  3380. params.emplace("name", "john5");
  3381. params.emplace("note", "developer");
  3382. res = cli_.Post("/person", params);
  3383. ASSERT_TRUE(res);
  3384. ASSERT_EQ(StatusCode::OK_200, res->status);
  3385. res = cli_.Get("/person/john5");
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::OK_200, res->status);
  3388. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3389. ASSERT_EQ("developer", res->body);
  3390. Params delete_params;
  3391. delete_params.emplace("name", "john5");
  3392. Headers headers;
  3393. headers.emplace("Custom-Header", "test-value");
  3394. res = cli_.Delete("/person", headers, delete_params);
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("DELETED", res->body);
  3398. res = cli_.Get("/person/john5");
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3401. }
  3402. TEST_F(ServerTest, DeleteMethod3) {
  3403. auto res = cli_.Get("/person/john6");
  3404. ASSERT_TRUE(res);
  3405. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3406. Params params;
  3407. params.emplace("name", "john6");
  3408. params.emplace("note", "tester");
  3409. res = cli_.Post("/person", params);
  3410. ASSERT_TRUE(res);
  3411. ASSERT_EQ(StatusCode::OK_200, res->status);
  3412. res = cli_.Get("/person/john6");
  3413. ASSERT_TRUE(res);
  3414. ASSERT_EQ(StatusCode::OK_200, res->status);
  3415. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3416. ASSERT_EQ("tester", res->body);
  3417. Params delete_params;
  3418. delete_params.emplace("name", "john6");
  3419. Headers headers;
  3420. headers.emplace("Custom-Header", "test-value");
  3421. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3422. ASSERT_TRUE(res);
  3423. ASSERT_EQ(StatusCode::OK_200, res->status);
  3424. ASSERT_EQ("DELETED", res->body);
  3425. res = cli_.Get("/person/john6");
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3428. }
  3429. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3430. Params params;
  3431. params.emplace("json", JSON_DATA);
  3432. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::OK_200, res->status);
  3435. ASSERT_EQ(JSON_DATA, res->body);
  3436. }
  3437. TEST_F(ServerTest, PostEmptyContent) {
  3438. auto res = cli_.Post("/empty", "", "text/plain");
  3439. ASSERT_TRUE(res);
  3440. ASSERT_EQ(StatusCode::OK_200, res->status);
  3441. ASSERT_EQ("empty", res->body);
  3442. }
  3443. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3444. auto res = cli_.Post("/empty-no-content-type");
  3445. ASSERT_TRUE(res);
  3446. ASSERT_EQ(StatusCode::OK_200, res->status);
  3447. ASSERT_EQ("empty-no-content-type", res->body);
  3448. }
  3449. TEST_F(ServerTest, PostPathOnly) {
  3450. auto res = cli_.Post("/path-only");
  3451. ASSERT_TRUE(res);
  3452. ASSERT_EQ(StatusCode::OK_200, res->status);
  3453. ASSERT_EQ("path-only", res->body);
  3454. }
  3455. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3456. auto res = cli_.Post("/path-headers-only",
  3457. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::OK_200, res->status);
  3460. ASSERT_EQ("path-headers-only", res->body);
  3461. }
  3462. TEST_F(ServerTest, PostLarge) {
  3463. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ(LARGE_DATA, res->body);
  3467. }
  3468. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3469. auto res = cli_.Put("/empty-no-content-type");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("empty-no-content-type", res->body);
  3473. }
  3474. TEST_F(ServerTest, GetMethodDir) {
  3475. auto res = cli_.Get("/dir/");
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3479. auto body = R"(<html>
  3480. <head>
  3481. </head>
  3482. <body>
  3483. <a href="/dir/test.html">Test</a>
  3484. <a href="/hi">hi</a>
  3485. </body>
  3486. </html>
  3487. )";
  3488. EXPECT_EQ(body, res->body);
  3489. }
  3490. TEST_F(ServerTest, GetMethodDirTest) {
  3491. auto res = cli_.Get("/dir/test.html");
  3492. ASSERT_TRUE(res);
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3495. EXPECT_EQ("test.html", res->body);
  3496. }
  3497. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3498. auto res = cli_.Get("/dir/../dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::OK_200, res->status);
  3501. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3502. EXPECT_EQ("test.html", res->body);
  3503. }
  3504. TEST_F(ServerTest, GetMethodInvalidPath) {
  3505. auto res = cli_.Get("/dir/../test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3508. }
  3509. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3510. auto res = cli_.Get("/../www/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3513. }
  3514. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3515. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3516. ASSERT_TRUE(res);
  3517. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3518. }
  3519. TEST_F(ServerTest, GetMethodDirMountTest) {
  3520. auto res = cli_.Get("/mount/dir/test.html");
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3524. EXPECT_EQ("test.html", res->body);
  3525. }
  3526. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3527. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("test.html", res->body);
  3532. }
  3533. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3534. auto res = cli_.Get("/mount/dir/../test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3539. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3542. }
  3543. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3544. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3545. ASSERT_TRUE(res);
  3546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3547. }
  3548. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3549. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3550. ASSERT_TRUE(res);
  3551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3552. }
  3553. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3554. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3555. ASSERT_TRUE(res);
  3556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3557. }
  3558. TEST_F(ServerTest, PostMethod303) {
  3559. auto res = cli_.Post("/1", "body", "text/plain");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3562. EXPECT_EQ("/2", res->get_header_value("Location"));
  3563. }
  3564. TEST_F(ServerTest, PostMethod303Redirect) {
  3565. cli_.set_follow_location(true);
  3566. auto res = cli_.Post("/1", "body", "text/plain");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("redirected.", res->body);
  3570. EXPECT_EQ("/2", res->location);
  3571. }
  3572. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3573. auto res = cli_.Get("/dir/test.abcde");
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3577. EXPECT_EQ("abcde", res->body);
  3578. }
  3579. TEST_F(ServerTest, StaticFileRange) {
  3580. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3583. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3584. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3585. EXPECT_EQ(true, res->has_header("Content-Range"));
  3586. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3587. EXPECT_EQ(std::string("cd"), res->body);
  3588. }
  3589. TEST_F(ServerTest, StaticFileRanges) {
  3590. auto res =
  3591. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3594. EXPECT_TRUE(
  3595. res->get_header_value("Content-Type")
  3596. .find(
  3597. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3598. 0);
  3599. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3600. }
  3601. TEST_F(ServerTest, StaticFileRangeHead) {
  3602. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3603. ASSERT_TRUE(res);
  3604. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3605. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3606. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3607. EXPECT_EQ(true, res->has_header("Content-Range"));
  3608. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3609. }
  3610. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3611. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3615. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3616. EXPECT_EQ(true, res->has_header("Content-Range"));
  3617. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3618. res->get_header_value("Content-Range"));
  3619. EXPECT_EQ("LAST\n", res->body);
  3620. }
  3621. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3622. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3625. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3626. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3627. EXPECT_EQ(true, res->has_header("Content-Range"));
  3628. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3629. }
  3630. TEST_F(ServerTest, StaticFileBigFile) {
  3631. auto res = cli_.Get("/dir/1MB.txt");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3636. }
  3637. TEST_F(ServerTest, InvalidBaseDirMount) {
  3638. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3639. }
  3640. TEST_F(ServerTest, Binary) {
  3641. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3642. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3643. "application/octet-stream");
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(4U, res->body.size());
  3647. res = cli_.Put("/binary", binary.data(), binary.size(),
  3648. "application/octet-stream");
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ(4U, res->body.size());
  3652. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3653. "application/octet-stream");
  3654. ASSERT_TRUE(res);
  3655. ASSERT_EQ(StatusCode::OK_200, res->status);
  3656. ASSERT_EQ(4U, res->body.size());
  3657. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3658. "application/octet-stream");
  3659. ASSERT_TRUE(res);
  3660. ASSERT_EQ(StatusCode::OK_200, res->status);
  3661. ASSERT_EQ(4U, res->body.size());
  3662. }
  3663. TEST_F(ServerTest, BinaryString) {
  3664. auto binary = std::string("\x00\x01\x02\x03", 4);
  3665. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3666. ASSERT_TRUE(res);
  3667. ASSERT_EQ(StatusCode::OK_200, res->status);
  3668. ASSERT_EQ(4U, res->body.size());
  3669. res = cli_.Put("/binary", binary, "application/octet-stream");
  3670. ASSERT_TRUE(res);
  3671. ASSERT_EQ(StatusCode::OK_200, res->status);
  3672. ASSERT_EQ(4U, res->body.size());
  3673. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(StatusCode::OK_200, res->status);
  3676. ASSERT_EQ(4U, res->body.size());
  3677. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3678. ASSERT_TRUE(res);
  3679. ASSERT_EQ(StatusCode::OK_200, res->status);
  3680. ASSERT_EQ(4U, res->body.size());
  3681. }
  3682. TEST_F(ServerTest, EmptyRequest) {
  3683. auto res = cli_.Get("");
  3684. ASSERT_TRUE(!res);
  3685. EXPECT_EQ(Error::Connection, res.error());
  3686. }
  3687. TEST_F(ServerTest, LongRequest) {
  3688. std::string request;
  3689. for (size_t i = 0; i < 545; i++) {
  3690. request += "/TooLongRequest";
  3691. }
  3692. request += "OK";
  3693. auto res = cli_.Get(request.c_str());
  3694. ASSERT_TRUE(res);
  3695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3696. }
  3697. TEST_F(ServerTest, TooLongRequest) {
  3698. std::string request;
  3699. for (size_t i = 0; i < 546; i++) {
  3700. request += "/TooLongRequest";
  3701. }
  3702. request += "_NG";
  3703. auto start = std::chrono::high_resolution_clock::now();
  3704. cli_.set_keep_alive(true);
  3705. auto res = cli_.Get(request.c_str());
  3706. auto end = std::chrono::high_resolution_clock::now();
  3707. auto elapsed =
  3708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3709. .count();
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3712. EXPECT_LE(elapsed, 100);
  3713. EXPECT_EQ("close", res->get_header_value("Connection"));
  3714. EXPECT_FALSE(cli_.is_socket_open());
  3715. }
  3716. TEST_F(ServerTest, AlmostTooLongRequest) {
  3717. // test for #2046 - URI length check shouldn't include other content on req
  3718. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3719. // leading /, space, HTTP/1.1)
  3720. std::string request =
  3721. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3722. auto res = cli_.Get(request.c_str());
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3725. }
  3726. TEST_F(ServerTest, LongHeader) {
  3727. Request req;
  3728. req.method = "GET";
  3729. req.path = "/hi";
  3730. std::string host_and_port;
  3731. host_and_port += HOST;
  3732. host_and_port += ":";
  3733. host_and_port += std::to_string(PORT);
  3734. req.headers.emplace("Host", host_and_port.c_str());
  3735. req.headers.emplace("Accept", "*/*");
  3736. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3737. req.headers.emplace(
  3738. "Header-Name",
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@");
  3768. auto res = std::make_shared<Response>();
  3769. auto error = Error::Success;
  3770. auto ret = cli_.send(req, *res, error);
  3771. ASSERT_TRUE(ret);
  3772. EXPECT_EQ(StatusCode::OK_200, res->status);
  3773. }
  3774. TEST_F(ServerTest, LongQueryValue) {
  3775. auto start = std::chrono::high_resolution_clock::now();
  3776. cli_.set_keep_alive(true);
  3777. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3778. auto end = std::chrono::high_resolution_clock::now();
  3779. auto elapsed =
  3780. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3781. .count();
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3784. EXPECT_LE(elapsed, 100);
  3785. EXPECT_EQ("close", res->get_header_value("Connection"));
  3786. EXPECT_FALSE(cli_.is_socket_open());
  3787. }
  3788. TEST_F(ServerTest, TooLongQueryValue) {
  3789. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3790. ASSERT_FALSE(res);
  3791. EXPECT_EQ(Error::Read, res.error());
  3792. }
  3793. TEST_F(ServerTest, TooLongHeader) {
  3794. Request req;
  3795. req.method = "GET";
  3796. req.path = "/hi";
  3797. std::string host_and_port;
  3798. host_and_port += HOST;
  3799. host_and_port += ":";
  3800. host_and_port += std::to_string(PORT);
  3801. req.headers.emplace("Host", host_and_port.c_str());
  3802. req.headers.emplace("Accept", "*/*");
  3803. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3804. req.headers.emplace(
  3805. "Header-Name",
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3834. "@@@@@@@@@@@@@@@@@");
  3835. auto res = std::make_shared<Response>();
  3836. auto error = Error::Success;
  3837. auto ret = cli_.send(req, *res, error);
  3838. ASSERT_TRUE(ret);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. }
  3841. TEST_F(ServerTest, HeaderCountAtLimit) {
  3842. // Test with headers just under the 100 limit
  3843. httplib::Headers headers;
  3844. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3845. // This should keep us just under the 100 header limit
  3846. for (int i = 0; i < 95; i++) {
  3847. std::string name = "X-Test-Header-" + std::to_string(i);
  3848. std::string value = "value" + std::to_string(i);
  3849. headers.emplace(name, value);
  3850. }
  3851. // This should work fine as we're under the limit
  3852. auto res = cli_.Get("/hi", headers);
  3853. EXPECT_TRUE(res);
  3854. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3855. }
  3856. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3857. // Test with many headers to exceed the 100 limit
  3858. httplib::Headers headers;
  3859. // Add 150 headers to definitely exceed the 100 limit
  3860. for (int i = 0; i < 150; i++) {
  3861. std::string name = "X-Test-Header-" + std::to_string(i);
  3862. std::string value = "value" + std::to_string(i);
  3863. headers.emplace(name, value);
  3864. }
  3865. // This should fail due to exceeding header count limit
  3866. cli_.set_keep_alive(true);
  3867. auto res = cli_.Get("/hi", headers);
  3868. // The request should either fail or return 400 Bad Request
  3869. if (res) {
  3870. // If we get a response, it should be 400 Bad Request
  3871. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3872. } else {
  3873. // Or the request should fail entirely
  3874. EXPECT_FALSE(res);
  3875. }
  3876. EXPECT_EQ("close", res->get_header_value("Connection"));
  3877. EXPECT_FALSE(cli_.is_socket_open());
  3878. }
  3879. TEST_F(ServerTest, PercentEncoding) {
  3880. auto res = cli_.Get("/e%6edwith%");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::OK_200, res->status);
  3883. }
  3884. TEST_F(ServerTest, PercentEncodingUnicode) {
  3885. auto res = cli_.Get("/e%u006edwith%");
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::OK_200, res->status);
  3888. }
  3889. TEST_F(ServerTest, InvalidPercentEncoding) {
  3890. auto res = cli_.Get("/%endwith%");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3893. }
  3894. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3895. auto res = cli_.Get("/%uendwith%");
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3898. }
  3899. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3900. auto res = cli_.Get("/hello?aaa=bbb%");
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3903. }
  3904. TEST_F(ServerTest, PlusSignEncoding) {
  3905. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3906. ASSERT_TRUE(res);
  3907. EXPECT_EQ(StatusCode::OK_200, res->status);
  3908. EXPECT_EQ("a +b", res->body);
  3909. }
  3910. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3911. // This test simulates a potential DoS attack using many headers
  3912. // to verify our security fix prevents memory exhaustion
  3913. httplib::Headers attack_headers;
  3914. // Attempt to add many headers like an attacker would (200 headers to far
  3915. // exceed limit)
  3916. for (int i = 0; i < 200; i++) {
  3917. std::string name = "X-Attack-Header-" + std::to_string(i);
  3918. std::string value = "attack_payload_" + std::to_string(i);
  3919. attack_headers.emplace(name, value);
  3920. }
  3921. // Try to POST with excessive headers
  3922. cli_.set_keep_alive(true);
  3923. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3924. // Should either fail or return 400 Bad Request due to security limit
  3925. if (res) {
  3926. // If we get a response, it should be 400 Bad Request
  3927. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3928. } else {
  3929. // Request failed, which is the expected behavior for DoS protection
  3930. EXPECT_FALSE(res);
  3931. }
  3932. EXPECT_EQ("close", res->get_header_value("Connection"));
  3933. EXPECT_FALSE(cli_.is_socket_open());
  3934. }
  3935. TEST_F(ServerTest, MultipartFormData) {
  3936. UploadFormDataItems items = {
  3937. {"text1", "text default", "", ""},
  3938. {"text2", "aωb", "", ""},
  3939. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3940. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3941. {"file3", "", "", "application/octet-stream"},
  3942. {"file4", "", "", " application/json tmp-string "}};
  3943. auto res = cli_.Post("/multipart", items);
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. }
  3947. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3948. UploadFormDataItems items = {
  3949. {"text", "default text", "", ""},
  3950. {"multi_text1", "aaaaa", "", ""},
  3951. {"multi_text1", "bbbbb", "", ""},
  3952. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3953. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3954. "application/json"},
  3955. };
  3956. auto res = cli_.Post("/multipart/multi_file_values", items);
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::OK_200, res->status);
  3959. }
  3960. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3961. auto res = cli_.Get("/hi");
  3962. ASSERT_TRUE(res);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3965. EXPECT_EQ("Hello World!", res->body);
  3966. }
  3967. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3968. Request req;
  3969. req.method = "POST";
  3970. req.path = "/chunked";
  3971. std::string host_and_port;
  3972. host_and_port += HOST;
  3973. host_and_port += ":";
  3974. host_and_port += std::to_string(PORT);
  3975. req.headers.emplace("Host", host_and_port.c_str());
  3976. req.headers.emplace("Accept", "*/*");
  3977. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3978. req.headers.emplace("Content-Type", "text/plain");
  3979. req.headers.emplace("Content-Length", "0");
  3980. req.headers.emplace(
  3981. "Transfer-Encoding",
  3982. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3983. // Client does not chunk, so make a chunked body manually.
  3984. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3985. auto res = std::make_shared<Response>();
  3986. auto error = Error::Success;
  3987. auto ret = cli_.send(req, *res, error);
  3988. ASSERT_TRUE(ret);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. }
  3991. TEST_F(ServerTest, GetStreamed2) {
  3992. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3995. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3996. EXPECT_EQ(true, res->has_header("Content-Range"));
  3997. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3998. EXPECT_EQ(std::string("ab"), res->body);
  3999. }
  4000. TEST_F(ServerTest, GetStreamed) {
  4001. auto res = cli_.Get("/streamed");
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ(StatusCode::OK_200, res->status);
  4004. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4005. EXPECT_EQ(std::string("aaabbb"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamedWithRange1) {
  4008. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4011. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(true, res->has_header("Content-Range"));
  4013. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4014. EXPECT_EQ(std::string("def"), res->body);
  4015. }
  4016. TEST_F(ServerTest, GetStreamedWithRange2) {
  4017. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4020. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4021. EXPECT_EQ(true, res->has_header("Content-Range"));
  4022. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4023. EXPECT_EQ(std::string("bcdefg"), res->body);
  4024. }
  4025. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4026. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4027. ASSERT_TRUE(res);
  4028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4029. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4030. EXPECT_EQ(true, res->has_header("Content-Range"));
  4031. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4032. EXPECT_EQ(std::string("efg"), res->body);
  4033. }
  4034. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4035. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4038. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ(false, res->has_header("Content-Range"));
  4040. EXPECT_EQ(0U, res->body.size());
  4041. }
  4042. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4043. auto res = cli_.Get("/streamed-with-range",
  4044. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4045. "92233720368547758079223372036854775807"}});
  4046. ASSERT_TRUE(res);
  4047. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4048. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4049. EXPECT_EQ(false, res->has_header("Content-Range"));
  4050. EXPECT_EQ(0U, res->body.size());
  4051. }
  4052. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4053. auto res = cli_.Get(
  4054. "/with-range",
  4055. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4056. {"Accept-Encoding", ""}});
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4059. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4060. EXPECT_EQ(true, res->has_header("Content-Range"));
  4061. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4062. EXPECT_EQ(std::string("abcdefg"), res->body);
  4063. }
  4064. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4065. auto res = cli_.Get("/with-range", {
  4066. {"Range", "bytes=0-"},
  4067. {"Accept-Encoding", ""},
  4068. });
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4071. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4072. EXPECT_EQ(true, res->has_header("Content-Range"));
  4073. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4074. EXPECT_EQ(std::string("abcdefg"), res->body);
  4075. }
  4076. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4077. auto res =
  4078. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4081. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4082. EXPECT_EQ(false, res->has_header("Content-Range"));
  4083. EXPECT_EQ(267U, res->body.size());
  4084. // Check that both range contents are present
  4085. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4086. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4087. // Check that Content-Range headers are present for both ranges
  4088. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4089. std::string::npos);
  4090. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4091. std::string::npos);
  4092. }
  4093. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4094. Ranges ranges;
  4095. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4096. ranges.emplace_back(0, -1);
  4097. }
  4098. auto res =
  4099. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4102. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(false, res->has_header("Content-Range"));
  4104. EXPECT_EQ(0U, res->body.size());
  4105. }
  4106. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4107. auto res =
  4108. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4109. ASSERT_TRUE(res);
  4110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4111. EXPECT_EQ(5U, res->body.size());
  4112. // Check that overlapping ranges are coalesced into a single range
  4113. EXPECT_EQ("bcdef", res->body);
  4114. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4115. // Should be single range, not multipart
  4116. EXPECT_TRUE(res->has_header("Content-Range"));
  4117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4118. }
  4119. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4120. auto res =
  4121. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4124. EXPECT_EQ(268U, res->body.size());
  4125. // Check that both range contents are present
  4126. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4127. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4128. // Check that Content-Range headers are present for both ranges
  4129. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4130. std::string::npos);
  4131. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4132. std::string::npos);
  4133. }
  4134. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4135. auto res =
  4136. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4139. EXPECT_EQ(269U, res->body.size());
  4140. // Check that both duplicate range contents are present
  4141. size_t first_abc = res->body.find("abc\r\n");
  4142. EXPECT_TRUE(first_abc != std::string::npos);
  4143. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4144. EXPECT_TRUE(second_abc != std::string::npos);
  4145. // Check that Content-Range headers are present for both ranges
  4146. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4147. EXPECT_TRUE(first_range != std::string::npos);
  4148. size_t second_range =
  4149. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4150. EXPECT_TRUE(second_range != std::string::npos);
  4151. }
  4152. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4153. auto res = cli_.Get("/streamed-with-range?error",
  4154. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4157. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4158. EXPECT_EQ(false, res->has_header("Content-Range"));
  4159. EXPECT_EQ(0U, res->body.size());
  4160. }
  4161. TEST_F(ServerTest, GetStreamedEndless) {
  4162. uint64_t offset = 0;
  4163. auto res = cli_.Get("/streamed-cancel",
  4164. [&](const char * /*data*/, uint64_t data_length) {
  4165. if (offset < 100) {
  4166. offset += data_length;
  4167. return true;
  4168. }
  4169. return false;
  4170. });
  4171. ASSERT_TRUE(!res);
  4172. EXPECT_EQ(Error::Canceled, res.error());
  4173. }
  4174. TEST_F(ServerTest, ClientStop) {
  4175. std::atomic_size_t count{4};
  4176. std::vector<std::thread> threads;
  4177. for (auto i = count.load(); i != 0; --i) {
  4178. threads.emplace_back([&]() {
  4179. auto res = cli_.Get("/streamed-cancel",
  4180. [&](const char *, uint64_t) { return true; });
  4181. --count;
  4182. ASSERT_TRUE(!res);
  4183. EXPECT_TRUE(res.error() == Error::Canceled ||
  4184. res.error() == Error::Read || res.error() == Error::Write);
  4185. });
  4186. }
  4187. std::this_thread::sleep_for(std::chrono::seconds(2));
  4188. while (count != 0) {
  4189. cli_.stop();
  4190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4191. }
  4192. for (auto &t : threads) {
  4193. t.join();
  4194. }
  4195. }
  4196. TEST_F(ServerTest, GetWithRange1) {
  4197. auto res = cli_.Get("/with-range", {
  4198. make_range_header({{3, 5}}),
  4199. {"Accept-Encoding", ""},
  4200. });
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4203. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ(true, res->has_header("Content-Range"));
  4205. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4206. EXPECT_EQ(std::string("def"), res->body);
  4207. }
  4208. TEST_F(ServerTest, GetWithRange2) {
  4209. auto res = cli_.Get("/with-range", {
  4210. make_range_header({{1, -1}}),
  4211. {"Accept-Encoding", ""},
  4212. });
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4215. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4216. EXPECT_EQ(true, res->has_header("Content-Range"));
  4217. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4218. EXPECT_EQ(std::string("bcdefg"), res->body);
  4219. }
  4220. TEST_F(ServerTest, GetWithRange3) {
  4221. auto res = cli_.Get("/with-range", {
  4222. make_range_header({{0, 0}}),
  4223. {"Accept-Encoding", ""},
  4224. });
  4225. ASSERT_TRUE(res);
  4226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4227. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4228. EXPECT_EQ(true, res->has_header("Content-Range"));
  4229. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4230. EXPECT_EQ(std::string("a"), res->body);
  4231. }
  4232. TEST_F(ServerTest, GetWithRange4) {
  4233. auto res = cli_.Get("/with-range", {
  4234. make_range_header({{-1, 2}}),
  4235. {"Accept-Encoding", ""},
  4236. });
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4239. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4240. EXPECT_EQ(true, res->has_header("Content-Range"));
  4241. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4242. EXPECT_EQ(std::string("fg"), res->body);
  4243. }
  4244. TEST_F(ServerTest, GetWithRange5) {
  4245. auto res = cli_.Get("/with-range", {
  4246. make_range_header({{0, 5}}),
  4247. {"Accept-Encoding", ""},
  4248. });
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4251. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4252. EXPECT_EQ(true, res->has_header("Content-Range"));
  4253. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4254. EXPECT_EQ(std::string("abcdef"), res->body);
  4255. }
  4256. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4257. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4260. }
  4261. TEST_F(ServerTest, GetWithRangeMultipart) {
  4262. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4265. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4266. EXPECT_EQ(false, res->has_header("Content-Range"));
  4267. EXPECT_EQ(267U, res->body.size());
  4268. }
  4269. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4270. auto res =
  4271. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4274. }
  4275. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4276. auto res = cli_.Get("/with-range-customized-response",
  4277. {{make_range_header({{1, 2}})}});
  4278. ASSERT_TRUE(res);
  4279. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4280. EXPECT_EQ(true, res->has_header("Content-Length"));
  4281. EXPECT_EQ(false, res->has_header("Content-Range"));
  4282. EXPECT_EQ(JSON_DATA, res->body);
  4283. }
  4284. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4285. auto res = cli_.Get("/with-range-customized-response",
  4286. {{make_range_header({{1, 2}, {4, 5}})}});
  4287. ASSERT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4289. EXPECT_EQ(true, res->has_header("Content-Length"));
  4290. EXPECT_EQ(false, res->has_header("Content-Range"));
  4291. EXPECT_EQ(JSON_DATA, res->body);
  4292. }
  4293. TEST_F(ServerTest, Issue1772) {
  4294. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4295. ASSERT_TRUE(res);
  4296. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4297. }
  4298. TEST_F(ServerTest, Issue609) {
  4299. auto res = cli_.Delete("/issue609");
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ(std::string("ok"), res->body);
  4303. }
  4304. TEST_F(ServerTest, GetStreamedChunked) {
  4305. auto res = cli_.Get("/streamed-chunked");
  4306. ASSERT_TRUE(res);
  4307. EXPECT_EQ(StatusCode::OK_200, res->status);
  4308. EXPECT_EQ(std::string("123456789"), res->body);
  4309. }
  4310. TEST_F(ServerTest, GetStreamedChunked2) {
  4311. auto res = cli_.Get("/streamed-chunked2");
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ(std::string("123456789"), res->body);
  4315. }
  4316. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4317. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ(std::string("123456789"), res->body);
  4321. EXPECT_TRUE(res->has_header("Trailer"));
  4322. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4323. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4324. // Trailers are now stored separately from headers (security fix)
  4325. EXPECT_EQ(2U, res->trailers.size());
  4326. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4327. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4328. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4329. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4330. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4331. // Verify trailers are NOT in headers (security verification)
  4332. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4333. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4334. }
  4335. TEST_F(ServerTest, LargeChunkedPost) {
  4336. Request req;
  4337. req.method = "POST";
  4338. req.path = "/large-chunked";
  4339. std::string host_and_port;
  4340. host_and_port += HOST;
  4341. host_and_port += ":";
  4342. host_and_port += std::to_string(PORT);
  4343. req.headers.emplace("Host", host_and_port.c_str());
  4344. req.headers.emplace("Accept", "*/*");
  4345. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4346. req.headers.emplace("Content-Type", "text/plain");
  4347. req.headers.emplace("Content-Length", "0");
  4348. req.headers.emplace("Transfer-Encoding", "chunked");
  4349. std::string long_string(30 * 1024u, 'a');
  4350. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4351. // Attempt to make a large enough post to exceed OS buffers, to test that
  4352. // the server handles short reads if the full chunk data isn't available.
  4353. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4354. auto res = std::make_shared<Response>();
  4355. auto error = Error::Success;
  4356. auto ret = cli_.send(req, *res, error);
  4357. ASSERT_TRUE(ret);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. }
  4360. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4361. auto res = cli_.Get("/remote_addr");
  4362. ASSERT_TRUE(res);
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4365. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4366. }
  4367. TEST_F(ServerTest, GetMethodLocalAddr) {
  4368. auto res = cli_.Get("/local_addr");
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4372. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4373. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4374. }
  4375. TEST_F(ServerTest, HTTPResponseSplitting) {
  4376. auto res = cli_.Get("/http_response_splitting");
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::OK_200, res->status);
  4379. }
  4380. TEST_F(ServerTest, SlowRequest) {
  4381. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4382. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4383. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4384. }
  4385. #if 0
  4386. TEST_F(ServerTest, SlowPost) {
  4387. char buffer[64 * 1024];
  4388. memset(buffer, 0x42, sizeof(buffer));
  4389. auto res = cli_.Post(
  4390. "/slowpost", 64 * 1024 * 1024,
  4391. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4392. auto ret = sink.write(buffer, sizeof(buffer));
  4393. EXPECT_TRUE(ret);
  4394. return true;
  4395. },
  4396. "text/plain");
  4397. ASSERT_TRUE(res);
  4398. EXPECT_EQ(StatusCode::OK_200, res->status);
  4399. }
  4400. TEST_F(ServerTest, SlowPostFail) {
  4401. char buffer[64 * 1024];
  4402. memset(buffer, 0x42, sizeof(buffer));
  4403. cli_.set_write_timeout(std::chrono::seconds(0));
  4404. auto res = cli_.Post(
  4405. "/slowpost", 64 * 1024 * 1024,
  4406. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4407. sink.write(buffer, sizeof(buffer));
  4408. return true;
  4409. },
  4410. "text/plain");
  4411. ASSERT_TRUE(!res);
  4412. EXPECT_EQ(Error::Write, res.error());
  4413. }
  4414. #endif
  4415. TEST_F(ServerTest, Put) {
  4416. auto res = cli_.Put("/put", "PUT", "text/plain");
  4417. ASSERT_TRUE(res);
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. EXPECT_EQ("PUT", res->body);
  4420. }
  4421. TEST_F(ServerTest, PutWithContentProvider) {
  4422. auto res = cli_.Put(
  4423. "/put", 3,
  4424. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4425. sink.os << "PUT";
  4426. return true;
  4427. },
  4428. "text/plain");
  4429. ASSERT_TRUE(res);
  4430. EXPECT_EQ(StatusCode::OK_200, res->status);
  4431. EXPECT_EQ("PUT", res->body);
  4432. }
  4433. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4434. auto res = cli_.Post(
  4435. "/post", 42,
  4436. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4437. return false;
  4438. },
  4439. "text/plain");
  4440. ASSERT_TRUE(!res);
  4441. EXPECT_EQ(Error::Canceled, res.error());
  4442. }
  4443. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4444. auto res = cli_.Put(
  4445. "/put",
  4446. [](size_t /*offset*/, DataSink &sink) {
  4447. sink.os << "PUT";
  4448. sink.done();
  4449. return true;
  4450. },
  4451. "text/plain");
  4452. ASSERT_TRUE(res);
  4453. EXPECT_EQ(StatusCode::OK_200, res->status);
  4454. EXPECT_EQ("PUT", res->body);
  4455. }
  4456. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4457. auto res = cli_.Post(
  4458. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4459. "text/plain");
  4460. ASSERT_TRUE(!res);
  4461. EXPECT_EQ(Error::Canceled, res.error());
  4462. }
  4463. TEST_F(ServerTest, PostLoopBack) {
  4464. std::string body;
  4465. auto res = cli_.Post(
  4466. "/post-loopback", 9,
  4467. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4468. EXPECT_EQ(9u, length);
  4469. sink.write("123", 3);
  4470. sink.write("456", 3);
  4471. sink.write("789", 3);
  4472. return true;
  4473. },
  4474. "text/plain",
  4475. [&body](const char *data, size_t data_length) {
  4476. body.append(data, data_length);
  4477. return true;
  4478. });
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("123456789", body);
  4482. }
  4483. TEST_F(ServerTest, PutLoopBack) {
  4484. std::string body;
  4485. auto res = cli_.Put(
  4486. "/put-loopback", 9,
  4487. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4488. EXPECT_EQ(9u, length);
  4489. sink.write("123", 3);
  4490. sink.write("456", 3);
  4491. sink.write("789", 3);
  4492. return true;
  4493. },
  4494. "text/plain",
  4495. [&body](const char *data, size_t data_length) {
  4496. body.append(data, data_length);
  4497. return true;
  4498. });
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::OK_200, res->status);
  4501. EXPECT_EQ("123456789", body);
  4502. }
  4503. TEST_F(ServerTest, PatchLoopBack) {
  4504. std::string body;
  4505. auto res = cli_.Patch(
  4506. "/patch-loopback", 9,
  4507. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4508. EXPECT_EQ(9u, length);
  4509. sink.write("123", 3);
  4510. sink.write("456", 3);
  4511. sink.write("789", 3);
  4512. return true;
  4513. },
  4514. "text/plain",
  4515. [&body](const char *data, size_t data_length) {
  4516. body.append(data, data_length);
  4517. return true;
  4518. });
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::OK_200, res->status);
  4521. EXPECT_EQ("123456789", body);
  4522. }
  4523. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4524. std::string body;
  4525. auto res = cli_.Post(
  4526. "/post-loopback",
  4527. [](size_t /*offset*/, DataSink &sink) {
  4528. sink.write("123", 3);
  4529. sink.write("456", 3);
  4530. sink.write("789", 3);
  4531. sink.done();
  4532. return true;
  4533. },
  4534. "text/plain",
  4535. [&body](const char *data, size_t data_length) {
  4536. body.append(data, data_length);
  4537. return true;
  4538. });
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ("123456789", body);
  4542. }
  4543. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4544. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4545. cli_.set_compress(true);
  4546. auto res = cli_.Put(
  4547. "/put", 3,
  4548. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4549. sink.os << "PUT";
  4550. return true;
  4551. },
  4552. "text/plain");
  4553. ASSERT_TRUE(res);
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("PUT", res->body);
  4556. }
  4557. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4558. cli_.set_compress(true);
  4559. auto res = cli_.Post(
  4560. "/post", 42,
  4561. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4562. return false;
  4563. },
  4564. "text/plain");
  4565. ASSERT_TRUE(!res);
  4566. EXPECT_EQ(Error::Canceled, res.error());
  4567. }
  4568. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4569. cli_.set_compress(true);
  4570. auto res = cli_.Put(
  4571. "/put",
  4572. [](size_t /*offset*/, DataSink &sink) {
  4573. sink.os << "PUT";
  4574. sink.done();
  4575. return true;
  4576. },
  4577. "text/plain");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. EXPECT_EQ("PUT", res->body);
  4581. }
  4582. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4583. cli_.set_compress(true);
  4584. auto res = cli_.Post(
  4585. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4586. "text/plain");
  4587. ASSERT_TRUE(!res);
  4588. EXPECT_EQ(Error::Canceled, res.error());
  4589. }
  4590. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4591. cli_.set_compress(true);
  4592. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ(LARGE_DATA, res->body);
  4596. }
  4597. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4599. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4600. Client cli(s.c_str());
  4601. cli.enable_server_certificate_verification(false);
  4602. #else
  4603. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4604. Client cli(s.c_str());
  4605. #endif
  4606. cli.set_compress(true);
  4607. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ(LARGE_DATA, res->body);
  4611. // The compressed size should be less than a 10th of the original. May vary
  4612. // depending on the zlib library.
  4613. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4614. static_cast<uint64_t>(10 * 1024 * 1024));
  4615. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4616. }
  4617. TEST_F(ServerTest, PutContentWithDeflate) {
  4618. cli_.set_compress(false);
  4619. Headers headers;
  4620. headers.emplace("Content-Encoding", "deflate");
  4621. // PUT in deflate format:
  4622. auto res = cli_.Put("/put", headers,
  4623. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::OK_200, res->status);
  4626. EXPECT_EQ("PUT", res->body);
  4627. }
  4628. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4629. Headers headers;
  4630. headers.emplace("Accept-Encoding", "gzip, deflate");
  4631. auto res = cli_.Get("/streamed-chunked", headers);
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ(std::string("123456789"), res->body);
  4635. }
  4636. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4637. Headers headers;
  4638. headers.emplace("Accept-Encoding", "gzip, deflate");
  4639. auto res = cli_.Get("/streamed-chunked2", headers);
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::OK_200, res->status);
  4642. EXPECT_EQ(std::string("123456789"), res->body);
  4643. }
  4644. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4645. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::OK_200, res->status);
  4648. }
  4649. TEST(GzipDecompressor, ChunkedDecompression) {
  4650. std::string data;
  4651. for (size_t i = 0; i < 32 * 1024; ++i) {
  4652. data.push_back(static_cast<char>('a' + i % 26));
  4653. }
  4654. std::string compressed_data;
  4655. {
  4656. httplib::detail::gzip_compressor compressor;
  4657. bool result = compressor.compress(
  4658. data.data(), data.size(),
  4659. /*last=*/true,
  4660. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4661. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4662. compressed_data_size);
  4663. return true;
  4664. });
  4665. ASSERT_TRUE(result);
  4666. }
  4667. std::string decompressed_data;
  4668. {
  4669. httplib::detail::gzip_decompressor decompressor;
  4670. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4671. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4672. size_t chunk_size = 130;
  4673. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4674. chunk_begin += chunk_size) {
  4675. size_t current_chunk_size =
  4676. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4677. bool result = decompressor.decompress(
  4678. compressed_data.data() + chunk_begin, current_chunk_size,
  4679. [&](const char *decompressed_data_chunk,
  4680. size_t decompressed_data_chunk_size) {
  4681. decompressed_data.insert(decompressed_data.size(),
  4682. decompressed_data_chunk,
  4683. decompressed_data_chunk_size);
  4684. return true;
  4685. });
  4686. ASSERT_TRUE(result);
  4687. }
  4688. }
  4689. ASSERT_EQ(data, decompressed_data);
  4690. }
  4691. TEST(GzipDecompressor, DeflateDecompression) {
  4692. std::string original_text = "Raw deflate without gzip";
  4693. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4694. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4695. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4696. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4697. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4698. std::string decompressed_data;
  4699. {
  4700. httplib::detail::gzip_decompressor decompressor;
  4701. bool result = decompressor.decompress(
  4702. compressed_data.data(), compressed_data.size(),
  4703. [&](const char *decompressed_data_chunk,
  4704. size_t decompressed_data_chunk_size) {
  4705. decompressed_data.insert(decompressed_data.size(),
  4706. decompressed_data_chunk,
  4707. decompressed_data_chunk_size);
  4708. return true;
  4709. });
  4710. ASSERT_TRUE(result);
  4711. }
  4712. ASSERT_EQ(original_text, decompressed_data);
  4713. }
  4714. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4715. std::string original_text = "Raw deflate without gzip";
  4716. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4717. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4718. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4719. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4720. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4721. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4722. std::string decompressed_data;
  4723. {
  4724. httplib::detail::gzip_decompressor decompressor;
  4725. bool result = decompressor.decompress(
  4726. compressed_data.data(), compressed_data.size(),
  4727. [&](const char *decompressed_data_chunk,
  4728. size_t decompressed_data_chunk_size) {
  4729. decompressed_data.insert(decompressed_data.size(),
  4730. decompressed_data_chunk,
  4731. decompressed_data_chunk_size);
  4732. return true;
  4733. });
  4734. ASSERT_TRUE(result);
  4735. }
  4736. ASSERT_EQ(original_text, decompressed_data);
  4737. }
  4738. #ifdef _WIN32
  4739. TEST(GzipDecompressor, LargeRandomData) {
  4740. // prepare large random data that is difficult to be compressed and is
  4741. // expected to have large size even when compressed
  4742. std::random_device seed_gen;
  4743. std::mt19937 random(seed_gen());
  4744. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4745. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4746. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4747. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4748. // compress data over 4GiB
  4749. std::string compressed_data;
  4750. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4751. httplib::detail::gzip_compressor compressor;
  4752. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4753. data.size() * sizeof(std::uint32_t), true,
  4754. [&](const char *data, size_t size) {
  4755. compressed_data.insert(
  4756. compressed_data.size(), data, size);
  4757. return true;
  4758. });
  4759. ASSERT_TRUE(result);
  4760. // FIXME: compressed data size is expected to be greater than 4GiB,
  4761. // but there is no guarantee
  4762. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4763. // decompress data over 4GiB
  4764. std::string decompressed_data;
  4765. decompressed_data.reserve(data_size);
  4766. httplib::detail::gzip_decompressor decompressor;
  4767. result = decompressor.decompress(
  4768. compressed_data.data(), compressed_data.size(),
  4769. [&](const char *data, size_t size) {
  4770. decompressed_data.insert(decompressed_data.size(), data, size);
  4771. return true;
  4772. });
  4773. ASSERT_TRUE(result);
  4774. // compare
  4775. ASSERT_EQ(data_size, decompressed_data.size());
  4776. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4777. 0);
  4778. }
  4779. #endif
  4780. #endif
  4781. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4782. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4783. Headers headers;
  4784. headers.emplace("Accept-Encoding", "br");
  4785. auto res = cli_.Get("/streamed-chunked", headers);
  4786. ASSERT_TRUE(res);
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. EXPECT_EQ(std::string("123456789"), res->body);
  4789. }
  4790. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4791. Headers headers;
  4792. headers.emplace("Accept-Encoding", "br");
  4793. auto res = cli_.Get("/streamed-chunked2", headers);
  4794. ASSERT_TRUE(res);
  4795. EXPECT_EQ(StatusCode::OK_200, res->status);
  4796. EXPECT_EQ(std::string("123456789"), res->body);
  4797. }
  4798. #endif
  4799. TEST_F(ServerTest, Patch) {
  4800. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("PATCH", res->body);
  4804. }
  4805. TEST_F(ServerTest, Delete) {
  4806. auto res = cli_.Delete("/delete");
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ("DELETE", res->body);
  4810. }
  4811. TEST_F(ServerTest, DeleteContentReceiver) {
  4812. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("content", res->body);
  4816. }
  4817. TEST_F(ServerTest, Options) {
  4818. auto res = cli_.Options("*");
  4819. ASSERT_TRUE(res);
  4820. EXPECT_EQ(StatusCode::OK_200, res->status);
  4821. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4822. EXPECT_TRUE(res->body.empty());
  4823. }
  4824. TEST_F(ServerTest, URL) {
  4825. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. }
  4829. TEST_F(ServerTest, ArrayParam) {
  4830. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4831. ASSERT_TRUE(res);
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. }
  4834. TEST_F(ServerTest, NoMultipleHeaders) {
  4835. Headers headers = {{"Content-Length", "5"}};
  4836. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4837. "text/plain");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, PostContentReceiver) {
  4842. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4843. ASSERT_TRUE(res);
  4844. ASSERT_EQ(StatusCode::OK_200, res->status);
  4845. ASSERT_EQ("content", res->body);
  4846. }
  4847. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4848. UploadFormDataItems items = {
  4849. {"text1", "text default", "", ""},
  4850. {"text2", "aωb", "", ""},
  4851. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4852. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4853. {"file3", "", "", "application/octet-stream"},
  4854. };
  4855. auto res = cli_.Post("/content_receiver", items);
  4856. ASSERT_TRUE(res);
  4857. EXPECT_EQ(StatusCode::OK_200, res->status);
  4858. }
  4859. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4860. UploadFormDataItems items = {
  4861. {"text1", "text default", "", ""},
  4862. {"text2", "aωb", "", ""},
  4863. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4864. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4865. {"file3", "", "", "application/octet-stream"},
  4866. };
  4867. auto boundary = std::string("+++++");
  4868. std::string body;
  4869. for (const auto &item : items) {
  4870. body += "--" + boundary + "\r\n";
  4871. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4872. if (!item.filename.empty()) {
  4873. body += "; filename=\"" + item.filename + "\"";
  4874. }
  4875. body += "\r\n";
  4876. if (!item.content_type.empty()) {
  4877. body += "Content-Type: " + item.content_type + "\r\n";
  4878. }
  4879. body += "\r\n";
  4880. body += item.content + "\r\n";
  4881. }
  4882. body += "--" + boundary + "--\r\n";
  4883. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4884. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST_F(ServerTest, PostContentReceiverGzip) {
  4889. cli_.set_compress(true);
  4890. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4891. ASSERT_TRUE(res);
  4892. ASSERT_EQ(StatusCode::OK_200, res->status);
  4893. ASSERT_EQ("content", res->body);
  4894. }
  4895. TEST_F(ServerTest, PutContentReceiver) {
  4896. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4897. ASSERT_TRUE(res);
  4898. ASSERT_EQ(StatusCode::OK_200, res->status);
  4899. ASSERT_EQ("content", res->body);
  4900. }
  4901. TEST_F(ServerTest, PatchContentReceiver) {
  4902. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4903. ASSERT_TRUE(res);
  4904. ASSERT_EQ(StatusCode::OK_200, res->status);
  4905. ASSERT_EQ("content", res->body);
  4906. }
  4907. template <typename ClientType>
  4908. void TestWithHeadersAndContentReceiver(
  4909. ClientType &cli,
  4910. std::function<Result(ClientType &, const std::string &, const Headers &,
  4911. const std::string &, const std::string &,
  4912. ContentReceiver, DownloadProgress)>
  4913. request_func) {
  4914. Headers headers;
  4915. headers.emplace("X-Custom-Header", "test-value");
  4916. std::string received_body;
  4917. auto res = request_func(
  4918. cli, "/content_receiver", headers, "content", "application/json",
  4919. [&](const char *data, size_t data_length) {
  4920. received_body.append(data, data_length);
  4921. return true;
  4922. },
  4923. nullptr);
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::OK_200, res->status);
  4926. EXPECT_EQ("content", received_body);
  4927. }
  4928. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4929. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4930. using ClientT = SSLClient;
  4931. #else
  4932. using ClientT = Client;
  4933. #endif
  4934. TestWithHeadersAndContentReceiver<ClientT>(
  4935. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4936. const std::string &body, const std::string &content_type,
  4937. ContentReceiver receiver, DownloadProgress progress) {
  4938. return cli.Post(path, headers, body, content_type, receiver, progress);
  4939. });
  4940. }
  4941. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4943. using ClientT = SSLClient;
  4944. #else
  4945. using ClientT = Client;
  4946. #endif
  4947. TestWithHeadersAndContentReceiver<ClientT>(
  4948. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4949. const std::string &body, const std::string &content_type,
  4950. ContentReceiver receiver, DownloadProgress progress) {
  4951. return cli.Put(path, headers, body, content_type, receiver, progress);
  4952. });
  4953. }
  4954. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4955. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4956. using ClientT = SSLClient;
  4957. #else
  4958. using ClientT = Client;
  4959. #endif
  4960. TestWithHeadersAndContentReceiver<ClientT>(
  4961. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4962. const std::string &body, const std::string &content_type,
  4963. ContentReceiver receiver, DownloadProgress progress) {
  4964. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4965. });
  4966. }
  4967. template <typename ClientType>
  4968. void TestWithHeadersAndContentReceiverWithProgress(
  4969. ClientType &cli,
  4970. std::function<Result(ClientType &, const std::string &, const Headers &,
  4971. const std::string &, const std::string &,
  4972. ContentReceiver, DownloadProgress)>
  4973. request_func) {
  4974. Headers headers;
  4975. headers.emplace("X-Test-Header", "progress-test");
  4976. std::string received_body;
  4977. auto progress_called = false;
  4978. auto res = request_func(
  4979. cli, "/content_receiver", headers, "content", "text/plain",
  4980. [&](const char *data, size_t data_length) {
  4981. received_body.append(data, data_length);
  4982. return true;
  4983. },
  4984. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4985. progress_called = true;
  4986. return true;
  4987. });
  4988. ASSERT_TRUE(res);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. EXPECT_EQ("content", received_body);
  4991. EXPECT_TRUE(progress_called);
  4992. }
  4993. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4995. using ClientT = SSLClient;
  4996. #else
  4997. using ClientT = Client;
  4998. #endif
  4999. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5001. const std::string &body, const std::string &content_type,
  5002. ContentReceiver receiver, DownloadProgress progress) {
  5003. return cli.Post(path, headers, body, content_type, receiver, progress);
  5004. });
  5005. }
  5006. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5008. using ClientT = SSLClient;
  5009. #else
  5010. using ClientT = Client;
  5011. #endif
  5012. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5014. const std::string &body, const std::string &content_type,
  5015. ContentReceiver receiver, DownloadProgress progress) {
  5016. return cli.Put(path, headers, body, content_type, receiver, progress);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5021. using ClientT = SSLClient;
  5022. #else
  5023. using ClientT = Client;
  5024. #endif
  5025. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5026. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5027. const std::string &body, const std::string &content_type,
  5028. ContentReceiver receiver, DownloadProgress progress) {
  5029. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5030. });
  5031. }
  5032. template <typename ClientType>
  5033. void TestWithHeadersAndContentReceiverError(
  5034. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5035. const Headers &, const std::string &,
  5036. const std::string &, ContentReceiver)>
  5037. request_func) {
  5038. Headers headers;
  5039. headers.emplace("X-Error-Test", "true");
  5040. std::string received_body;
  5041. auto receiver_failed = false;
  5042. auto res =
  5043. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5044. [&](const char *data, size_t data_length) {
  5045. received_body.append(data, data_length);
  5046. receiver_failed = true;
  5047. return false;
  5048. });
  5049. ASSERT_FALSE(res);
  5050. EXPECT_TRUE(receiver_failed);
  5051. }
  5052. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5054. using ClientT = SSLClient;
  5055. #else
  5056. using ClientT = Client;
  5057. #endif
  5058. TestWithHeadersAndContentReceiverError<ClientT>(
  5059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5060. const std::string &body, const std::string &content_type,
  5061. ContentReceiver receiver) {
  5062. return cli.Post(path, headers, body, content_type, receiver);
  5063. });
  5064. }
  5065. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5066. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5067. using ClientT = SSLClient;
  5068. #else
  5069. using ClientT = Client;
  5070. #endif
  5071. TestWithHeadersAndContentReceiverError<ClientT>(
  5072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5073. const std::string &body, const std::string &content_type,
  5074. ContentReceiver receiver) {
  5075. return cli.Put(path, headers, body, content_type, receiver);
  5076. });
  5077. }
  5078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5080. using ClientT = SSLClient;
  5081. #else
  5082. using ClientT = Client;
  5083. #endif
  5084. TestWithHeadersAndContentReceiverError<ClientT>(
  5085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5086. const std::string &body, const std::string &content_type,
  5087. ContentReceiver receiver) {
  5088. return cli.Patch(path, headers, body, content_type, receiver);
  5089. });
  5090. }
  5091. TEST_F(ServerTest, PostQueryStringAndBody) {
  5092. auto res =
  5093. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5094. ASSERT_TRUE(res);
  5095. ASSERT_EQ(StatusCode::OK_200, res->status);
  5096. }
  5097. TEST_F(ServerTest, HTTP2Magic) {
  5098. Request req;
  5099. req.method = "PRI";
  5100. req.path = "*";
  5101. req.body = "SM";
  5102. auto res = std::make_shared<Response>();
  5103. auto error = Error::Success;
  5104. auto ret = cli_.send(req, *res, error);
  5105. ASSERT_TRUE(ret);
  5106. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5107. }
  5108. TEST_F(ServerTest, KeepAlive) {
  5109. auto res = cli_.Get("/hi");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("Hello World!", res->body);
  5114. res = cli_.Get("/hi");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ("Hello World!", res->body);
  5119. res = cli_.Get("/hi");
  5120. ASSERT_TRUE(res);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5123. EXPECT_EQ("Hello World!", res->body);
  5124. res = cli_.Get("/not-exist");
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5127. res = cli_.Post("/empty", "", "text/plain");
  5128. ASSERT_TRUE(res);
  5129. EXPECT_EQ(StatusCode::OK_200, res->status);
  5130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5131. EXPECT_EQ("empty", res->body);
  5132. EXPECT_EQ("close", res->get_header_value("Connection"));
  5133. res = cli_.Post(
  5134. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5135. "text/plain");
  5136. ASSERT_TRUE(res);
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5139. EXPECT_EQ("empty", res->body);
  5140. cli_.set_keep_alive(false);
  5141. res = cli_.Get("/last-request");
  5142. ASSERT_TRUE(res);
  5143. EXPECT_EQ(StatusCode::OK_200, res->status);
  5144. EXPECT_EQ("close", res->get_header_value("Connection"));
  5145. }
  5146. TEST_F(ServerTest, TooManyRedirect) {
  5147. cli_.set_follow_location(true);
  5148. auto res = cli_.Get("/redirect/0");
  5149. ASSERT_TRUE(!res);
  5150. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5151. }
  5152. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5153. Request req;
  5154. req.method = "FOOBAR";
  5155. req.path = "/hi";
  5156. cli_.set_keep_alive(true);
  5157. auto res = cli_.send(req);
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5160. EXPECT_EQ("close", res->get_header_value("Connection"));
  5161. EXPECT_FALSE(cli_.is_socket_open());
  5162. }
  5163. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5164. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5165. TEST_F(ServerTest, Gzip) {
  5166. Headers headers;
  5167. headers.emplace("Accept-Encoding", "gzip, deflate");
  5168. auto res = cli_.Get("/compress", headers);
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5174. "7890123456789012345678901234567890",
  5175. res->body);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "");
  5181. auto res = cli_.Get("/compress", headers);
  5182. ASSERT_TRUE(res);
  5183. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5185. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5186. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5187. "7890123456789012345678901234567890",
  5188. res->body);
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. }
  5191. TEST_F(ServerTest, GzipWithContentReceiver) {
  5192. Headers headers;
  5193. headers.emplace("Accept-Encoding", "gzip, deflate");
  5194. std::string body;
  5195. auto res = cli_.Get("/compress", headers,
  5196. [&](const char *data, uint64_t data_length) {
  5197. EXPECT_EQ(100U, data_length);
  5198. body.append(data, data_length);
  5199. return true;
  5200. });
  5201. ASSERT_TRUE(res);
  5202. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5204. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5206. "7890123456789012345678901234567890",
  5207. body);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. }
  5210. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5211. Headers headers;
  5212. headers.emplace("Accept-Encoding", "gzip, deflate");
  5213. cli_.set_decompress(false);
  5214. auto res = cli_.Get("/compress", headers);
  5215. ASSERT_TRUE(res);
  5216. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5217. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5218. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5219. EXPECT_EQ(33U, res->body.size());
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. }
  5222. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5223. Headers headers;
  5224. headers.emplace("Accept-Encoding", "");
  5225. std::string body;
  5226. auto res = cli_.Get("/compress", headers,
  5227. [&](const char *data, uint64_t data_length) {
  5228. EXPECT_EQ(100U, data_length);
  5229. body.append(data, data_length);
  5230. return true;
  5231. });
  5232. ASSERT_TRUE(res);
  5233. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5237. "7890123456789012345678901234567890",
  5238. body);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, NoGzip) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "gzip, deflate");
  5244. auto res = cli_.Get("/nocompress", headers);
  5245. ASSERT_TRUE(res);
  5246. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5247. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("100", 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. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "gzip, deflate");
  5257. std::string body;
  5258. auto res = cli_.Get("/nocompress", headers,
  5259. [&](const char *data, uint64_t data_length) {
  5260. EXPECT_EQ(100U, data_length);
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5266. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5267. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5269. "7890123456789012345678901234567890",
  5270. body);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST_F(ServerTest, MultipartFormDataGzip) {
  5274. UploadFormDataItems items = {
  5275. {"key1", "test", "", ""},
  5276. {"key2", "--abcdefg123", "", ""},
  5277. };
  5278. cli_.set_compress(true);
  5279. auto res = cli_.Post("/compress-multipart", items);
  5280. ASSERT_TRUE(res);
  5281. EXPECT_EQ(StatusCode::OK_200, res->status);
  5282. }
  5283. #endif
  5284. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5285. TEST_F(ServerTest, Brotli) {
  5286. Headers headers;
  5287. headers.emplace("Accept-Encoding", "br");
  5288. auto res = cli_.Get("/compress", headers);
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5292. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5293. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5294. "7890123456789012345678901234567890",
  5295. res->body);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. }
  5298. #endif
  5299. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5300. TEST_F(ServerTest, Zstd) {
  5301. Headers headers;
  5302. headers.emplace("Accept-Encoding", "zstd");
  5303. auto res = cli_.Get("/compress", headers);
  5304. ASSERT_TRUE(res);
  5305. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5306. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5307. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5308. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5309. "7890123456789012345678901234567890",
  5310. res->body);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. }
  5313. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5314. Headers headers;
  5315. headers.emplace("Accept-Encoding", "");
  5316. auto res = cli_.Get("/compress", headers);
  5317. ASSERT_TRUE(res);
  5318. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5320. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5321. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5322. "7890123456789012345678901234567890",
  5323. res->body);
  5324. EXPECT_EQ(StatusCode::OK_200, res->status);
  5325. }
  5326. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5327. Headers headers;
  5328. headers.emplace("Accept-Encoding", "zstd");
  5329. std::string body;
  5330. auto res = cli_.Get("/compress", headers,
  5331. [&](const char *data, uint64_t data_length) {
  5332. EXPECT_EQ(100U, data_length);
  5333. body.append(data, data_length);
  5334. return true;
  5335. });
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5341. "7890123456789012345678901234567890",
  5342. body);
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "zstd");
  5348. cli_.set_decompress(false);
  5349. auto res = cli_.Get("/compress", headers);
  5350. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5351. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5352. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5353. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5354. ASSERT_TRUE(res);
  5355. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. ASSERT_EQ(26U, res->body.size());
  5360. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5361. 0);
  5362. }
  5363. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5364. Headers headers;
  5365. headers.emplace("Accept-Encoding", "");
  5366. std::string body;
  5367. auto res = cli_.Get("/compress", headers,
  5368. [&](const char *data, uint64_t data_length) {
  5369. EXPECT_EQ(100U, data_length);
  5370. body.append(data, data_length);
  5371. return true;
  5372. });
  5373. ASSERT_TRUE(res);
  5374. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5376. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5377. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5378. "7890123456789012345678901234567890",
  5379. body);
  5380. EXPECT_EQ(StatusCode::OK_200, res->status);
  5381. }
  5382. TEST_F(ServerTest, NoZstd) {
  5383. Headers headers;
  5384. headers.emplace("Accept-Encoding", "zstd");
  5385. auto res = cli_.Get("/nocompress", headers);
  5386. ASSERT_TRUE(res);
  5387. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5388. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5389. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5390. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5391. "7890123456789012345678901234567890",
  5392. res->body);
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. }
  5395. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5396. Headers headers;
  5397. headers.emplace("Accept-Encoding", "zstd");
  5398. std::string body;
  5399. auto res = cli_.Get("/nocompress", headers,
  5400. [&](const char *data, uint64_t data_length) {
  5401. EXPECT_EQ(100U, data_length);
  5402. body.append(data, data_length);
  5403. return true;
  5404. });
  5405. ASSERT_TRUE(res);
  5406. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5407. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5408. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5410. "7890123456789012345678901234567890",
  5411. body);
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. }
  5414. // TODO: How to enable zstd ??
  5415. TEST_F(ServerTest, MultipartFormDataZstd) {
  5416. UploadFormDataItems items = {
  5417. {"key1", "test", "", ""},
  5418. {"key2", "--abcdefg123", "", ""},
  5419. };
  5420. Headers headers;
  5421. headers.emplace("Accept-Encoding", "zstd");
  5422. cli_.set_compress(true);
  5423. auto res = cli_.Post("/compress-multipart", headers, items);
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. }
  5427. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5428. Headers headers;
  5429. headers.emplace("Accept-Encoding", "zstd");
  5430. cli_.set_compress(true);
  5431. auto res = cli_.Put(
  5432. "/put", headers, 3,
  5433. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5434. sink.os << "PUT";
  5435. return true;
  5436. },
  5437. "text/plain");
  5438. ASSERT_TRUE(res);
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. EXPECT_EQ("PUT", res->body);
  5441. }
  5442. // Pre-compression logging tests
  5443. TEST_F(ServerTest, PreCompressionLogging) {
  5444. // Test data for compression (matches the actual /compress endpoint content)
  5445. const std::string test_content =
  5446. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5447. "3456789012345678901234567890";
  5448. // Variables to capture logging data
  5449. std::string pre_compression_body;
  5450. std::string pre_compression_content_type;
  5451. std::string pre_compression_content_encoding;
  5452. std::string post_compression_body;
  5453. std::string post_compression_content_type;
  5454. std::string post_compression_content_encoding;
  5455. // Set up pre-compression logger
  5456. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5457. const Response &res) {
  5458. pre_compression_body = res.body;
  5459. pre_compression_content_type = res.get_header_value("Content-Type");
  5460. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5461. });
  5462. // Set up post-compression logger
  5463. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5464. post_compression_body = res.body;
  5465. post_compression_content_type = res.get_header_value("Content-Type");
  5466. post_compression_content_encoding =
  5467. res.get_header_value("Content-Encoding");
  5468. });
  5469. // Test with gzip compression
  5470. Headers headers;
  5471. headers.emplace("Accept-Encoding", "gzip");
  5472. auto res = cli_.Get("/compress", headers);
  5473. // Verify response was compressed
  5474. ASSERT_TRUE(res);
  5475. EXPECT_EQ(StatusCode::OK_200, res->status);
  5476. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5477. // Verify pre-compression logger captured uncompressed content
  5478. EXPECT_EQ(test_content, pre_compression_body);
  5479. EXPECT_EQ("text/plain", pre_compression_content_type);
  5480. EXPECT_TRUE(pre_compression_content_encoding
  5481. .empty()); // No encoding header before compression
  5482. // Verify post-compression logger captured compressed content
  5483. EXPECT_NE(test_content,
  5484. post_compression_body); // Should be different after compression
  5485. EXPECT_EQ("text/plain", post_compression_content_type);
  5486. EXPECT_EQ("gzip", post_compression_content_encoding);
  5487. // Verify compressed content is smaller
  5488. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5489. }
  5490. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5491. const std::string test_content =
  5492. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5493. "3456789012345678901234567890";
  5494. std::string pre_compression_body;
  5495. std::string post_compression_body;
  5496. svr_.set_pre_compression_logger(
  5497. [&](const Request & /*req*/, const Response &res) {
  5498. pre_compression_body = res.body;
  5499. });
  5500. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5501. post_compression_body = res.body;
  5502. });
  5503. Headers headers;
  5504. headers.emplace("Accept-Encoding", "br");
  5505. auto res = cli_.Get("/compress", headers);
  5506. ASSERT_TRUE(res);
  5507. EXPECT_EQ(StatusCode::OK_200, res->status);
  5508. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5509. // Verify pre-compression content is uncompressed
  5510. EXPECT_EQ(test_content, pre_compression_body);
  5511. // Verify post-compression content is compressed
  5512. EXPECT_NE(test_content, post_compression_body);
  5513. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5514. }
  5515. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5516. const std::string test_content =
  5517. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5518. "3456789012345678901234567890";
  5519. std::string pre_compression_body;
  5520. std::string post_compression_body;
  5521. svr_.set_pre_compression_logger(
  5522. [&](const Request & /*req*/, const Response &res) {
  5523. pre_compression_body = res.body;
  5524. });
  5525. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5526. post_compression_body = res.body;
  5527. });
  5528. // Request without compression (use /nocompress endpoint)
  5529. Headers headers;
  5530. auto res = cli_.Get("/nocompress", headers);
  5531. ASSERT_TRUE(res);
  5532. EXPECT_EQ(StatusCode::OK_200, res->status);
  5533. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5534. // Pre-compression logger should not be called when no compression is applied
  5535. EXPECT_TRUE(
  5536. pre_compression_body.empty()); // Pre-compression logger not called
  5537. EXPECT_EQ(
  5538. test_content,
  5539. post_compression_body); // Post-compression logger captures final content
  5540. }
  5541. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5542. const std::string test_content =
  5543. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5544. "3456789012345678901234567890";
  5545. std::string pre_compression_body;
  5546. bool pre_logger_called = false;
  5547. // Set only pre-compression logger
  5548. svr_.set_pre_compression_logger(
  5549. [&](const Request & /*req*/, const Response &res) {
  5550. pre_compression_body = res.body;
  5551. pre_logger_called = true;
  5552. });
  5553. Headers headers;
  5554. headers.emplace("Accept-Encoding", "gzip");
  5555. auto res = cli_.Get("/compress", headers);
  5556. ASSERT_TRUE(res);
  5557. EXPECT_EQ(StatusCode::OK_200, res->status);
  5558. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5559. // Verify pre-compression logger was called
  5560. EXPECT_TRUE(pre_logger_called);
  5561. EXPECT_EQ(test_content, pre_compression_body);
  5562. }
  5563. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5564. {
  5565. // Test with Expect: 100-continue header - success case
  5566. // Server returns 100 Continue, client sends body, server returns 200 OK
  5567. Request req;
  5568. req.method = "POST";
  5569. req.path = "/post-large";
  5570. req.set_header("Expect", "100-continue");
  5571. req.body = LARGE_DATA;
  5572. Response res;
  5573. auto error = Error::Success;
  5574. cli_.set_keep_alive(true);
  5575. auto ret = cli_.send(req, res, error);
  5576. EXPECT_TRUE(ret);
  5577. EXPECT_EQ(StatusCode::OK_200, res.status);
  5578. EXPECT_EQ(LARGE_DATA, res.body);
  5579. }
  5580. {
  5581. // Test with Expect: 100-continue header - error case
  5582. // Client should not send the body when server returns an error
  5583. Request req;
  5584. req.method = "POST";
  5585. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5586. req.set_header("Expect", "100-continue");
  5587. req.body = LARGE_DATA;
  5588. Response res;
  5589. auto error = Error::Success;
  5590. auto start = std::chrono::high_resolution_clock::now();
  5591. cli_.set_keep_alive(true);
  5592. auto ret = cli_.send(req, res, error);
  5593. auto end = std::chrono::high_resolution_clock::now();
  5594. auto elapsed =
  5595. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5596. .count();
  5597. // With Expect: 100-continue, request completes successfully but with error
  5598. EXPECT_TRUE(ret);
  5599. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5600. EXPECT_EQ("close", res.get_header_value("Connection"));
  5601. EXPECT_FALSE(cli_.is_socket_open());
  5602. EXPECT_LE(elapsed, 200);
  5603. }
  5604. {
  5605. // Send an extra GET request to ensure error recovery without hanging
  5606. Request req;
  5607. req.method = "GET";
  5608. req.path = "/hi";
  5609. auto start = std::chrono::high_resolution_clock::now();
  5610. auto res = cli_.send(req);
  5611. auto end = std::chrono::high_resolution_clock::now();
  5612. auto elapsed =
  5613. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5614. .count();
  5615. ASSERT_TRUE(res);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. EXPECT_EQ("Hello World!", res->body);
  5618. EXPECT_LE(elapsed, 100);
  5619. }
  5620. }
  5621. TEST(ZstdDecompressor, ChunkedDecompression) {
  5622. std::string data;
  5623. for (size_t i = 0; i < 32 * 1024; ++i) {
  5624. data.push_back(static_cast<char>('a' + i % 26));
  5625. }
  5626. std::string compressed_data;
  5627. {
  5628. httplib::detail::zstd_compressor compressor;
  5629. bool result = compressor.compress(
  5630. data.data(), data.size(),
  5631. /*last=*/true,
  5632. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5633. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5634. compressed_data_size);
  5635. return true;
  5636. });
  5637. ASSERT_TRUE(result);
  5638. }
  5639. std::string decompressed_data;
  5640. {
  5641. httplib::detail::zstd_decompressor decompressor;
  5642. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5643. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5644. size_t chunk_size = 130;
  5645. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5646. chunk_begin += chunk_size) {
  5647. size_t current_chunk_size =
  5648. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5649. bool result = decompressor.decompress(
  5650. compressed_data.data() + chunk_begin, current_chunk_size,
  5651. [&](const char *decompressed_data_chunk,
  5652. size_t decompressed_data_chunk_size) {
  5653. decompressed_data.insert(decompressed_data.size(),
  5654. decompressed_data_chunk,
  5655. decompressed_data_chunk_size);
  5656. return true;
  5657. });
  5658. ASSERT_TRUE(result);
  5659. }
  5660. }
  5661. ASSERT_EQ(data, decompressed_data);
  5662. }
  5663. TEST(ZstdDecompressor, Decompress) {
  5664. std::string original_text = "Compressed with ZSTD";
  5665. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5666. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5667. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5668. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5669. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5670. std::string decompressed_data;
  5671. {
  5672. httplib::detail::zstd_decompressor decompressor;
  5673. bool result = decompressor.decompress(
  5674. compressed_data.data(), compressed_data.size(),
  5675. [&](const char *decompressed_data_chunk,
  5676. size_t decompressed_data_chunk_size) {
  5677. decompressed_data.insert(decompressed_data.size(),
  5678. decompressed_data_chunk,
  5679. decompressed_data_chunk_size);
  5680. return true;
  5681. });
  5682. ASSERT_TRUE(result);
  5683. }
  5684. ASSERT_EQ(original_text, decompressed_data);
  5685. }
  5686. #endif
  5687. // Sends a raw request to a server listening at HOST:PORT.
  5688. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5689. std::string *resp = nullptr) {
  5690. auto error = Error::Success;
  5691. auto client_sock = detail::create_client_socket(
  5692. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5693. /*connection_timeout_sec=*/5, 0,
  5694. /*read_timeout_sec=*/5, 0,
  5695. /*write_timeout_sec=*/5, 0, std::string(), error);
  5696. if (client_sock == INVALID_SOCKET) { return false; }
  5697. auto ret = detail::process_client_socket(
  5698. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5699. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5700. if (req.size() !=
  5701. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5702. return false;
  5703. }
  5704. char buf[512];
  5705. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5706. while (line_reader.getline()) {
  5707. if (resp) { *resp += line_reader.ptr(); }
  5708. }
  5709. return true;
  5710. });
  5711. detail::close_socket(client_sock);
  5712. return ret;
  5713. }
  5714. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5715. Server svr;
  5716. std::string header_value;
  5717. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5718. header_value = req.get_header_value("foo");
  5719. res.set_content("ok", "text/plain");
  5720. });
  5721. thread t = thread([&] { svr.listen(HOST, PORT); });
  5722. auto se = detail::scope_exit([&] {
  5723. svr.stop();
  5724. t.join();
  5725. ASSERT_FALSE(svr.is_running());
  5726. });
  5727. svr.wait_until_ready();
  5728. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5729. // like characters are not treated the same - use vertical tab and escape.
  5730. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5731. "foo: \t \v bar \x1B\t \r\n"
  5732. "Connection: close\r\n"
  5733. "\r\n";
  5734. std::string res;
  5735. ASSERT_TRUE(send_request(5, req, &res));
  5736. EXPECT_EQ(header_value, "");
  5737. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5738. }
  5739. // Sends a raw request and verifies that there isn't a crash or exception.
  5740. static void test_raw_request(const std::string &req,
  5741. std::string *out = nullptr) {
  5742. Server svr;
  5743. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5744. res.set_content("ok", "text/plain");
  5745. });
  5746. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5747. res.set_content("ok", "text/plain");
  5748. });
  5749. svr.Get("/header_field_value_check",
  5750. [&](const Request & /*req*/, Response &res) {
  5751. res.set_content("ok", "text/plain");
  5752. });
  5753. // Server read timeout must be longer than the client read timeout for the
  5754. // bug to reproduce, probably to force the server to process a request
  5755. // without a trailing blank line.
  5756. const time_t client_read_timeout_sec = 1;
  5757. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5758. bool listen_thread_ok = false;
  5759. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5760. auto se = detail::scope_exit([&] {
  5761. svr.stop();
  5762. t.join();
  5763. ASSERT_FALSE(svr.is_running());
  5764. EXPECT_TRUE(listen_thread_ok);
  5765. });
  5766. svr.wait_until_ready();
  5767. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5768. }
  5769. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5770. // A certain header line causes an exception if the header property is parsed
  5771. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5772. test_raw_request(
  5773. "GET /hi HTTP/1.1\r\n"
  5774. " : "
  5775. " "
  5776. " ");
  5777. }
  5778. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5779. // A certain header line causes an exception if the header property *name* is
  5780. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5781. // greedy matcher and requires backtracking when there are a lot of ":"
  5782. // characters.
  5783. // This occurs with libc++ but not libstdc++.
  5784. test_raw_request(
  5785. "GET /hi HTTP/1.1\r\n"
  5786. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5787. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5788. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5789. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5790. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5791. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5792. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5793. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5794. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5795. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5796. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5797. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5798. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5799. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5800. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5801. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5802. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5803. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5804. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5805. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5806. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5807. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5808. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5809. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5810. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5811. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5812. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5813. "&&&%%%");
  5814. }
  5815. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5816. // Make sure this doesn't crash the server.
  5817. // In a previous version of the header line regex, the "\r" rendered the line
  5818. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5819. // a new position where the leading white space ended and the field value
  5820. // began.
  5821. // The crash occurs with libc++ but not libstdc++.
  5822. test_raw_request("GET /hi HTTP/1.1\r\n"
  5823. "a:" +
  5824. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5825. "\r\n"
  5826. "\r\n");
  5827. }
  5828. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5829. std::string out;
  5830. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5831. "Content-Type: text/plain\r\n"
  5832. "Transfer-Encoding: chunked\r\n"
  5833. "\r\n"
  5834. "nothex\r\n",
  5835. &out);
  5836. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5837. }
  5838. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5839. std::string out;
  5840. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5841. "Content-Type: text/plain\r\n"
  5842. "Transfer-Encoding: chunked\r\n"
  5843. "\r\n"
  5844. "3\r\n"
  5845. "xyz\r\n"
  5846. "NaN\r\n",
  5847. &out);
  5848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5849. }
  5850. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5851. std::string out;
  5852. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5853. "Content-Type: text/plain\r\n"
  5854. "Transfer-Encoding: chunked\r\n"
  5855. "\r\n"
  5856. // Length is too large for 64 bits.
  5857. "1ffffffffffffffff\r\n"
  5858. "xyz\r\n",
  5859. &out);
  5860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5861. }
  5862. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5863. test_raw_request("GET /hi HTTP/1.1\r\n"
  5864. "Content-Type: text/plain\r\n\r");
  5865. }
  5866. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5867. std::string out;
  5868. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5869. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5870. }
  5871. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5872. Server svr;
  5873. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5874. EXPECT_TRUE(!req.remote_addr.empty());
  5875. });
  5876. thread t = thread([&] { svr.listen(HOST, PORT); });
  5877. auto se = detail::scope_exit([&] {
  5878. svr.stop();
  5879. t.join();
  5880. ASSERT_FALSE(svr.is_running());
  5881. });
  5882. svr.wait_until_ready();
  5883. // Send an invalid request line to trigger Bad Request
  5884. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5885. std::string out;
  5886. ASSERT_TRUE(send_request(5, bad_req, &out));
  5887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5888. }
  5889. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5890. std::string out;
  5891. std::string request(
  5892. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5893. test_raw_request(request, &out);
  5894. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5895. }
  5896. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5897. std::string out;
  5898. std::string request(
  5899. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5900. test_raw_request(request, &out);
  5901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5902. }
  5903. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5904. std::string out;
  5905. std::string request(
  5906. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5907. test_raw_request(request, &out);
  5908. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5909. }
  5910. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5911. std::string out;
  5912. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5913. "Test: \r\n\r\n",
  5914. &out);
  5915. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5916. }
  5917. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5918. Server svr;
  5919. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5920. res.set_header("Cache-Control", "no-cache");
  5921. res.set_chunked_content_provider(
  5922. "text/event-stream", [](size_t offset, DataSink &sink) {
  5923. std::string s = "data:";
  5924. s += std::to_string(offset);
  5925. s += "\n\n";
  5926. auto ret = sink.write(s.data(), s.size());
  5927. EXPECT_TRUE(ret);
  5928. std::this_thread::sleep_for(std::chrono::seconds(1));
  5929. return true;
  5930. });
  5931. });
  5932. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5933. svr.wait_until_ready();
  5934. Client client(HOST, PORT);
  5935. const Headers headers = {{"Accept", "text/event-stream"}};
  5936. auto get_thread = std::thread([&client, &headers]() {
  5937. auto res = client.Get(
  5938. "/events", headers,
  5939. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5940. });
  5941. auto se = detail::scope_exit([&] {
  5942. svr.stop();
  5943. get_thread.join();
  5944. listen_thread.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. // Give GET time to get a few messages.
  5948. std::this_thread::sleep_for(std::chrono::seconds(2));
  5949. }
  5950. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5951. httplib::Server svr;
  5952. svr.Post("/hi",
  5953. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5954. res.status = StatusCode::OK_200;
  5955. });
  5956. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5957. svr.wait_until_ready();
  5958. Client cli(HOST, PORT);
  5959. auto res = cli.Post("/hi", "data", "text/plain");
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ(StatusCode::OK_200, res->status);
  5962. svr.stop();
  5963. thread.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. res = cli.Post("/hi", "data", "text/plain");
  5966. ASSERT_FALSE(res);
  5967. }
  5968. TEST(ServerStopTest, ListenFailure) {
  5969. Server svr;
  5970. auto t = thread([&]() {
  5971. auto ret = svr.listen("????", PORT);
  5972. EXPECT_FALSE(ret);
  5973. });
  5974. svr.wait_until_ready();
  5975. svr.stop();
  5976. t.join();
  5977. }
  5978. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5979. TEST(ServerStopTest, Decommision) {
  5980. Server svr;
  5981. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5982. for (int i = 0; i < 4; i++) {
  5983. auto is_even = !(i % 2);
  5984. std::thread t{[&] {
  5985. try {
  5986. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5987. if (is_even) {
  5988. throw std::runtime_error("Some thing that happens to go wrong.");
  5989. }
  5990. svr.listen(HOST, PORT);
  5991. } catch (...) { svr.decommission(); }
  5992. }};
  5993. svr.wait_until_ready();
  5994. // Server is up
  5995. {
  5996. Client cli(HOST, PORT);
  5997. auto res = cli.Get("/hi");
  5998. if (is_even) {
  5999. EXPECT_FALSE(res);
  6000. } else {
  6001. EXPECT_TRUE(res);
  6002. EXPECT_EQ("hi...", res->body);
  6003. }
  6004. }
  6005. svr.stop();
  6006. t.join();
  6007. // Server is down...
  6008. {
  6009. Client cli(HOST, PORT);
  6010. auto res = cli.Get("/hi");
  6011. EXPECT_FALSE(res);
  6012. }
  6013. }
  6014. }
  6015. #endif
  6016. // Helper function for string body upload progress tests
  6017. template <typename SetupHandler, typename ClientCall>
  6018. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6019. ClientCall &&client_call,
  6020. const string &body) {
  6021. Server svr;
  6022. setup_handler(svr);
  6023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6024. auto se = detail::scope_exit([&] {
  6025. svr.stop();
  6026. t.join();
  6027. });
  6028. svr.wait_until_ready();
  6029. Client cli(HOST, PORT);
  6030. vector<uint64_t> progress_values;
  6031. bool progress_called = false;
  6032. auto res =
  6033. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6034. progress_values.push_back(current);
  6035. progress_called = true;
  6036. return true;
  6037. });
  6038. ASSERT_TRUE(res);
  6039. EXPECT_EQ(200, res->status);
  6040. EXPECT_TRUE(progress_called);
  6041. }
  6042. TEST(UploadProgressTest, PostStringBodyBasic) {
  6043. TestStringBodyUploadProgress(
  6044. [](Server &svr) {
  6045. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6046. res.set_content("received", "text/plain");
  6047. });
  6048. },
  6049. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6050. return cli.Post("/test", body, "text/plain", progress_callback);
  6051. },
  6052. "test data for upload progress");
  6053. }
  6054. TEST(UploadProgressTest, PutStringBodyBasic) {
  6055. TestStringBodyUploadProgress(
  6056. [](Server &svr) {
  6057. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6058. res.set_content("put received", "text/plain");
  6059. });
  6060. },
  6061. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6062. return cli.Put("/test", body, "text/plain", progress_callback);
  6063. },
  6064. "put test data for upload progress");
  6065. }
  6066. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6067. TestStringBodyUploadProgress(
  6068. [](Server &svr) {
  6069. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6070. res.set_content("patch received", "text/plain");
  6071. });
  6072. },
  6073. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6074. return cli.Patch("/test", body, "text/plain", progress_callback);
  6075. },
  6076. "patch test data for upload progress");
  6077. }
  6078. // Helper function for content provider upload progress tests
  6079. template <typename SetupHandler, typename ClientCall>
  6080. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6081. ClientCall &&client_call) {
  6082. Server svr;
  6083. setup_handler(svr);
  6084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6085. auto se = detail::scope_exit([&] {
  6086. svr.stop();
  6087. t.join();
  6088. });
  6089. svr.wait_until_ready();
  6090. Client cli(HOST, PORT);
  6091. vector<uint64_t> progress_values;
  6092. auto res =
  6093. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6094. progress_values.push_back(current);
  6095. return true;
  6096. });
  6097. ASSERT_TRUE(res);
  6098. EXPECT_EQ(200, res->status);
  6099. EXPECT_FALSE(progress_values.empty());
  6100. }
  6101. TEST(UploadProgressTest, PostContentProviderProgress) {
  6102. TestContentProviderUploadProgress(
  6103. [](Server &svr) {
  6104. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6105. res.set_content("provider received", "text/plain");
  6106. });
  6107. },
  6108. [](Client &cli, UploadProgress progress_callback) {
  6109. return cli.Post(
  6110. "/test", 10,
  6111. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6112. sink.os << "test data";
  6113. return true;
  6114. },
  6115. "text/plain", progress_callback);
  6116. });
  6117. }
  6118. // Helper function for multipart upload progress tests
  6119. template <typename SetupHandler, typename ClientCall>
  6120. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6121. ClientCall &&client_call,
  6122. const string &endpoint) {
  6123. Server svr;
  6124. setup_handler(svr);
  6125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6126. auto se = detail::scope_exit([&] {
  6127. svr.stop();
  6128. t.join();
  6129. });
  6130. svr.wait_until_ready();
  6131. Client cli(HOST, PORT);
  6132. vector<uint64_t> progress_values;
  6133. UploadFormDataItems items = {
  6134. {"field1", "value1", "", ""},
  6135. {"field2", "longer value for progress tracking test", "", ""},
  6136. {"file1", "file content data for upload progress", "test.txt",
  6137. "text/plain"}};
  6138. auto res = client_call(cli, endpoint, items,
  6139. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6140. progress_values.push_back(current);
  6141. return true;
  6142. });
  6143. ASSERT_TRUE(res);
  6144. EXPECT_EQ(200, res->status);
  6145. EXPECT_FALSE(progress_values.empty());
  6146. }
  6147. TEST(UploadProgressTest, PostMultipartProgress) {
  6148. TestMultipartUploadProgress(
  6149. [](Server &svr) {
  6150. svr.Post("/multipart", [](const Request &req, Response &res) {
  6151. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6152. res.set_content("multipart received", "text/plain");
  6153. });
  6154. },
  6155. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6156. UploadProgress progress_callback) {
  6157. return cli.Post(endpoint, items, progress_callback);
  6158. },
  6159. "/multipart");
  6160. }
  6161. // Helper function for basic download progress tests
  6162. template <typename SetupHandler, typename ClientCall>
  6163. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6164. ClientCall &&client_call, const string &endpoint,
  6165. size_t expected_content_size) {
  6166. Server svr;
  6167. setup_handler(svr);
  6168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6169. auto se = detail::scope_exit([&] {
  6170. svr.stop();
  6171. t.join();
  6172. });
  6173. svr.wait_until_ready();
  6174. Client cli(HOST, PORT);
  6175. vector<uint64_t> progress_values;
  6176. auto res = client_call(cli, endpoint,
  6177. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6178. progress_values.push_back(current);
  6179. return true;
  6180. });
  6181. ASSERT_TRUE(res);
  6182. EXPECT_EQ(200, res->status);
  6183. EXPECT_FALSE(progress_values.empty());
  6184. EXPECT_EQ(expected_content_size, res->body.size());
  6185. }
  6186. TEST(DownloadProgressTest, GetBasic) {
  6187. TestBasicDownloadProgress(
  6188. [](Server &svr) {
  6189. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6190. string content(1000, 'D');
  6191. res.set_content(content, "text/plain");
  6192. });
  6193. },
  6194. [](Client &cli, const string &endpoint,
  6195. DownloadProgress progress_callback) {
  6196. return cli.Get(endpoint, progress_callback);
  6197. },
  6198. "/download", 1000u);
  6199. }
  6200. // Helper function for content receiver download progress tests
  6201. template <typename SetupHandler, typename ClientCall>
  6202. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6203. ClientCall &&client_call,
  6204. const string &endpoint,
  6205. size_t expected_content_size) {
  6206. Server svr;
  6207. setup_handler(svr);
  6208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6209. auto se = detail::scope_exit([&] {
  6210. svr.stop();
  6211. t.join();
  6212. });
  6213. svr.wait_until_ready();
  6214. Client cli(HOST, PORT);
  6215. vector<uint64_t> progress_values;
  6216. string received_body;
  6217. auto res = client_call(
  6218. cli, endpoint,
  6219. [&](const char *data, size_t data_length) -> bool {
  6220. received_body.append(data, data_length);
  6221. return true;
  6222. },
  6223. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6224. progress_values.push_back(current);
  6225. return true;
  6226. });
  6227. ASSERT_TRUE(res);
  6228. EXPECT_EQ(200, res->status);
  6229. EXPECT_FALSE(progress_values.empty());
  6230. EXPECT_EQ(expected_content_size, received_body.size());
  6231. EXPECT_TRUE(res->body.empty());
  6232. }
  6233. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6234. TestContentReceiverDownloadProgress(
  6235. [](Server &svr) {
  6236. svr.Get("/download-receiver",
  6237. [](const Request & /*req*/, Response &res) {
  6238. string content(2000, 'R');
  6239. res.set_content(content, "text/plain");
  6240. });
  6241. },
  6242. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6243. DownloadProgress progress_callback) {
  6244. return cli.Get(endpoint, content_receiver, progress_callback);
  6245. },
  6246. "/download-receiver", 2000u);
  6247. }
  6248. TEST(StreamingTest, NoContentLengthStreaming) {
  6249. Server svr;
  6250. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6251. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6252. if (offset < 6) {
  6253. sink.os << (offset < 3 ? "a" : "b");
  6254. } else {
  6255. sink.done();
  6256. }
  6257. return true;
  6258. });
  6259. });
  6260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6261. auto listen_se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. listen_thread.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. Client client(HOST, PORT);
  6268. auto get_thread = std::thread([&client]() {
  6269. std::string s;
  6270. auto res =
  6271. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6272. s += std::string(data, len);
  6273. return true;
  6274. });
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ("aaabbb", s);
  6278. });
  6279. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6280. // Give GET time to get a few messages.
  6281. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6282. }
  6283. TEST(MountTest, Unmount) {
  6284. Server svr;
  6285. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6286. auto se = detail::scope_exit([&] {
  6287. svr.stop();
  6288. listen_thread.join();
  6289. ASSERT_FALSE(svr.is_running());
  6290. });
  6291. svr.wait_until_ready();
  6292. Client cli("localhost", PORT);
  6293. svr.set_mount_point("/mount2", "./www2");
  6294. auto res = cli.Get("/");
  6295. ASSERT_TRUE(res);
  6296. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6297. res = cli.Get("/mount2/dir/test.html");
  6298. ASSERT_TRUE(res);
  6299. EXPECT_EQ(StatusCode::OK_200, res->status);
  6300. svr.set_mount_point("/", "./www");
  6301. res = cli.Get("/dir/");
  6302. ASSERT_TRUE(res);
  6303. EXPECT_EQ(StatusCode::OK_200, res->status);
  6304. svr.remove_mount_point("/");
  6305. res = cli.Get("/dir/");
  6306. ASSERT_TRUE(res);
  6307. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6308. svr.remove_mount_point("/mount2");
  6309. res = cli.Get("/mount2/dir/test.html");
  6310. ASSERT_TRUE(res);
  6311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6312. }
  6313. TEST(MountTest, Redicect) {
  6314. Server svr;
  6315. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6316. auto se = detail::scope_exit([&] {
  6317. svr.stop();
  6318. listen_thread.join();
  6319. ASSERT_FALSE(svr.is_running());
  6320. });
  6321. svr.set_mount_point("/", "./www");
  6322. svr.wait_until_ready();
  6323. Client cli("localhost", PORT);
  6324. auto res = cli.Get("/dir/");
  6325. ASSERT_TRUE(res);
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. res = cli.Get("/dir");
  6328. ASSERT_TRUE(res);
  6329. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6330. res = cli.Get("/file");
  6331. ASSERT_TRUE(res);
  6332. EXPECT_EQ(StatusCode::OK_200, res->status);
  6333. res = cli.Get("/file/");
  6334. ASSERT_TRUE(res);
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. cli.set_follow_location(true);
  6337. res = cli.Get("/dir");
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. }
  6341. TEST(MountTest, MultibytesPathName) {
  6342. Server svr;
  6343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6344. auto se = detail::scope_exit([&] {
  6345. svr.stop();
  6346. listen_thread.join();
  6347. ASSERT_FALSE(svr.is_running());
  6348. });
  6349. svr.set_mount_point("/", "./www");
  6350. svr.wait_until_ready();
  6351. Client cli("localhost", PORT);
  6352. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6353. ASSERT_TRUE(res);
  6354. EXPECT_EQ(StatusCode::OK_200, res->status);
  6355. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6356. }
  6357. TEST(KeepAliveTest, ReadTimeout) {
  6358. Server svr;
  6359. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6360. std::this_thread::sleep_for(std::chrono::seconds(2));
  6361. res.set_content("a", "text/plain");
  6362. });
  6363. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6364. res.set_content("b", "text/plain");
  6365. });
  6366. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6367. auto se = detail::scope_exit([&] {
  6368. svr.stop();
  6369. listen_thread.join();
  6370. ASSERT_FALSE(svr.is_running());
  6371. });
  6372. svr.wait_until_ready();
  6373. Client cli("localhost", PORT);
  6374. cli.set_keep_alive(true);
  6375. cli.set_read_timeout(std::chrono::seconds(1));
  6376. auto resa = cli.Get("/a");
  6377. ASSERT_FALSE(resa);
  6378. EXPECT_EQ(Error::Read, resa.error());
  6379. auto resb = cli.Get("/b");
  6380. ASSERT_TRUE(resb);
  6381. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6382. EXPECT_EQ("b", resb->body);
  6383. }
  6384. TEST(KeepAliveTest, MaxCount) {
  6385. size_t keep_alive_max_count = 3;
  6386. Server svr;
  6387. svr.set_keep_alive_max_count(keep_alive_max_count);
  6388. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6389. res.set_content("Hello World!", "text/plain");
  6390. });
  6391. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6392. auto se = detail::scope_exit([&] {
  6393. svr.stop();
  6394. listen_thread.join();
  6395. ASSERT_FALSE(svr.is_running());
  6396. });
  6397. svr.wait_until_ready();
  6398. Client cli(HOST, PORT);
  6399. cli.set_keep_alive(true);
  6400. for (size_t i = 0; i < 5; i++) {
  6401. auto result = cli.Get("/hi");
  6402. ASSERT_TRUE(result);
  6403. EXPECT_EQ(StatusCode::OK_200, result->status);
  6404. if (i == keep_alive_max_count - 1) {
  6405. EXPECT_EQ("close", result->get_header_value("Connection"));
  6406. } else {
  6407. EXPECT_FALSE(result->has_header("Connection"));
  6408. }
  6409. }
  6410. }
  6411. TEST(KeepAliveTest, Issue1041) {
  6412. Server svr;
  6413. svr.set_keep_alive_timeout(3);
  6414. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6415. res.set_content("Hello World!", "text/plain");
  6416. });
  6417. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6418. auto se = detail::scope_exit([&] {
  6419. svr.stop();
  6420. listen_thread.join();
  6421. ASSERT_FALSE(svr.is_running());
  6422. });
  6423. svr.wait_until_ready();
  6424. Client cli(HOST, PORT);
  6425. cli.set_keep_alive(true);
  6426. auto result = cli.Get("/hi");
  6427. ASSERT_TRUE(result);
  6428. EXPECT_EQ(StatusCode::OK_200, result->status);
  6429. std::this_thread::sleep_for(std::chrono::seconds(5));
  6430. result = cli.Get("/hi");
  6431. ASSERT_TRUE(result);
  6432. EXPECT_EQ(StatusCode::OK_200, result->status);
  6433. }
  6434. TEST(KeepAliveTest, Issue1959) {
  6435. Server svr;
  6436. svr.set_keep_alive_timeout(5);
  6437. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6438. res.set_content("a", "text/plain");
  6439. });
  6440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6441. auto se = detail::scope_exit([&] {
  6442. if (!svr.is_running()) return;
  6443. svr.stop();
  6444. listen_thread.join();
  6445. ASSERT_FALSE(svr.is_running());
  6446. });
  6447. svr.wait_until_ready();
  6448. Client cli("localhost", PORT);
  6449. cli.set_keep_alive(true);
  6450. using namespace std::chrono;
  6451. auto start = steady_clock::now();
  6452. cli.Get("/a");
  6453. svr.stop();
  6454. listen_thread.join();
  6455. auto end = steady_clock::now();
  6456. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6457. EXPECT_LT(elapsed, 5000);
  6458. }
  6459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6460. TEST(KeepAliveTest, SSLClientReconnection) {
  6461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6462. ASSERT_TRUE(svr.is_valid());
  6463. svr.set_keep_alive_timeout(1);
  6464. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6465. res.set_content("Hello World!", "text/plain");
  6466. });
  6467. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6468. auto se = detail::scope_exit([&] {
  6469. svr.stop();
  6470. listen_thread.join();
  6471. ASSERT_FALSE(svr.is_running());
  6472. });
  6473. svr.wait_until_ready();
  6474. SSLClient cli(HOST, PORT);
  6475. cli.enable_server_certificate_verification(false);
  6476. cli.set_keep_alive(true);
  6477. auto result = cli.Get("/hi");
  6478. ASSERT_TRUE(result);
  6479. EXPECT_EQ(StatusCode::OK_200, result->status);
  6480. result = cli.Get("/hi");
  6481. ASSERT_TRUE(result);
  6482. EXPECT_EQ(StatusCode::OK_200, result->status);
  6483. std::this_thread::sleep_for(std::chrono::seconds(2));
  6484. // Recoonect
  6485. result = cli.Get("/hi");
  6486. ASSERT_TRUE(result);
  6487. EXPECT_EQ(StatusCode::OK_200, result->status);
  6488. result = cli.Get("/hi");
  6489. ASSERT_TRUE(result);
  6490. EXPECT_EQ(StatusCode::OK_200, result->status);
  6491. }
  6492. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6494. ASSERT_TRUE(svr.is_valid());
  6495. svr.set_keep_alive_timeout(1);
  6496. std::string content = "reconnect";
  6497. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6498. res.set_content("Hello World!", "text/plain");
  6499. });
  6500. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6501. auto se = detail::scope_exit([&] {
  6502. svr.stop();
  6503. listen_thread.join();
  6504. ASSERT_FALSE(svr.is_running());
  6505. });
  6506. svr.wait_until_ready();
  6507. SSLClient cli(HOST, PORT);
  6508. cli.enable_server_certificate_verification(false);
  6509. cli.set_keep_alive(true);
  6510. auto result = cli.Post(
  6511. "/hi", content.size(),
  6512. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6513. sink.write(content.c_str(), content.size());
  6514. return true;
  6515. },
  6516. "text/plain");
  6517. ASSERT_TRUE(result);
  6518. EXPECT_EQ(200, result->status);
  6519. std::this_thread::sleep_for(std::chrono::seconds(2));
  6520. // Recoonect
  6521. result = cli.Post(
  6522. "/hi", content.size(),
  6523. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6524. sink.write(content.c_str(), content.size());
  6525. return true;
  6526. },
  6527. "text/plain");
  6528. ASSERT_TRUE(result);
  6529. EXPECT_EQ(200, result->status);
  6530. result = cli.Post(
  6531. "/hi", content.size(),
  6532. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6533. sink.write(content.c_str(), content.size());
  6534. return true;
  6535. },
  6536. "text/plain");
  6537. ASSERT_TRUE(result);
  6538. EXPECT_EQ(200, result->status);
  6539. }
  6540. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6541. {
  6542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6543. ASSERT_TRUE(svr.is_valid());
  6544. svr.Get("/sni", [&](const Request &req, Response &res) {
  6545. std::string expected;
  6546. if (req.ssl) {
  6547. if (const char *sni =
  6548. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6549. expected = sni;
  6550. }
  6551. }
  6552. EXPECT_EQ(expected, req.get_param_value("expected"));
  6553. res.set_content("ok", "text/plain");
  6554. });
  6555. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6556. auto se = detail::scope_exit([&] {
  6557. svr.stop();
  6558. listen_thread.join();
  6559. ASSERT_FALSE(svr.is_running());
  6560. });
  6561. svr.wait_until_ready();
  6562. {
  6563. SSLClient cli("localhost", PORT);
  6564. cli.enable_server_certificate_verification(false);
  6565. auto res = cli.Get("/sni?expected=localhost");
  6566. ASSERT_TRUE(res);
  6567. }
  6568. {
  6569. SSLClient cli("::1", PORT);
  6570. cli.enable_server_certificate_verification(false);
  6571. auto res = cli.Get("/sni?expected=");
  6572. // NOTE: This may fail if the server is listening on IPv4 only
  6573. // (e.g., when localhost resolves to 127.0.0.1 only)
  6574. if (res) {
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. } else {
  6577. EXPECT_EQ(Error::Connection, res.error());
  6578. }
  6579. }
  6580. }
  6581. }
  6582. #endif
  6583. TEST(ClientProblemDetectionTest, ContentProvider) {
  6584. Server svr;
  6585. size_t content_length = 1024 * 1024;
  6586. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6587. res.set_content_provider(
  6588. content_length, "text/plain",
  6589. [&](size_t offset, size_t length, DataSink &sink) {
  6590. auto out_len = std::min(length, static_cast<size_t>(1024));
  6591. std::string out(out_len, '@');
  6592. sink.write(out.data(), out_len);
  6593. return offset < 4096;
  6594. },
  6595. [](bool success) { ASSERT_FALSE(success); });
  6596. });
  6597. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6598. res.set_content_provider(
  6599. 0, "text/plain",
  6600. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6601. EXPECT_TRUE(false);
  6602. return true;
  6603. },
  6604. [](bool success) { ASSERT_FALSE(success); });
  6605. });
  6606. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. listen_thread.join();
  6610. ASSERT_FALSE(svr.is_running());
  6611. });
  6612. svr.wait_until_ready();
  6613. Client cli("localhost", PORT);
  6614. {
  6615. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6616. size_t /*data_length*/) { return false; });
  6617. ASSERT_FALSE(res);
  6618. }
  6619. {
  6620. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6621. size_t /*data_length*/) { return false; });
  6622. ASSERT_TRUE(res);
  6623. }
  6624. }
  6625. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6626. Server svr;
  6627. svr.set_error_handler([](Request const &, Response &res) -> void {
  6628. res.set_chunked_content_provider(
  6629. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6630. sink.os << "hello";
  6631. sink.os << "world";
  6632. sink.done();
  6633. return true;
  6634. });
  6635. });
  6636. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6637. auto se = detail::scope_exit([&] {
  6638. svr.stop();
  6639. listen_thread.join();
  6640. ASSERT_FALSE(svr.is_running());
  6641. });
  6642. svr.wait_until_ready();
  6643. Client cli("localhost", PORT);
  6644. auto res = cli.Get("/");
  6645. ASSERT_TRUE(res);
  6646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6647. EXPECT_EQ("helloworld", res->body);
  6648. }
  6649. TEST(LongPollingTest, ClientCloseDetection) {
  6650. Server svr;
  6651. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6652. res.set_chunked_content_provider(
  6653. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6654. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6655. sink.os << "hello";
  6656. auto count = 10;
  6657. while (count > 0 && sink.is_writable()) {
  6658. this_thread::sleep_for(chrono::milliseconds(10));
  6659. count--;
  6660. }
  6661. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6662. return true;
  6663. });
  6664. });
  6665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6666. auto se = detail::scope_exit([&] {
  6667. svr.stop();
  6668. listen_thread.join();
  6669. ASSERT_FALSE(svr.is_running());
  6670. });
  6671. svr.wait_until_ready();
  6672. Client cli("localhost", PORT);
  6673. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6674. EXPECT_EQ("hello", string(data, data_length));
  6675. return false; // close the socket immediately.
  6676. });
  6677. ASSERT_FALSE(res);
  6678. }
  6679. TEST(GetWithParametersTest, GetWithParameters) {
  6680. Server svr;
  6681. svr.Get("/", [&](const Request &req, Response &) {
  6682. EXPECT_EQ("world", req.get_param_value("hello"));
  6683. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6684. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6685. });
  6686. svr.Get("/params", [&](const Request &req, Response &) {
  6687. EXPECT_EQ("world", req.get_param_value("hello"));
  6688. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6689. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6690. });
  6691. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6692. EXPECT_EQ("resource-id", req.matches[1]);
  6693. EXPECT_EQ("foo", req.get_param_value("param1"));
  6694. EXPECT_EQ("bar", req.get_param_value("param2"));
  6695. });
  6696. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6697. EXPECT_EQ("user-id", req.path_params.at("id"));
  6698. EXPECT_EQ("foo", req.get_param_value("param1"));
  6699. EXPECT_EQ("bar", req.get_param_value("param2"));
  6700. });
  6701. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6702. auto se = detail::scope_exit([&] {
  6703. svr.stop();
  6704. listen_thread.join();
  6705. ASSERT_FALSE(svr.is_running());
  6706. });
  6707. svr.wait_until_ready();
  6708. {
  6709. Client cli(HOST, PORT);
  6710. Params params;
  6711. params.emplace("hello", "world");
  6712. params.emplace("hello2", "world2");
  6713. params.emplace("hello3", "world3");
  6714. auto res = cli.Get("/", params, Headers{});
  6715. ASSERT_TRUE(res);
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. }
  6718. {
  6719. Client cli(HOST, PORT);
  6720. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6721. ASSERT_TRUE(res);
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. {
  6725. Client cli(HOST, PORT);
  6726. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6727. ASSERT_TRUE(res);
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. }
  6730. {
  6731. Client cli(HOST, PORT);
  6732. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6733. ASSERT_TRUE(res);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. }
  6737. TEST(GetWithParametersTest, GetWithParameters2) {
  6738. Server svr;
  6739. svr.Get("/", [&](const Request &req, Response &res) {
  6740. auto text = req.get_param_value("hello");
  6741. res.set_content(text, "text/plain");
  6742. });
  6743. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6744. auto se = detail::scope_exit([&] {
  6745. svr.stop();
  6746. listen_thread.join();
  6747. ASSERT_FALSE(svr.is_running());
  6748. });
  6749. svr.wait_until_ready();
  6750. Client cli("localhost", PORT);
  6751. Params params;
  6752. params.emplace("hello", "world");
  6753. std::string body;
  6754. auto res = cli.Get("/", params, Headers{},
  6755. [&](const char *data, size_t data_length) {
  6756. body.append(data, data_length);
  6757. return true;
  6758. });
  6759. ASSERT_TRUE(res);
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ("world", body);
  6762. }
  6763. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6764. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6765. auto host = "httpcan.org";
  6766. auto path = std::string{"/range/32"};
  6767. #else
  6768. auto host = "nghttp2.org";
  6769. auto path = std::string{"/httpbin/range/32"};
  6770. #endif
  6771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6772. SSLClient cli(host);
  6773. #else
  6774. Client cli(host);
  6775. #endif
  6776. cli.set_default_headers({make_range_header({{1, 10}})});
  6777. cli.set_connection_timeout(5);
  6778. {
  6779. auto res = cli.Get(path);
  6780. ASSERT_TRUE(res);
  6781. EXPECT_EQ("bcdefghijk", res->body);
  6782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6783. }
  6784. {
  6785. auto res = cli.Get(path);
  6786. ASSERT_TRUE(res);
  6787. EXPECT_EQ("bcdefghijk", res->body);
  6788. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6789. }
  6790. }
  6791. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6792. Server svr;
  6793. svr.set_default_headers({{"Hello", "World"}});
  6794. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6795. res.set_content("ok", "text/plain");
  6796. });
  6797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6798. auto se = detail::scope_exit([&] {
  6799. svr.stop();
  6800. listen_thread.join();
  6801. ASSERT_FALSE(svr.is_running());
  6802. });
  6803. svr.wait_until_ready();
  6804. Client cli("localhost", PORT);
  6805. auto res = cli.Get("/");
  6806. ASSERT_TRUE(res);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("ok", res->body);
  6809. EXPECT_EQ("World", res->get_header_value("Hello"));
  6810. }
  6811. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6812. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6814. ASSERT_TRUE(svr.is_valid());
  6815. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6816. std::this_thread::sleep_for(std::chrono::seconds(2));
  6817. res.set_content("a", "text/plain");
  6818. });
  6819. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6820. res.set_content("b", "text/plain");
  6821. });
  6822. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6823. auto se = detail::scope_exit([&] {
  6824. svr.stop();
  6825. listen_thread.join();
  6826. ASSERT_FALSE(svr.is_running());
  6827. });
  6828. svr.wait_until_ready();
  6829. SSLClient cli("localhost", PORT);
  6830. cli.enable_server_certificate_verification(false);
  6831. cli.set_keep_alive(true);
  6832. cli.set_read_timeout(std::chrono::seconds(1));
  6833. auto resa = cli.Get("/a");
  6834. ASSERT_TRUE(!resa);
  6835. EXPECT_EQ(Error::Read, resa.error());
  6836. auto resb = cli.Get("/b");
  6837. ASSERT_TRUE(resb);
  6838. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6839. EXPECT_EQ("b", resb->body);
  6840. }
  6841. #endif
  6842. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6843. protected:
  6844. ServerTestWithAI_PASSIVE()
  6845. : cli_(HOST, PORT)
  6846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6847. ,
  6848. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6849. #endif
  6850. {
  6851. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6852. cli_.enable_server_certificate_verification(false);
  6853. #endif
  6854. }
  6855. virtual void SetUp() {
  6856. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6857. res.set_content("Hello World!", "text/plain");
  6858. });
  6859. t_ = thread(
  6860. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6861. svr_.wait_until_ready();
  6862. }
  6863. virtual void TearDown() {
  6864. svr_.stop();
  6865. t_.join();
  6866. }
  6867. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6868. SSLClient cli_;
  6869. SSLServer svr_;
  6870. #else
  6871. Client cli_;
  6872. Server svr_;
  6873. #endif
  6874. thread t_;
  6875. };
  6876. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6877. auto res = cli_.Get("/hi");
  6878. ASSERT_TRUE(res);
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6881. EXPECT_EQ("Hello World!", res->body);
  6882. }
  6883. class ServerUpDownTest : public ::testing::Test {
  6884. protected:
  6885. ServerUpDownTest() : cli_(HOST, PORT) {}
  6886. virtual void SetUp() {
  6887. t_ = thread([&]() {
  6888. svr_.bind_to_any_port(HOST);
  6889. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6890. ASSERT_TRUE(svr_.listen_after_bind());
  6891. });
  6892. svr_.wait_until_ready();
  6893. }
  6894. virtual void TearDown() {
  6895. svr_.stop();
  6896. t_.join();
  6897. }
  6898. Client cli_;
  6899. Server svr_;
  6900. thread t_;
  6901. };
  6902. TEST_F(ServerUpDownTest, QuickStartStop) {
  6903. // Should not crash, especially when run with
  6904. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6905. }
  6906. class PayloadMaxLengthTest : public ::testing::Test {
  6907. protected:
  6908. PayloadMaxLengthTest()
  6909. : cli_(HOST, PORT)
  6910. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6911. ,
  6912. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6913. #endif
  6914. {
  6915. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6916. cli_.enable_server_certificate_verification(false);
  6917. #endif
  6918. }
  6919. virtual void SetUp() {
  6920. svr_.set_payload_max_length(8);
  6921. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6922. res.set_content("test", "text/plain");
  6923. });
  6924. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6925. svr_.wait_until_ready();
  6926. }
  6927. virtual void TearDown() {
  6928. svr_.stop();
  6929. t_.join();
  6930. }
  6931. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6932. SSLClient cli_;
  6933. SSLServer svr_;
  6934. #else
  6935. Client cli_;
  6936. Server svr_;
  6937. #endif
  6938. thread t_;
  6939. };
  6940. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6941. auto res = cli_.Post("/test", "123456789", "text/plain");
  6942. ASSERT_TRUE(res);
  6943. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6944. res = cli_.Post("/test", "12345678", "text/plain");
  6945. ASSERT_TRUE(res);
  6946. EXPECT_EQ(StatusCode::OK_200, res->status);
  6947. }
  6948. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6949. // Test chunked encoding with payload exceeding the 8-byte limit
  6950. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6951. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6952. ASSERT_TRUE(res);
  6953. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6954. }
  6955. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6956. // Test chunked encoding with payload within the 8-byte limit
  6957. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6958. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6959. ASSERT_TRUE(res);
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6963. // Test using send_request to send chunked data exceeding payload limit
  6964. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6965. "Host: " +
  6966. std::string(HOST) + ":" + std::to_string(PORT) +
  6967. "\r\n"
  6968. "Transfer-Encoding: chunked\r\n"
  6969. "Connection: close\r\n"
  6970. "\r\n"
  6971. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6972. "0123456789\r\n"
  6973. "0\r\n" // End chunk
  6974. "\r\n";
  6975. std::string response;
  6976. bool result = send_request(1, chunked_request, &response);
  6977. if (!result) {
  6978. // If send_request fails, it might be because the server closed the
  6979. // connection due to payload limit enforcement, which is acceptable
  6980. SUCCEED()
  6981. << "Server rejected oversized chunked request (connection closed)";
  6982. } else {
  6983. // If we got a response, check if it's an error response or connection was
  6984. // closed early Short response length indicates connection was closed due to
  6985. // payload limit
  6986. if (response.length() <= 10) {
  6987. SUCCEED() << "Server closed connection for oversized chunked request";
  6988. } else {
  6989. // Check for error status codes
  6990. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6991. response.find("Payload Too Large") != std::string::npos ||
  6992. response.find("400") != std::string::npos);
  6993. }
  6994. }
  6995. }
  6996. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6997. // Test request without Content-Length header exceeding payload limit
  6998. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6999. "Host: " +
  7000. std::string(HOST) + ":" +
  7001. std::to_string(PORT) +
  7002. "\r\n"
  7003. "Connection: close\r\n"
  7004. "\r\n";
  7005. // Add payload exceeding the 8-byte limit
  7006. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7007. request_without_content_length += large_payload;
  7008. std::string response;
  7009. bool result = send_request(1, request_without_content_length, &response);
  7010. if (!result) {
  7011. // If send_request fails, server likely closed connection due to payload
  7012. // limit
  7013. SUCCEED() << "Server rejected oversized request without Content-Length "
  7014. "(connection closed)";
  7015. } else {
  7016. // Check if server responded with error or closed connection early
  7017. if (response.length() <= 10) {
  7018. SUCCEED() << "Server closed connection for oversized request without "
  7019. "Content-Length";
  7020. } else {
  7021. // Check for error status codes
  7022. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7023. response.find("Payload Too Large") != std::string::npos ||
  7024. response.find("400") != std::string::npos);
  7025. }
  7026. }
  7027. }
  7028. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7029. // Test request without Content-Length header within payload limit
  7030. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7031. "Host: " +
  7032. std::string(HOST) + ":" +
  7033. std::to_string(PORT) +
  7034. "\r\n"
  7035. "Connection: close\r\n"
  7036. "\r\n";
  7037. // Add payload within the 8-byte limit
  7038. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7039. request_without_content_length += small_payload;
  7040. std::string response;
  7041. bool result = send_request(1, request_without_content_length, &response);
  7042. // For requests without Content-Length, the server may have different behavior
  7043. // The key is that it should not reject due to payload limit for small
  7044. // payloads
  7045. if (result) {
  7046. // Check for any HTTP response (success or error, but not connection closed)
  7047. if (response.length() > 10) {
  7048. SUCCEED()
  7049. << "Server processed request without Content-Length within limit";
  7050. } else {
  7051. // Short response might indicate connection closed, which is acceptable
  7052. SUCCEED() << "Server closed connection for request without "
  7053. "Content-Length (acceptable behavior)";
  7054. }
  7055. } else {
  7056. // Connection failure might be due to protocol requirements
  7057. SUCCEED() << "Connection issue with request without Content-Length "
  7058. "(environment-specific)";
  7059. }
  7060. }
  7061. class LargePayloadMaxLengthTest : public ::testing::Test {
  7062. protected:
  7063. LargePayloadMaxLengthTest()
  7064. : cli_(HOST, PORT)
  7065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7066. ,
  7067. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7068. #endif
  7069. {
  7070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7071. cli_.enable_server_certificate_verification(false);
  7072. #endif
  7073. }
  7074. virtual void SetUp() {
  7075. // Set 10MB payload limit
  7076. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7077. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7078. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7079. res.set_content("Large payload test", "text/plain");
  7080. });
  7081. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7082. svr_.wait_until_ready();
  7083. }
  7084. virtual void TearDown() {
  7085. svr_.stop();
  7086. t_.join();
  7087. }
  7088. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7089. SSLClient cli_;
  7090. SSLServer svr_;
  7091. #else
  7092. Client cli_;
  7093. Server svr_;
  7094. #endif
  7095. thread t_;
  7096. };
  7097. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7098. // Test chunked encoding with payload within 10MB limit
  7099. std::string medium_payload(5 * 1024 * 1024,
  7100. 'A'); // 5MB payload, within 10MB limit
  7101. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7102. ASSERT_TRUE(res);
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. }
  7105. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7106. // Test chunked encoding with payload exceeding 10MB limit
  7107. std::string large_payload(12 * 1024 * 1024,
  7108. 'B'); // 12MB payload, exceeds 10MB limit
  7109. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7110. ASSERT_TRUE(res);
  7111. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7112. }
  7113. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7114. // Test request without Content-Length header within 10MB limit
  7115. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7116. "Host: " +
  7117. std::string(HOST) + ":" +
  7118. std::to_string(PORT) +
  7119. "\r\n"
  7120. "Connection: close\r\n"
  7121. "\r\n";
  7122. // Add 1MB payload (within 10MB limit)
  7123. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7124. request_without_content_length += medium_payload;
  7125. std::string response;
  7126. bool result = send_request(5, request_without_content_length, &response);
  7127. if (result) {
  7128. // Should get a proper HTTP response for payloads within limit
  7129. if (response.length() > 10) {
  7130. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7131. "10MB limit";
  7132. } else {
  7133. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7134. "Content-Length)";
  7135. }
  7136. } else {
  7137. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7138. }
  7139. }
  7140. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7141. // Test request without Content-Length header exceeding 10MB limit
  7142. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7143. "Host: " +
  7144. std::string(HOST) + ":" +
  7145. std::to_string(PORT) +
  7146. "\r\n"
  7147. "Connection: close\r\n"
  7148. "\r\n";
  7149. // Add 12MB payload (exceeds 10MB limit)
  7150. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7151. request_without_content_length += large_payload;
  7152. std::string response;
  7153. bool result = send_request(10, request_without_content_length, &response);
  7154. if (!result) {
  7155. // Server should close connection due to payload limit
  7156. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7157. "(connection closed)";
  7158. } else {
  7159. // Check for error response
  7160. if (response.length() <= 10) {
  7161. SUCCEED()
  7162. << "Server closed connection for 12MB request exceeding 10MB limit";
  7163. } else {
  7164. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7165. response.find("Payload Too Large") != std::string::npos ||
  7166. response.find("400") != std::string::npos);
  7167. }
  7168. }
  7169. }
  7170. TEST(HostAndPortPropertiesTest, NoSSL) {
  7171. httplib::Client cli("www.google.com", 1234);
  7172. ASSERT_EQ("www.google.com", cli.host());
  7173. ASSERT_EQ(1234, cli.port());
  7174. }
  7175. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7176. httplib::Client cli("www.google.com:1234");
  7177. ASSERT_EQ("www.google.com", cli.host());
  7178. ASSERT_EQ(1234, cli.port());
  7179. }
  7180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7181. TEST(HostAndPortPropertiesTest, SSL) {
  7182. httplib::SSLClient cli("www.google.com");
  7183. ASSERT_EQ("www.google.com", cli.host());
  7184. ASSERT_EQ(443, cli.port());
  7185. }
  7186. #endif
  7187. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7188. TEST(SSLClientTest, UpdateCAStore) {
  7189. httplib::SSLClient httplib_client("www.google.com");
  7190. auto ca_store_1 = X509_STORE_new();
  7191. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7192. nullptr);
  7193. httplib_client.set_ca_cert_store(ca_store_1);
  7194. auto ca_store_2 = X509_STORE_new();
  7195. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7196. nullptr);
  7197. httplib_client.set_ca_cert_store(ca_store_2);
  7198. }
  7199. TEST(SSLClientTest, ServerNameIndication_Online) {
  7200. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7201. auto host = "httpcan.org";
  7202. auto path = std::string{"/get"};
  7203. #else
  7204. auto host = "nghttp2.org";
  7205. auto path = std::string{"/httpbin/get"};
  7206. #endif
  7207. SSLClient cli(host, 443);
  7208. auto res = cli.Get(path);
  7209. ASSERT_TRUE(res);
  7210. ASSERT_EQ(StatusCode::OK_200, res->status);
  7211. }
  7212. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7213. // Use a site that will cause SSL verification failure due to self-signed cert
  7214. SSLClient cli("self-signed.badssl.com", 443);
  7215. cli.enable_server_certificate_verification(true);
  7216. auto res = cli.Get("/");
  7217. ASSERT_TRUE(!res);
  7218. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7219. // For SSL server verification errors, ssl_error should be 0, only
  7220. // ssl_openssl_error should be set
  7221. EXPECT_EQ(0, res.ssl_error());
  7222. // Verify OpenSSL error is captured for SSLServerVerification
  7223. // This occurs when SSL_get_verify_result() returns a verification failure
  7224. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7225. res.ssl_openssl_error());
  7226. }
  7227. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7228. // Use a site where hostname doesn't match the certificate
  7229. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7230. SSLClient cli("wrong.host.badssl.com", 443);
  7231. cli.enable_server_certificate_verification(true);
  7232. cli.enable_server_hostname_verification(true);
  7233. auto res = cli.Get("/");
  7234. ASSERT_TRUE(!res);
  7235. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7236. // For SSL hostname verification errors, ssl_error should be 0, only
  7237. // ssl_openssl_error should be set
  7238. EXPECT_EQ(0, res.ssl_error());
  7239. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7240. // This occurs when verify_host() fails due to hostname mismatch
  7241. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7242. res.ssl_openssl_error());
  7243. }
  7244. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7245. Client cli("https://google.com");
  7246. auto res = cli.Get("/");
  7247. ASSERT_TRUE(res);
  7248. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7249. }
  7250. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7251. SSLClient cli("google.com");
  7252. cli.set_ca_cert_path(CA_CERT_FILE);
  7253. auto res = cli.Get("/");
  7254. ASSERT_TRUE(res);
  7255. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7256. }
  7257. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7258. SSLClient cli("google.com");
  7259. cli.enable_server_certificate_verification(true);
  7260. cli.set_ca_cert_path("hello");
  7261. auto res = cli.Get("/");
  7262. ASSERT_TRUE(!res);
  7263. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7264. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7265. // should be set
  7266. EXPECT_EQ(0, res.ssl_error());
  7267. // Verify OpenSSL error is captured for SSLLoadingCerts
  7268. // This error occurs when SSL_CTX_load_verify_locations() fails
  7269. // > openssl errstr 0x80000002
  7270. // error:80000002:system library::No such file or directory
  7271. // > openssl errstr 0xA000126
  7272. // error:0A000126:SSL routines::unexpected eof while reading
  7273. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7274. res.ssl_openssl_error() == 0xA000126);
  7275. }
  7276. TEST(SSLClientTest, ServerCertificateVerification4) {
  7277. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7278. ASSERT_TRUE(svr.is_valid());
  7279. svr.Get("/test", [&](const Request &, Response &res) {
  7280. res.set_content("test", "text/plain");
  7281. svr.stop();
  7282. ASSERT_TRUE(true);
  7283. });
  7284. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7285. auto se = detail::scope_exit([&] {
  7286. t.join();
  7287. ASSERT_FALSE(svr.is_running());
  7288. });
  7289. svr.wait_until_ready();
  7290. SSLClient cli("127.0.0.1", PORT);
  7291. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7292. cli.enable_server_certificate_verification(true);
  7293. cli.set_connection_timeout(30);
  7294. auto res = cli.Get("/test");
  7295. ASSERT_TRUE(res);
  7296. ASSERT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7299. std::string cert;
  7300. read_file(CA_CERT_FILE, cert);
  7301. SSLClient cli("google.com");
  7302. cli.load_ca_cert_store(cert.data(), cert.size());
  7303. const auto res = cli.Get("/");
  7304. ASSERT_TRUE(res);
  7305. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7306. }
  7307. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7308. // clang-format off
  7309. static constexpr char cert[] =
  7310. "GlobalSign Root CA\n"
  7311. "==================\n"
  7312. "-----BEGIN CERTIFICATE-----\n"
  7313. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7314. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7315. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7316. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7317. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7318. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7319. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7320. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7321. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7322. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7323. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7324. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7325. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7326. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7327. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7328. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7329. "-----END CERTIFICATE-----\n";
  7330. // clang-format on
  7331. SSLClient cli("google.com");
  7332. cli.load_ca_cert_store(cert, sizeof(cert));
  7333. const auto res = cli.Get("/");
  7334. ASSERT_TRUE(res);
  7335. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7336. }
  7337. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7338. SSLClient cli("www.youtube.com");
  7339. cli.set_ca_cert_path(CA_CERT_FILE);
  7340. cli.enable_server_certificate_verification(true);
  7341. cli.set_follow_location(true);
  7342. auto res = cli.Get("/");
  7343. ASSERT_TRUE(res);
  7344. ASSERT_EQ(StatusCode::OK_200, res->status);
  7345. }
  7346. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7347. SSLClient cli("wWw.YouTube.Com");
  7348. cli.set_ca_cert_path(CA_CERT_FILE);
  7349. cli.enable_server_certificate_verification(true);
  7350. cli.enable_server_hostname_verification(true);
  7351. cli.set_follow_location(true);
  7352. auto res = cli.Get("/");
  7353. ASSERT_TRUE(res);
  7354. ASSERT_EQ(StatusCode::OK_200, res->status);
  7355. }
  7356. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7357. SSLClient cli("gOoGlE.COm");
  7358. cli.enable_server_certificate_verification(true);
  7359. cli.enable_server_hostname_verification(true);
  7360. cli.set_follow_location(true);
  7361. auto res = cli.Get("/");
  7362. ASSERT_TRUE(res);
  7363. ASSERT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST(SSLClientTest, Issue2004_Online) {
  7366. Client client("https://google.com");
  7367. client.set_follow_location(true);
  7368. auto res = client.Get("/");
  7369. ASSERT_TRUE(res);
  7370. ASSERT_EQ(StatusCode::OK_200, res->status);
  7371. auto body = res->body;
  7372. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7373. }
  7374. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7375. // Create SSLClient with invalid cert/key to make is_valid() return false
  7376. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7377. "nonexistent_key.pem");
  7378. // is_valid() should be false due to cert loading failure
  7379. ASSERT_FALSE(cli.is_valid());
  7380. auto res = cli.Get("/");
  7381. ASSERT_FALSE(res);
  7382. EXPECT_EQ(Error::SSLConnection, res.error());
  7383. }
  7384. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7385. // Test for Issue #2251: SSL error not properly reported when client cert
  7386. // and key paths are swapped or mismatched
  7387. // This simulates the scenario where user accidentally swaps the cert and key
  7388. // files
  7389. // Using client cert file as private key and vice versa (completely wrong)
  7390. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7391. // Should fail validation due to cert/key mismatch
  7392. ASSERT_FALSE(cli.is_valid());
  7393. // Attempt to make a request should fail with proper error
  7394. auto res = cli.Get("/");
  7395. ASSERT_FALSE(res);
  7396. EXPECT_EQ(Error::SSLConnection, res.error());
  7397. // SSL error should be recorded in the Result object (this is the key fix for
  7398. // Issue #2251)
  7399. auto openssl_error = res.ssl_openssl_error();
  7400. EXPECT_NE(0u, openssl_error);
  7401. }
  7402. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7403. // Another variant: using valid file paths but with mismatched cert/key pair
  7404. // This tests the case where files exist but contain incompatible key material
  7405. // Using client cert with wrong key (cert2 key)
  7406. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7407. // Should fail validation
  7408. ASSERT_FALSE(cli.is_valid());
  7409. auto res = cli.Get("/");
  7410. ASSERT_FALSE(res);
  7411. // Must report error properly, not appear as success
  7412. EXPECT_EQ(Error::SSLConnection, res.error());
  7413. // OpenSSL error should be captured in Result
  7414. EXPECT_NE(0u, res.ssl_openssl_error());
  7415. }
  7416. #if 0
  7417. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7418. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7419. ASSERT_TRUE(cli != nullptr);
  7420. cli->set_address_family(AF_INET6);
  7421. cli->set_interface("en0");
  7422. auto res = cli->Get("/get");
  7423. ASSERT_TRUE(res);
  7424. ASSERT_EQ(StatusCode::OK_200, res->status);
  7425. }
  7426. #endif
  7427. void ClientCertPresent(
  7428. const std::string &client_cert_file,
  7429. const std::string &client_private_key_file,
  7430. const std::string &client_encrypted_private_key_pass = std::string()) {
  7431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7432. CLIENT_CA_CERT_DIR);
  7433. ASSERT_TRUE(svr.is_valid());
  7434. svr.Get("/test", [&](const Request &req, Response &res) {
  7435. res.set_content("test", "text/plain");
  7436. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7437. ASSERT_TRUE(peer_cert != nullptr);
  7438. auto subject_name = X509_get_subject_name(peer_cert);
  7439. ASSERT_TRUE(subject_name != nullptr);
  7440. std::string common_name;
  7441. {
  7442. char name[BUFSIZ];
  7443. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7444. name, sizeof(name));
  7445. common_name.assign(name, static_cast<size_t>(name_len));
  7446. }
  7447. EXPECT_EQ("Common Name", common_name);
  7448. X509_free(peer_cert);
  7449. });
  7450. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7451. auto se = detail::scope_exit([&] {
  7452. svr.stop();
  7453. t.join();
  7454. ASSERT_FALSE(svr.is_running());
  7455. });
  7456. svr.wait_until_ready();
  7457. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7458. client_encrypted_private_key_pass);
  7459. cli.enable_server_certificate_verification(false);
  7460. cli.set_connection_timeout(30);
  7461. auto res = cli.Get("/test");
  7462. ASSERT_TRUE(res);
  7463. ASSERT_EQ(StatusCode::OK_200, res->status);
  7464. }
  7465. TEST(SSLClientServerTest, ClientCertPresent) {
  7466. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7467. }
  7468. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7469. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7470. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7471. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7472. }
  7473. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7474. void MemoryClientCertPresent(
  7475. const std::string &client_cert_file,
  7476. const std::string &client_private_key_file,
  7477. const std::string &client_encrypted_private_key_pass = std::string()) {
  7478. auto f = fopen(SERVER_CERT_FILE, "r+");
  7479. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7480. fclose(f);
  7481. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7482. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7483. fclose(f);
  7484. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7485. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7486. auto client_ca_cert_store = X509_STORE_new();
  7487. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7488. X509_free(client_cert);
  7489. fclose(f);
  7490. f = fopen(client_cert_file.c_str(), "r+");
  7491. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7492. fclose(f);
  7493. f = fopen(client_private_key_file.c_str(), "r+");
  7494. auto client_private_key = PEM_read_PrivateKey(
  7495. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7496. fclose(f);
  7497. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7498. ASSERT_TRUE(svr.is_valid());
  7499. svr.Get("/test", [&](const Request &req, Response &res) {
  7500. res.set_content("test", "text/plain");
  7501. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7502. ASSERT_TRUE(peer_cert != nullptr);
  7503. auto subject_name = X509_get_subject_name(peer_cert);
  7504. ASSERT_TRUE(subject_name != nullptr);
  7505. std::string common_name;
  7506. {
  7507. char name[BUFSIZ];
  7508. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7509. name, sizeof(name));
  7510. common_name.assign(name, static_cast<size_t>(name_len));
  7511. }
  7512. EXPECT_EQ("Common Name", common_name);
  7513. X509_free(peer_cert);
  7514. });
  7515. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7516. auto se = detail::scope_exit([&] {
  7517. svr.stop();
  7518. t.join();
  7519. ASSERT_FALSE(svr.is_running());
  7520. });
  7521. svr.wait_until_ready();
  7522. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7523. client_encrypted_private_key_pass);
  7524. cli.enable_server_certificate_verification(false);
  7525. cli.set_connection_timeout(30);
  7526. auto res = cli.Get("/test");
  7527. ASSERT_TRUE(res);
  7528. ASSERT_EQ(StatusCode::OK_200, res->status);
  7529. X509_free(server_cert);
  7530. EVP_PKEY_free(server_private_key);
  7531. X509_free(client_cert);
  7532. EVP_PKEY_free(client_private_key);
  7533. }
  7534. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7535. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7536. }
  7537. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7538. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7539. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7540. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7541. }
  7542. #endif
  7543. TEST(SSLClientServerTest, ClientCertMissing) {
  7544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7545. CLIENT_CA_CERT_DIR);
  7546. ASSERT_TRUE(svr.is_valid());
  7547. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7548. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7549. auto se = detail::scope_exit([&] {
  7550. svr.stop();
  7551. t.join();
  7552. ASSERT_FALSE(svr.is_running());
  7553. });
  7554. svr.wait_until_ready();
  7555. SSLClient cli(HOST, PORT);
  7556. cli.set_connection_timeout(30);
  7557. auto res = cli.Get("/test");
  7558. ASSERT_TRUE(!res);
  7559. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7560. // For SSL server verification errors, ssl_error should be 0, only
  7561. // ssl_openssl_error should be set
  7562. EXPECT_EQ(0, res.ssl_error());
  7563. // Verify OpenSSL error is captured for SSLServerVerification
  7564. // Note: This test may have different error codes depending on the exact
  7565. // verification failure
  7566. EXPECT_NE(0UL, res.ssl_openssl_error());
  7567. }
  7568. TEST(SSLClientServerTest, TrustDirOptional) {
  7569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7570. ASSERT_TRUE(svr.is_valid());
  7571. svr.Get("/test", [&](const Request &, Response &res) {
  7572. res.set_content("test", "text/plain");
  7573. });
  7574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7575. auto se = detail::scope_exit([&] {
  7576. svr.stop();
  7577. t.join();
  7578. ASSERT_FALSE(svr.is_running());
  7579. });
  7580. svr.wait_until_ready();
  7581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7582. cli.enable_server_certificate_verification(false);
  7583. cli.set_connection_timeout(30);
  7584. auto res = cli.Get("/test");
  7585. ASSERT_TRUE(res);
  7586. ASSERT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7589. class NoListenSSLServer : public SSLServer {
  7590. public:
  7591. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7592. const char *client_ca_cert_file_path,
  7593. const char *client_ca_cert_dir_path = nullptr)
  7594. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7595. client_ca_cert_dir_path),
  7596. stop_(false) {}
  7597. std::atomic_bool stop_;
  7598. private:
  7599. bool process_and_close_socket(socket_t /*sock*/) override {
  7600. // Don't create SSL context
  7601. while (!stop_.load()) {
  7602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7603. }
  7604. return true;
  7605. }
  7606. };
  7607. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7608. CLIENT_CA_CERT_FILE);
  7609. ASSERT_TRUE(svr.is_valid());
  7610. svr.Get("/test", [&](const Request &, Response &res) {
  7611. res.set_content("test", "text/plain");
  7612. });
  7613. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7614. auto se = detail::scope_exit([&] {
  7615. svr.stop_ = true;
  7616. svr.stop();
  7617. t.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7622. cli.enable_server_certificate_verification(false);
  7623. cli.set_connection_timeout(1);
  7624. auto res = cli.Get("/test");
  7625. ASSERT_TRUE(!res);
  7626. EXPECT_EQ(Error::SSLConnection, res.error());
  7627. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7628. }
  7629. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7630. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7631. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7632. SSL_CTX_set_options(&ssl_ctx,
  7633. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7634. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7635. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7636. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7637. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7638. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7639. "ECDHE-DSS-AES128-SHA256:"
  7640. "ECDHE-RSA-AES256-SHA256:"
  7641. "ECDHE-DSS-AES256-SHA256:";
  7642. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7643. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7644. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7645. SSL_FILETYPE_PEM) != 1) {
  7646. return false;
  7647. }
  7648. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7649. CLIENT_CA_CERT_DIR);
  7650. SSL_CTX_set_verify(
  7651. &ssl_ctx,
  7652. SSL_VERIFY_PEER |
  7653. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7654. nullptr);
  7655. return true;
  7656. };
  7657. SSLServer svr(setup_ssl_ctx_callback);
  7658. ASSERT_TRUE(svr.is_valid());
  7659. svr.Get("/test", [&](const Request &req, Response &res) {
  7660. res.set_content("test", "text/plain");
  7661. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7662. ASSERT_TRUE(peer_cert != nullptr);
  7663. auto subject_name = X509_get_subject_name(peer_cert);
  7664. ASSERT_TRUE(subject_name != nullptr);
  7665. std::string common_name;
  7666. {
  7667. char name[BUFSIZ];
  7668. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7669. name, sizeof(name));
  7670. common_name.assign(name, static_cast<size_t>(name_len));
  7671. }
  7672. EXPECT_EQ("Common Name", common_name);
  7673. X509_free(peer_cert);
  7674. });
  7675. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7676. auto se = detail::scope_exit([&] {
  7677. svr.stop();
  7678. t.join();
  7679. ASSERT_FALSE(svr.is_running());
  7680. });
  7681. svr.wait_until_ready();
  7682. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7683. cli.enable_server_certificate_verification(false);
  7684. cli.set_connection_timeout(30);
  7685. auto res = cli.Get("/test");
  7686. ASSERT_TRUE(res);
  7687. ASSERT_EQ(StatusCode::OK_200, res->status);
  7688. }
  7689. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7691. ASSERT_TRUE(svr.is_valid());
  7692. // Set up a handler to verify client certificate is present
  7693. bool client_cert_verified = false;
  7694. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7695. // Verify that client certificate was provided
  7696. client_cert_verified = true;
  7697. res.set_content("success", "text/plain");
  7698. });
  7699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7700. auto se = detail::scope_exit([&] {
  7701. svr.stop();
  7702. t.join();
  7703. ASSERT_FALSE(svr.is_running());
  7704. });
  7705. svr.wait_until_ready();
  7706. // Client with certificate
  7707. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7708. cli.enable_server_certificate_verification(false);
  7709. cli.set_connection_timeout(30);
  7710. auto res = cli.Get("/test");
  7711. ASSERT_TRUE(res);
  7712. ASSERT_EQ(StatusCode::OK_200, res->status);
  7713. ASSERT_TRUE(client_cert_verified);
  7714. EXPECT_EQ("success", res->body);
  7715. }
  7716. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7717. // Test that when client CA cert file is provided,
  7718. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7719. // Create a server with client authentication
  7720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7721. ASSERT_TRUE(svr.is_valid());
  7722. // We can't directly access the SSL_CTX from SSLServer to verify,
  7723. // but we can test that the server properly requests client certificates
  7724. // and accepts valid ones from the specified CA
  7725. bool handler_called = false;
  7726. svr.Get("/test", [&](const Request &req, Response &res) {
  7727. handler_called = true;
  7728. // Verify that a client certificate was provided
  7729. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7730. ASSERT_TRUE(peer_cert != nullptr);
  7731. // Get the issuer name
  7732. auto issuer_name = X509_get_issuer_name(peer_cert);
  7733. ASSERT_TRUE(issuer_name != nullptr);
  7734. char issuer_buf[256];
  7735. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7736. // The client certificate should be issued by our test CA
  7737. std::string issuer_str(issuer_buf);
  7738. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7739. X509_free(peer_cert);
  7740. res.set_content("authenticated", "text/plain");
  7741. });
  7742. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. t.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. // Connect with a client certificate issued by the CA
  7750. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7751. cli.enable_server_certificate_verification(false);
  7752. cli.set_connection_timeout(30);
  7753. auto res = cli.Get("/test");
  7754. ASSERT_TRUE(res);
  7755. ASSERT_EQ(StatusCode::OK_200, res->status);
  7756. ASSERT_TRUE(handler_called);
  7757. EXPECT_EQ("authenticated", res->body);
  7758. }
  7759. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7760. // Test 1: Valid CA file - no error should be recorded
  7761. {
  7762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7763. CLIENT_CA_CERT_FILE);
  7764. ASSERT_TRUE(svr.is_valid());
  7765. // With valid setup, last_ssl_error should be 0
  7766. EXPECT_EQ(0, svr.ssl_last_error());
  7767. }
  7768. // Test 2: Invalid CA file content
  7769. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7770. {
  7771. // Create a temporary file with completely invalid content
  7772. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7773. {
  7774. std::ofstream ofs(temp_invalid_ca);
  7775. ofs << "This is not a certificate file at all\n";
  7776. ofs << "Just plain text content\n";
  7777. }
  7778. // Create server with invalid CA file
  7779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7780. // Clean up temporary file
  7781. std::remove(temp_invalid_ca);
  7782. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7783. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7784. // Note: SSL_CTX_load_verify_locations typically fails first,
  7785. // but our error handling code path is still exercised
  7786. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7787. }
  7788. }
  7789. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7790. // Test SSL server using X509_STORE constructor with client CA certificates
  7791. // This test verifies that Phase 2 implementation correctly extracts CA names
  7792. // from an X509_STORE and sets them in the SSL context
  7793. // Load the CA certificate into memory
  7794. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7795. ASSERT_NE(nullptr, bio);
  7796. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7797. BIO_free(bio);
  7798. ASSERT_NE(nullptr, ca_cert);
  7799. // Create an X509_STORE and add the CA certificate
  7800. auto store = X509_STORE_new();
  7801. ASSERT_NE(nullptr, store);
  7802. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7803. // Load server certificate and private key
  7804. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7805. ASSERT_NE(nullptr, cert_bio);
  7806. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7807. BIO_free(cert_bio);
  7808. ASSERT_NE(nullptr, server_cert);
  7809. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7810. ASSERT_NE(nullptr, key_bio);
  7811. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7812. BIO_free(key_bio);
  7813. ASSERT_NE(nullptr, server_key);
  7814. // Create SSLServer with X509_STORE constructor
  7815. // Note: X509_STORE ownership is transferred to SSL_CTX
  7816. SSLServer svr(server_cert, server_key, store);
  7817. ASSERT_TRUE(svr.is_valid());
  7818. // No SSL error should be recorded for valid setup
  7819. EXPECT_EQ(0, svr.ssl_last_error());
  7820. // Set up server endpoints
  7821. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7822. res.set_content("ok", "text/plain");
  7823. });
  7824. // Start server in a thread
  7825. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7826. svr.wait_until_ready();
  7827. // Connect with client certificate (using constructor with paths)
  7828. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7829. cli.enable_server_certificate_verification(false);
  7830. auto res = cli.Get("/test-x509store");
  7831. ASSERT_TRUE(res);
  7832. EXPECT_EQ(200, res->status);
  7833. EXPECT_EQ("ok", res->body);
  7834. // Clean up
  7835. X509_free(server_cert);
  7836. EVP_PKEY_free(server_key);
  7837. X509_free(ca_cert);
  7838. svr.stop();
  7839. server_thread.join();
  7840. }
  7841. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7842. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7843. // prepare large data
  7844. std::random_device seed_gen;
  7845. std::mt19937 random(seed_gen());
  7846. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7847. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7848. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7849. // server
  7850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7851. ASSERT_TRUE(svr.is_valid());
  7852. svr.Post("/binary", [&](const Request &req, Response &res) {
  7853. EXPECT_EQ(large_size_byte, req.body.size());
  7854. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7855. res.set_content(req.body, "application/octet-stream");
  7856. });
  7857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7858. auto se = detail::scope_exit([&] {
  7859. svr.stop();
  7860. listen_thread.join();
  7861. ASSERT_FALSE(svr.is_running());
  7862. });
  7863. svr.wait_until_ready();
  7864. // client POST
  7865. SSLClient cli("localhost", PORT);
  7866. cli.enable_server_certificate_verification(false);
  7867. cli.set_read_timeout(std::chrono::seconds(100));
  7868. cli.set_write_timeout(std::chrono::seconds(100));
  7869. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7870. large_size_byte, "application/octet-stream");
  7871. // compare
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_EQ(large_size_byte, res->body.size());
  7874. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7875. }
  7876. #endif
  7877. #ifdef _WIN32
  7878. TEST(CleanupTest, WSACleanup) {
  7879. int ret = WSACleanup();
  7880. ASSERT_EQ(0, ret);
  7881. }
  7882. #endif
  7883. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7884. TEST(NoSSLSupport, SimpleInterface) {
  7885. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7886. }
  7887. #endif
  7888. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7889. TEST(InvalidScheme, SimpleInterface) {
  7890. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7891. }
  7892. #endif
  7893. TEST(NoScheme, SimpleInterface) {
  7894. Client cli("yahoo.com:80");
  7895. ASSERT_TRUE(cli.is_valid());
  7896. }
  7897. TEST(SendAPI, SimpleInterface_Online) {
  7898. Client cli("http://yahoo.com");
  7899. Request req;
  7900. req.method = "GET";
  7901. req.path = "/";
  7902. auto res = cli.send(req);
  7903. ASSERT_TRUE(res);
  7904. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7905. }
  7906. TEST(SendAPI, WithParamsInRequest) {
  7907. Server svr;
  7908. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7909. EXPECT_TRUE(req.has_param("test"));
  7910. EXPECT_EQ("test_value", req.get_param_value("test"));
  7911. });
  7912. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7913. auto se = detail::scope_exit([&] {
  7914. svr.stop();
  7915. t.join();
  7916. ASSERT_FALSE(svr.is_running());
  7917. });
  7918. svr.wait_until_ready();
  7919. Client cli(HOST, PORT);
  7920. {
  7921. Request req;
  7922. req.method = "GET";
  7923. req.path = "/";
  7924. req.params.emplace("test", "test_value");
  7925. auto res = cli.send(req);
  7926. ASSERT_TRUE(res);
  7927. }
  7928. {
  7929. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7930. ASSERT_TRUE(res);
  7931. }
  7932. }
  7933. TEST(ClientImplMethods, GetSocketTest) {
  7934. httplib::Server svr;
  7935. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7936. res.status = StatusCode::OK_200;
  7937. });
  7938. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7939. auto se = detail::scope_exit([&] {
  7940. svr.stop();
  7941. thread.join();
  7942. ASSERT_FALSE(svr.is_running());
  7943. });
  7944. svr.wait_until_ready();
  7945. {
  7946. httplib::Client cli("http://127.0.0.1:3333");
  7947. cli.set_keep_alive(true);
  7948. // Use the behavior of cpp-httplib of opening the connection
  7949. // only when the first request happens. If that changes,
  7950. // this test would be obsolete.
  7951. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7952. // This also implicitly tests the server. But other tests would fail much
  7953. // earlier than this one to be considered.
  7954. auto res = cli.Get("/");
  7955. ASSERT_TRUE(res);
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7958. }
  7959. }
  7960. // Disabled due to out-of-memory problem on GitHub Actions
  7961. #ifdef _WIN64
  7962. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7963. // allocate content size larger than 2GB in memory
  7964. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7965. char *content = (char *)malloc(content_size);
  7966. ASSERT_TRUE(content);
  7967. Server svr;
  7968. svr.Get("/foo",
  7969. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7970. res.set_content(content, content_size, "application/octet-stream");
  7971. });
  7972. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7973. auto se = detail::scope_exit([&] {
  7974. svr.stop();
  7975. listen_thread.join();
  7976. if (content) free(content);
  7977. ASSERT_FALSE(svr.is_running());
  7978. });
  7979. svr.wait_until_ready();
  7980. Client cli(HOST, PORT);
  7981. auto res = cli.Get("/foo");
  7982. ASSERT_TRUE(res);
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. EXPECT_EQ(content_size, res->body.length());
  7985. }
  7986. #endif
  7987. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7988. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7989. Client cli("http://yahoo.com");
  7990. auto res = cli.Get("/");
  7991. ASSERT_TRUE(res);
  7992. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7993. cli.set_follow_location(true);
  7994. res = cli.Get("/");
  7995. ASSERT_TRUE(res);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7998. }
  7999. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8000. Client cli("https://yahoo.com");
  8001. auto res = cli.Get("/");
  8002. ASSERT_TRUE(res);
  8003. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8004. cli.set_follow_location(true);
  8005. res = cli.Get("/");
  8006. ASSERT_TRUE(res);
  8007. EXPECT_EQ(StatusCode::OK_200, res->status);
  8008. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8009. }
  8010. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8011. Client cli("https://yahoo.com");
  8012. auto res = cli.Get("/");
  8013. ASSERT_TRUE(res);
  8014. ASSERT_FALSE(!res);
  8015. ASSERT_TRUE(res);
  8016. ASSERT_FALSE(res == nullptr);
  8017. ASSERT_TRUE(res != nullptr);
  8018. EXPECT_EQ(Error::Success, res.error());
  8019. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8020. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8021. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8022. cli.set_follow_location(true);
  8023. res = cli.Get("/");
  8024. ASSERT_TRUE(res);
  8025. EXPECT_EQ(Error::Success, res.error());
  8026. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8027. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8030. }
  8031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8032. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8033. Client cli("https://cdnjs.cloudflare.com");
  8034. auto res =
  8035. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8036. ASSERT_TRUE(res);
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. EXPECT_EQ(287630U, res->body.size());
  8039. EXPECT_EQ("application/javascript; charset=utf-8",
  8040. res->get_header_value("Content-Type"));
  8041. }
  8042. #endif
  8043. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8044. #undef REDIR_HOST // Silence compiler warning
  8045. #define REDIR_HOST "https://httpbingo.org"
  8046. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8047. Client cli(REDIR_HOST);
  8048. cli.set_follow_location(true);
  8049. auto res =
  8050. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8051. ASSERT_TRUE(res);
  8052. EXPECT_EQ(StatusCode::OK_200, res->status);
  8053. }
  8054. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8055. Client cli(REDIR_HOST);
  8056. cli.set_follow_location(true);
  8057. Params params;
  8058. params.emplace("url", "http://example.com");
  8059. params.emplace("status_code", "302");
  8060. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8061. ASSERT_TRUE(res);
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. }
  8064. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8065. Client cli(REDIR_HOST);
  8066. cli.set_follow_location(true);
  8067. Params params;
  8068. params.emplace("url", "http://example.com");
  8069. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8070. ASSERT_TRUE(res);
  8071. EXPECT_EQ(StatusCode::OK_200, res->status);
  8072. }
  8073. TEST(HttpToHttpsRedirectTest, CertFile) {
  8074. Server svr;
  8075. ASSERT_TRUE(svr.is_valid());
  8076. svr.Get("/index", [&](const Request &, Response &res) {
  8077. res.set_redirect("https://127.0.0.1:1235/index");
  8078. svr.stop();
  8079. });
  8080. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8081. ASSERT_TRUE(ssl_svr.is_valid());
  8082. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8083. res.set_content("test", "text/plain");
  8084. ssl_svr.stop();
  8085. });
  8086. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8087. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8088. auto se = detail::scope_exit([&] {
  8089. t2.join();
  8090. t.join();
  8091. ASSERT_FALSE(svr.is_running());
  8092. });
  8093. svr.wait_until_ready();
  8094. ssl_svr.wait_until_ready();
  8095. Client cli("127.0.0.1", PORT);
  8096. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8097. cli.enable_server_certificate_verification(true);
  8098. cli.set_follow_location(true);
  8099. cli.set_connection_timeout(30);
  8100. auto res = cli.Get("/index");
  8101. ASSERT_TRUE(res);
  8102. ASSERT_EQ(StatusCode::OK_200, res->status);
  8103. }
  8104. TEST(SSLClientRedirectTest, CertFile) {
  8105. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8106. ASSERT_TRUE(ssl_svr1.is_valid());
  8107. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8108. res.set_redirect("https://127.0.0.1:1235/index");
  8109. ssl_svr1.stop();
  8110. });
  8111. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8112. ASSERT_TRUE(ssl_svr2.is_valid());
  8113. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8114. res.set_content("test", "text/plain");
  8115. ssl_svr2.stop();
  8116. });
  8117. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8118. thread t2 =
  8119. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8120. auto se = detail::scope_exit([&] {
  8121. t2.join();
  8122. t.join();
  8123. ASSERT_FALSE(ssl_svr1.is_running());
  8124. });
  8125. ssl_svr1.wait_until_ready();
  8126. ssl_svr2.wait_until_ready();
  8127. SSLClient cli("127.0.0.1", PORT);
  8128. std::string cert;
  8129. read_file(SERVER_CERT2_FILE, cert);
  8130. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8131. cli.enable_server_certificate_verification(true);
  8132. cli.set_follow_location(true);
  8133. cli.set_connection_timeout(30);
  8134. auto res = cli.Get("/index");
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::OK_200, res->status);
  8137. }
  8138. // Test that set_ca_cert_store() skips system certs (consistent with
  8139. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8140. // should be trusted - system certs should NOT be loaded.
  8141. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8142. // Load a specific cert that is NOT a system CA cert
  8143. std::string cert;
  8144. read_file(SERVER_CERT2_FILE, cert);
  8145. SSLClient cli("google.com");
  8146. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8147. cli.enable_server_certificate_verification(true);
  8148. // This should FAIL because:
  8149. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8150. // 2. System certs should NOT be loaded when custom store is set
  8151. // If system certs WERE loaded, this would succeed
  8152. auto res = cli.Get("/");
  8153. ASSERT_FALSE(res);
  8154. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8155. }
  8156. TEST(MultipartFormDataTest, LargeData) {
  8157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8158. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8159. const ContentReader &content_reader) {
  8160. if (req.is_multipart_form_data()) {
  8161. std::vector<FormData> items;
  8162. content_reader(
  8163. [&](const FormData &file) {
  8164. items.push_back(file);
  8165. return true;
  8166. },
  8167. [&](const char *data, size_t data_length) {
  8168. items.back().content.append(data, data_length);
  8169. return true;
  8170. });
  8171. EXPECT_TRUE(std::string(items[0].name) == "document");
  8172. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8173. EXPECT_TRUE(items[0].filename == "2MB_data");
  8174. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8175. EXPECT_TRUE(items[1].name == "hello");
  8176. EXPECT_TRUE(items[1].content == "world");
  8177. EXPECT_TRUE(items[1].filename == "");
  8178. EXPECT_TRUE(items[1].content_type == "");
  8179. } else {
  8180. std::string body;
  8181. content_reader([&](const char *data, size_t data_length) {
  8182. body.append(data, data_length);
  8183. return true;
  8184. });
  8185. }
  8186. });
  8187. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8188. auto se = detail::scope_exit([&] {
  8189. svr.stop();
  8190. t.join();
  8191. ASSERT_FALSE(svr.is_running());
  8192. });
  8193. svr.wait_until_ready();
  8194. {
  8195. std::string data(1024 * 1024 * 2, '.');
  8196. std::stringstream buffer;
  8197. buffer << data;
  8198. Client cli("https://localhost:8080");
  8199. cli.enable_server_certificate_verification(false);
  8200. UploadFormDataItems items{
  8201. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8202. {"hello", "world", "", ""},
  8203. };
  8204. auto res = cli.Post("/post", items);
  8205. ASSERT_TRUE(res);
  8206. ASSERT_EQ(StatusCode::OK_200, res->status);
  8207. }
  8208. }
  8209. TEST(MultipartFormDataTest, DataProviderItems) {
  8210. std::random_device seed_gen;
  8211. std::mt19937 random(seed_gen());
  8212. std::string rand1;
  8213. rand1.resize(1000);
  8214. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8215. std::string rand2;
  8216. rand2.resize(3000);
  8217. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8219. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8220. const ContentReader &content_reader) {
  8221. ASSERT_FALSE(req.is_multipart_form_data());
  8222. std::string body;
  8223. content_reader([&](const char *data, size_t data_length) {
  8224. body.append(data, data_length);
  8225. return true;
  8226. });
  8227. EXPECT_EQ(body, "");
  8228. });
  8229. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8230. const ContentReader &content_reader) {
  8231. ASSERT_TRUE(req.is_multipart_form_data());
  8232. std::vector<FormData> items;
  8233. content_reader(
  8234. [&](const FormData &file) {
  8235. items.push_back(file);
  8236. return true;
  8237. },
  8238. [&](const char *data, size_t data_length) {
  8239. items.back().content.append(data, data_length);
  8240. return true;
  8241. });
  8242. ASSERT_TRUE(items.size() == 2);
  8243. EXPECT_EQ(std::string(items[0].name), "name1");
  8244. EXPECT_EQ(items[0].content, "Testing123");
  8245. EXPECT_EQ(items[0].filename, "filename1");
  8246. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8247. EXPECT_EQ(items[1].name, "name2");
  8248. EXPECT_EQ(items[1].content, "Testing456");
  8249. EXPECT_EQ(items[1].filename, "");
  8250. EXPECT_EQ(items[1].content_type, "");
  8251. });
  8252. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8253. const ContentReader &content_reader) {
  8254. ASSERT_TRUE(req.is_multipart_form_data());
  8255. std::vector<FormData> items;
  8256. content_reader(
  8257. [&](const FormData &file) {
  8258. items.push_back(file);
  8259. return true;
  8260. },
  8261. [&](const char *data, size_t data_length) {
  8262. items.back().content.append(data, data_length);
  8263. return true;
  8264. });
  8265. ASSERT_TRUE(items.size() == 2);
  8266. EXPECT_EQ(items[0].name, "name3");
  8267. EXPECT_EQ(items[0].content, rand1);
  8268. EXPECT_EQ(items[0].filename, "filename3");
  8269. EXPECT_EQ(items[0].content_type, "");
  8270. EXPECT_EQ(items[1].name, "name4");
  8271. EXPECT_EQ(items[1].content, rand2);
  8272. EXPECT_EQ(items[1].filename, "filename4");
  8273. EXPECT_EQ(items[1].content_type, "");
  8274. });
  8275. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8276. const ContentReader &content_reader) {
  8277. ASSERT_TRUE(req.is_multipart_form_data());
  8278. std::vector<FormData> items;
  8279. content_reader(
  8280. [&](const FormData &file) {
  8281. items.push_back(file);
  8282. return true;
  8283. },
  8284. [&](const char *data, size_t data_length) {
  8285. items.back().content.append(data, data_length);
  8286. return true;
  8287. });
  8288. ASSERT_TRUE(items.size() == 4);
  8289. EXPECT_EQ(std::string(items[0].name), "name1");
  8290. EXPECT_EQ(items[0].content, "Testing123");
  8291. EXPECT_EQ(items[0].filename, "filename1");
  8292. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8293. EXPECT_EQ(items[1].name, "name2");
  8294. EXPECT_EQ(items[1].content, "Testing456");
  8295. EXPECT_EQ(items[1].filename, "");
  8296. EXPECT_EQ(items[1].content_type, "");
  8297. EXPECT_EQ(items[2].name, "name3");
  8298. EXPECT_EQ(items[2].content, rand1);
  8299. EXPECT_EQ(items[2].filename, "filename3");
  8300. EXPECT_EQ(items[2].content_type, "");
  8301. EXPECT_EQ(items[3].name, "name4");
  8302. EXPECT_EQ(items[3].content, rand2);
  8303. EXPECT_EQ(items[3].filename, "filename4");
  8304. EXPECT_EQ(items[3].content_type, "");
  8305. });
  8306. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8307. auto se = detail::scope_exit([&] {
  8308. svr.stop();
  8309. t.join();
  8310. ASSERT_FALSE(svr.is_running());
  8311. });
  8312. svr.wait_until_ready();
  8313. {
  8314. Client cli("https://localhost:8080");
  8315. cli.enable_server_certificate_verification(false);
  8316. UploadFormDataItems items{
  8317. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8318. {"name2", "Testing456", "", ""}, // not a file
  8319. };
  8320. {
  8321. auto res = cli.Post("/post-none", {}, {}, {});
  8322. ASSERT_TRUE(res);
  8323. ASSERT_EQ(StatusCode::OK_200, res->status);
  8324. }
  8325. FormDataProviderItems providers;
  8326. {
  8327. auto res =
  8328. cli.Post("/post-items", {}, items, providers); // empty providers
  8329. ASSERT_TRUE(res);
  8330. ASSERT_EQ(StatusCode::OK_200, res->status);
  8331. }
  8332. providers.push_back({"name3",
  8333. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8334. // test the offset is given correctly at each step
  8335. if (!offset)
  8336. sink.os.write(rand1.data(), 30);
  8337. else if (offset == 30)
  8338. sink.os.write(rand1.data() + 30, 300);
  8339. else if (offset == 330)
  8340. sink.os.write(rand1.data() + 330, 670);
  8341. else if (offset == rand1.size())
  8342. sink.done();
  8343. return true;
  8344. },
  8345. "filename3",
  8346. {}});
  8347. providers.push_back({"name4",
  8348. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8349. // test the offset is given correctly at each step
  8350. if (!offset)
  8351. sink.os.write(rand2.data(), 2000);
  8352. else if (offset == 2000)
  8353. sink.os.write(rand2.data() + 2000, 1);
  8354. else if (offset == 2001)
  8355. sink.os.write(rand2.data() + 2001, 999);
  8356. else if (offset == rand2.size())
  8357. sink.done();
  8358. return true;
  8359. },
  8360. "filename4",
  8361. {}});
  8362. {
  8363. auto res = cli.Post("/post-providers", {}, {}, providers);
  8364. ASSERT_TRUE(res);
  8365. ASSERT_EQ(StatusCode::OK_200, res->status);
  8366. }
  8367. {
  8368. auto res = cli.Post("/post-both", {}, items, providers);
  8369. ASSERT_TRUE(res);
  8370. ASSERT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. }
  8373. }
  8374. TEST(MultipartFormDataTest, BadHeader) {
  8375. Server svr;
  8376. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8377. res.set_content("ok", "text/plain");
  8378. });
  8379. thread t = thread([&] { svr.listen(HOST, PORT); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. t.join();
  8383. ASSERT_FALSE(svr.is_running());
  8384. });
  8385. svr.wait_until_ready();
  8386. const std::string body =
  8387. "This is the preamble. It is to be ignored, though it\r\n"
  8388. "is a handy place for composition agents to include an\r\n"
  8389. "explanatory note to non-MIME conformant readers.\r\n"
  8390. "\r\n"
  8391. "\r\n"
  8392. "--simple boundary\r\n"
  8393. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8394. ": BAD...\r\n"
  8395. "\r\n"
  8396. "value1\r\n"
  8397. "--simple boundary\r\n"
  8398. "Content-Disposition: form-data; name=\"field2\"; "
  8399. "filename=\"example.txt\"\r\n"
  8400. "\r\n"
  8401. "value2\r\n"
  8402. "--simple boundary--\r\n"
  8403. "This is the epilogue. It is also to be ignored.\r\n";
  8404. std::string content_type =
  8405. R"(multipart/form-data; boundary="simple boundary")";
  8406. Client cli(HOST, PORT);
  8407. auto res = cli.Post("/post", body, content_type.c_str());
  8408. ASSERT_TRUE(res);
  8409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8410. }
  8411. TEST(MultipartFormDataTest, WithPreamble) {
  8412. Server svr;
  8413. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8414. res.set_content("ok", "text/plain");
  8415. });
  8416. thread t = thread([&] { svr.listen(HOST, PORT); });
  8417. auto se = detail::scope_exit([&] {
  8418. svr.stop();
  8419. t.join();
  8420. ASSERT_FALSE(svr.is_running());
  8421. });
  8422. svr.wait_until_ready();
  8423. const std::string body =
  8424. "This is the preamble. It is to be ignored, though it\r\n"
  8425. "is a handy place for composition agents to include an\r\n"
  8426. "explanatory note to non-MIME conformant readers.\r\n"
  8427. "\r\n"
  8428. "\r\n"
  8429. "--simple boundary\r\n"
  8430. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8431. "\r\n"
  8432. "value1\r\n"
  8433. "--simple boundary\r\n"
  8434. "Content-Disposition: form-data; name=\"field2\"; "
  8435. "filename=\"example.txt\"\r\n"
  8436. "\r\n"
  8437. "value2\r\n"
  8438. "--simple boundary--\r\n"
  8439. "This is the epilogue. It is also to be ignored.\r\n";
  8440. std::string content_type =
  8441. R"(multipart/form-data; boundary="simple boundary")";
  8442. Client cli(HOST, PORT);
  8443. auto res = cli.Post("/post", body, content_type.c_str());
  8444. ASSERT_TRUE(res);
  8445. EXPECT_EQ(StatusCode::OK_200, res->status);
  8446. }
  8447. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8449. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8450. const ContentReader &content_reader) {
  8451. if (req.is_multipart_form_data()) {
  8452. std::vector<FormData> items;
  8453. content_reader(
  8454. [&](const FormData &file) {
  8455. items.push_back(file);
  8456. return true;
  8457. },
  8458. [&](const char *data, size_t data_length) {
  8459. items.back().content.append(data, data_length);
  8460. return true;
  8461. });
  8462. EXPECT_TRUE(std::string(items[0].name) == "document");
  8463. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8464. EXPECT_TRUE(items[0].filename == "2MB_data");
  8465. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8466. EXPECT_TRUE(items[1].name == "hello");
  8467. EXPECT_TRUE(items[1].content == "world");
  8468. EXPECT_TRUE(items[1].filename == "");
  8469. EXPECT_TRUE(items[1].content_type == "");
  8470. } else {
  8471. std::string body;
  8472. content_reader([&](const char *data, size_t data_length) {
  8473. body.append(data, data_length);
  8474. return true;
  8475. });
  8476. }
  8477. });
  8478. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. {
  8486. std::string data(1024 * 1024 * 2, '.');
  8487. std::stringstream buffer;
  8488. buffer << data;
  8489. Client cli("https://localhost:8080");
  8490. cli.enable_server_certificate_verification(false);
  8491. UploadFormDataItems items{
  8492. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8493. {"hello", "world", "", ""},
  8494. };
  8495. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8496. ASSERT_TRUE(res);
  8497. ASSERT_EQ(StatusCode::OK_200, res->status);
  8498. }
  8499. }
  8500. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8501. std::string data(1024 * 1024 * 2, '&');
  8502. std::stringstream buffer;
  8503. buffer << data;
  8504. Client cli("https://localhost:8080");
  8505. UploadFormDataItems items{
  8506. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8507. {"hello", "world", "", ""},
  8508. };
  8509. for (const char &c : " \t\r\n") {
  8510. auto res =
  8511. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8512. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8513. ASSERT_FALSE(res);
  8514. }
  8515. }
  8516. TEST(MultipartFormDataTest, PutFormData) {
  8517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8518. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8519. const ContentReader &content_reader) {
  8520. if (req.is_multipart_form_data()) {
  8521. std::vector<FormData> items;
  8522. content_reader(
  8523. [&](const FormData &file) {
  8524. items.push_back(file);
  8525. return true;
  8526. },
  8527. [&](const char *data, size_t data_length) {
  8528. items.back().content.append(data, data_length);
  8529. return true;
  8530. });
  8531. EXPECT_TRUE(std::string(items[0].name) == "document");
  8532. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8533. EXPECT_TRUE(items[0].filename == "2MB_data");
  8534. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8535. EXPECT_TRUE(items[1].name == "hello");
  8536. EXPECT_TRUE(items[1].content == "world");
  8537. EXPECT_TRUE(items[1].filename == "");
  8538. EXPECT_TRUE(items[1].content_type == "");
  8539. } else {
  8540. std::string body;
  8541. content_reader([&](const char *data, size_t data_length) {
  8542. body.append(data, data_length);
  8543. return true;
  8544. });
  8545. }
  8546. });
  8547. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8548. auto se = detail::scope_exit([&] {
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. });
  8553. svr.wait_until_ready();
  8554. {
  8555. std::string data(1024 * 1024 * 2, '&');
  8556. std::stringstream buffer;
  8557. buffer << data;
  8558. Client cli("https://localhost:8080");
  8559. cli.enable_server_certificate_verification(false);
  8560. UploadFormDataItems items{
  8561. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8562. {"hello", "world", "", ""},
  8563. };
  8564. auto res = cli.Put("/put", items);
  8565. ASSERT_TRUE(res);
  8566. ASSERT_EQ(StatusCode::OK_200, res->status);
  8567. }
  8568. }
  8569. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8571. svr.Put("/put_customboundary",
  8572. [&](const Request &req, const Response & /*res*/,
  8573. const ContentReader &content_reader) {
  8574. if (req.is_multipart_form_data()) {
  8575. std::vector<FormData> items;
  8576. content_reader(
  8577. [&](const FormData &file) {
  8578. items.push_back(file);
  8579. return true;
  8580. },
  8581. [&](const char *data, size_t data_length) {
  8582. items.back().content.append(data, data_length);
  8583. return true;
  8584. });
  8585. EXPECT_TRUE(std::string(items[0].name) == "document");
  8586. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8587. EXPECT_TRUE(items[0].filename == "2MB_data");
  8588. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8589. EXPECT_TRUE(items[1].name == "hello");
  8590. EXPECT_TRUE(items[1].content == "world");
  8591. EXPECT_TRUE(items[1].filename == "");
  8592. EXPECT_TRUE(items[1].content_type == "");
  8593. } else {
  8594. std::string body;
  8595. content_reader([&](const char *data, size_t data_length) {
  8596. body.append(data, data_length);
  8597. return true;
  8598. });
  8599. }
  8600. });
  8601. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8602. auto se = detail::scope_exit([&] {
  8603. svr.stop();
  8604. t.join();
  8605. ASSERT_FALSE(svr.is_running());
  8606. });
  8607. svr.wait_until_ready();
  8608. {
  8609. std::string data(1024 * 1024 * 2, '&');
  8610. std::stringstream buffer;
  8611. buffer << data;
  8612. Client cli("https://localhost:8080");
  8613. cli.enable_server_certificate_verification(false);
  8614. UploadFormDataItems items{
  8615. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8616. {"hello", "world", "", ""},
  8617. };
  8618. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8619. ASSERT_TRUE(res);
  8620. ASSERT_EQ(StatusCode::OK_200, res->status);
  8621. }
  8622. }
  8623. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8624. std::string data(1024 * 1024 * 2, '&');
  8625. std::stringstream buffer;
  8626. buffer << data;
  8627. Client cli("https://localhost:8080");
  8628. cli.enable_server_certificate_verification(false);
  8629. UploadFormDataItems items{
  8630. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8631. {"hello", "world", "", ""},
  8632. };
  8633. for (const char &c : " \t\r\n") {
  8634. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8635. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8636. ASSERT_FALSE(res);
  8637. }
  8638. }
  8639. TEST(MultipartFormDataTest, AlternateFilename) {
  8640. auto handled = false;
  8641. Server svr;
  8642. svr.Post("/test", [&](const Request &req, Response &res) {
  8643. ASSERT_EQ(2u, req.form.files.size());
  8644. ASSERT_EQ(1u, req.form.fields.size());
  8645. // Test files
  8646. const auto &file1 = req.form.get_file("file1");
  8647. ASSERT_EQ("file1", file1.name);
  8648. ASSERT_EQ("A.txt", file1.filename);
  8649. ASSERT_EQ("text/plain", file1.content_type);
  8650. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8651. const auto &file2 = req.form.get_file("file2");
  8652. ASSERT_EQ("file2", file2.name);
  8653. ASSERT_EQ("a.html", file2.filename);
  8654. ASSERT_EQ("text/html", file2.content_type);
  8655. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8656. file2.content);
  8657. // Test text field
  8658. const auto &text = req.form.get_field("text");
  8659. ASSERT_EQ("text default", text);
  8660. res.set_content("ok", "text/plain");
  8661. handled = true;
  8662. });
  8663. thread t = thread([&] { svr.listen(HOST, PORT); });
  8664. auto se = detail::scope_exit([&] {
  8665. svr.stop();
  8666. t.join();
  8667. ASSERT_FALSE(svr.is_running());
  8668. ASSERT_TRUE(handled);
  8669. });
  8670. svr.wait_until_ready();
  8671. auto req = "POST /test HTTP/1.1\r\n"
  8672. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8673. "Content-Length: 399\r\n"
  8674. "\r\n"
  8675. "----------\r\n"
  8676. "Content-Disposition: form-data; name=\"text\"\r\n"
  8677. "\r\n"
  8678. "text default\r\n"
  8679. "----------\r\n"
  8680. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8681. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8682. "Content-Type: text/plain\r\n"
  8683. "\r\n"
  8684. "Content of a.txt.\r\n"
  8685. "\r\n"
  8686. "----------\r\n"
  8687. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8688. "\"a.html\"\r\n"
  8689. "Content-Type: text/html\r\n"
  8690. "\r\n"
  8691. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8692. "\r\n"
  8693. "------------\r\n";
  8694. ASSERT_TRUE(send_request(1, req));
  8695. }
  8696. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8697. auto handled = false;
  8698. Server svr;
  8699. svr.Post("/test", [&](const Request &req, Response &) {
  8700. ASSERT_EQ(2u, req.form.fields.size());
  8701. const auto &text1 = req.form.get_field("text1");
  8702. ASSERT_EQ("text1", text1);
  8703. const auto &text2 = req.form.get_field("text2");
  8704. ASSERT_EQ("text2", text2);
  8705. handled = true;
  8706. });
  8707. thread t = thread([&] { svr.listen(HOST, PORT); });
  8708. auto se = detail::scope_exit([&] {
  8709. svr.stop();
  8710. t.join();
  8711. ASSERT_FALSE(svr.is_running());
  8712. ASSERT_TRUE(handled);
  8713. });
  8714. svr.wait_until_ready();
  8715. auto req = "POST /test HTTP/1.1\r\n"
  8716. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8717. "Content-Length: 146\r\n"
  8718. "\r\n----------\r\n"
  8719. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8720. "\r\n"
  8721. "text1"
  8722. "\r\n----------\r\n"
  8723. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8724. "\r\n"
  8725. "text2"
  8726. "\r\n------------";
  8727. std::string response;
  8728. ASSERT_TRUE(send_request(1, req, &response));
  8729. ASSERT_EQ("200", response.substr(9, 3));
  8730. }
  8731. TEST(MultipartFormDataTest, ContentLength) {
  8732. auto handled = false;
  8733. Server svr;
  8734. svr.Post("/test", [&](const Request &req, Response &) {
  8735. ASSERT_EQ(2u, req.form.fields.size());
  8736. const auto &text1 = req.form.get_field("text1");
  8737. ASSERT_EQ("text1", text1);
  8738. const auto &text2 = req.form.get_field("text2");
  8739. ASSERT_EQ("text2", text2);
  8740. handled = true;
  8741. });
  8742. thread t = thread([&] { svr.listen(HOST, PORT); });
  8743. auto se = detail::scope_exit([&] {
  8744. svr.stop();
  8745. t.join();
  8746. ASSERT_FALSE(svr.is_running());
  8747. ASSERT_TRUE(handled);
  8748. });
  8749. svr.wait_until_ready();
  8750. auto req = "POST /test HTTP/1.1\r\n"
  8751. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8752. "Content-Length: 167\r\n"
  8753. "\r\n----------\r\n"
  8754. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8755. "Content-Length: 5\r\n"
  8756. "\r\n"
  8757. "text1"
  8758. "\r\n----------\r\n"
  8759. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8760. "\r\n"
  8761. "text2"
  8762. "\r\n------------\r\n";
  8763. std::string response;
  8764. ASSERT_TRUE(send_request(1, req, &response));
  8765. ASSERT_EQ("200", response.substr(9, 3));
  8766. }
  8767. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8768. auto handled = false;
  8769. Server svr;
  8770. svr.Post("/test", [&](const Request &req, Response &) {
  8771. ASSERT_EQ(2u, req.form.fields.size());
  8772. const auto &text1 = req.form.get_field("text1");
  8773. ASSERT_EQ("text1", text1);
  8774. // TODO: Add header access for text fields if needed
  8775. const auto &text2 = req.form.get_field("text2");
  8776. ASSERT_EQ("text2", text2);
  8777. // TODO: Header access for text fields needs to be implemented
  8778. // auto &headers = it->second.headers;
  8779. // ASSERT_EQ(3U, headers.size());
  8780. // auto custom_header = headers.find("x-whatever");
  8781. // ASSERT_TRUE(custom_header != headers.end());
  8782. // ASSERT_NE("customvalue", custom_header->second);
  8783. // ASSERT_EQ("CustomValue", custom_header->second);
  8784. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8785. handled = true;
  8786. });
  8787. thread t = thread([&] { svr.listen(HOST, PORT); });
  8788. auto se = detail::scope_exit([&] {
  8789. svr.stop();
  8790. t.join();
  8791. ASSERT_FALSE(svr.is_running());
  8792. ASSERT_TRUE(handled);
  8793. });
  8794. svr.wait_until_ready();
  8795. auto req = "POST /test HTTP/1.1\r\n"
  8796. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8797. "Content-Length: 232\r\n"
  8798. "\r\n----------\r\n"
  8799. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8800. "Content-Length: 5\r\n"
  8801. "X-Test: 1\r\n"
  8802. "\r\n"
  8803. "text1"
  8804. "\r\n----------\r\n"
  8805. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8806. "Content-Type: text/plain\r\n"
  8807. "X-Whatever: CustomValue\r\n"
  8808. "\r\n"
  8809. "text2"
  8810. "\r\n------------\r\n"
  8811. "That should be disregarded. Not even read";
  8812. std::string response;
  8813. ASSERT_TRUE(send_request(1, req, &response));
  8814. ASSERT_EQ("200", response.substr(9, 3));
  8815. }
  8816. #endif
  8817. TEST(MultipartFormDataTest, LargeHeader) {
  8818. auto handled = false;
  8819. Server svr;
  8820. svr.Post("/test", [&](const Request &req, Response &) {
  8821. ASSERT_EQ(1u, req.form.fields.size());
  8822. const auto &text = req.form.get_field("name1");
  8823. ASSERT_EQ("text1", text);
  8824. handled = true;
  8825. });
  8826. thread t = thread([&] { svr.listen(HOST, PORT); });
  8827. auto se = detail::scope_exit([&] {
  8828. svr.stop();
  8829. t.join();
  8830. ASSERT_FALSE(svr.is_running());
  8831. ASSERT_TRUE(handled);
  8832. });
  8833. svr.wait_until_ready();
  8834. auto boundary = std::string("cpp-httplib-multipart-data");
  8835. std::string content = "--" + boundary +
  8836. "\r\n"
  8837. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8838. "\r\n"
  8839. "text1\r\n"
  8840. "--" +
  8841. boundary + "--\r\n";
  8842. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8843. "Content-Type: multipart/form-data;boundary=" +
  8844. boundary +
  8845. "\r\n"
  8846. "Content-Length: " +
  8847. std::to_string(content.size()) +
  8848. "\r\n"
  8849. "Dummy-Header: ";
  8850. std::string header_suffix = "\r\n"
  8851. "\r\n";
  8852. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8853. size_t header_dummy_size =
  8854. read_buff_size -
  8855. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8856. auto header_dummy = std::string(header_dummy_size, '@');
  8857. auto req = header_prefix + header_dummy + header_suffix + content;
  8858. std::string response;
  8859. ASSERT_TRUE(send_request(1, req, &response));
  8860. ASSERT_EQ("200", response.substr(9, 3));
  8861. }
  8862. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8863. static constexpr unsigned int number_of_tasks{1000000};
  8864. std::atomic_uint count{0};
  8865. std::unique_ptr<TaskQueue> task_queue{
  8866. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8867. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8868. auto queued = task_queue->enqueue(
  8869. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8870. EXPECT_TRUE(queued);
  8871. }
  8872. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8873. task_queue->shutdown();
  8874. #else
  8875. EXPECT_NO_THROW(task_queue->shutdown());
  8876. #endif
  8877. EXPECT_EQ(number_of_tasks, count.load());
  8878. }
  8879. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8880. static constexpr unsigned int number_of_tasks{1000000};
  8881. static constexpr unsigned int qlimit{2};
  8882. unsigned int queued_count{0};
  8883. std::atomic_uint count{0};
  8884. std::unique_ptr<TaskQueue> task_queue{
  8885. new ThreadPool{/*num_threads=*/1, qlimit}};
  8886. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8887. if (task_queue->enqueue(
  8888. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8889. queued_count++;
  8890. }
  8891. }
  8892. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8893. task_queue->shutdown();
  8894. #else
  8895. EXPECT_NO_THROW(task_queue->shutdown());
  8896. #endif
  8897. EXPECT_EQ(queued_count, count.load());
  8898. EXPECT_TRUE(queued_count <= number_of_tasks);
  8899. EXPECT_TRUE(queued_count >= qlimit);
  8900. }
  8901. TEST(TaskQueueTest, MaxQueuedRequests) {
  8902. static constexpr unsigned int qlimit{3};
  8903. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8904. std::condition_variable sem_cv;
  8905. std::mutex sem_mtx;
  8906. int credits = 0;
  8907. bool queued;
  8908. /* Fill up the queue with tasks that will block until we give them credits to
  8909. * complete. */
  8910. for (unsigned int n = 0; n <= qlimit;) {
  8911. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8912. std::unique_lock<std::mutex> lock(sem_mtx);
  8913. while (credits <= 0) {
  8914. sem_cv.wait(lock);
  8915. }
  8916. /* Consume the credit and signal the test code if they are all gone. */
  8917. if (--credits == 0) { sem_cv.notify_one(); }
  8918. });
  8919. if (n < qlimit) {
  8920. /* The first qlimit enqueues must succeed. */
  8921. EXPECT_TRUE(queued);
  8922. } else {
  8923. /* The last one will succeed only when the worker thread
  8924. * starts and dequeues the first blocking task. Although
  8925. * not necessary for the correctness of this test, we sleep for
  8926. * a short while to avoid busy waiting. */
  8927. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8928. }
  8929. if (queued) { n++; }
  8930. }
  8931. /* Further enqueues must fail since the queue is full. */
  8932. for (auto i = 0; i < 4; i++) {
  8933. queued = task_queue->enqueue([] {});
  8934. EXPECT_FALSE(queued);
  8935. }
  8936. /* Give the credits to allow the previous tasks to complete. */
  8937. {
  8938. std::unique_lock<std::mutex> lock(sem_mtx);
  8939. credits += qlimit + 1;
  8940. }
  8941. sem_cv.notify_all();
  8942. /* Wait for all the credits to be consumed. */
  8943. {
  8944. std::unique_lock<std::mutex> lock(sem_mtx);
  8945. while (credits > 0) {
  8946. sem_cv.wait(lock);
  8947. }
  8948. }
  8949. /* Check that we are able again to enqueue at least qlimit tasks. */
  8950. for (unsigned int i = 0; i < qlimit; i++) {
  8951. queued = task_queue->enqueue([] {});
  8952. EXPECT_TRUE(queued);
  8953. }
  8954. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8955. task_queue->shutdown();
  8956. #else
  8957. EXPECT_NO_THROW(task_queue->shutdown());
  8958. #endif
  8959. }
  8960. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8961. Server svr;
  8962. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8963. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8964. });
  8965. svr.Get("/hello", [](const Request &req, Response &res) {
  8966. res.set_content(req.get_param_value("key"), "text/plain");
  8967. });
  8968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8969. auto se = detail::scope_exit([&] {
  8970. svr.stop();
  8971. thread.join();
  8972. ASSERT_FALSE(svr.is_running());
  8973. });
  8974. svr.wait_until_ready();
  8975. {
  8976. Client cli(HOST, PORT);
  8977. cli.set_follow_location(true);
  8978. auto res = cli.Get("/");
  8979. ASSERT_TRUE(res);
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. EXPECT_EQ("val&key2=val2", res->body);
  8982. }
  8983. }
  8984. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8985. Server svr;
  8986. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8987. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8988. });
  8989. svr.Get("/hello", [](const Request &req, Response &res) {
  8990. res.set_content(req.get_param_value("key"), "text/plain");
  8991. });
  8992. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8993. auto se = detail::scope_exit([&] {
  8994. svr.stop();
  8995. thread.join();
  8996. ASSERT_FALSE(svr.is_running());
  8997. });
  8998. svr.wait_until_ready();
  8999. {
  9000. Client cli(HOST, PORT);
  9001. cli.set_follow_location(true);
  9002. auto res = cli.Get("/");
  9003. ASSERT_TRUE(res);
  9004. EXPECT_EQ(StatusCode::OK_200, res->status);
  9005. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9006. }
  9007. }
  9008. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9009. TEST(RedirectTest, Issue2185_Online) {
  9010. SSLClient client("github.com");
  9011. client.set_follow_location(true);
  9012. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9013. "Coollab-Windows.zip");
  9014. ASSERT_TRUE(res);
  9015. EXPECT_EQ(StatusCode::OK_200, res->status);
  9016. EXPECT_EQ(9920427U, res->body.size());
  9017. }
  9018. #endif
  9019. TEST(VulnerabilityTest, CRLFInjection) {
  9020. Server svr;
  9021. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9022. res.set_content("Hello 1", "text/plain");
  9023. });
  9024. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9025. res.set_content("Hello 2", "text/plain");
  9026. });
  9027. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9028. res.set_content("Hello 3", "text/plain");
  9029. });
  9030. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9031. res.set_content("Hello 4", "text/plain");
  9032. });
  9033. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9034. for (const auto &x : req.headers) {
  9035. auto key = x.first;
  9036. EXPECT_STRNE("evil", key.c_str());
  9037. }
  9038. });
  9039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9040. auto se = detail::scope_exit([&] {
  9041. svr.stop();
  9042. thread.join();
  9043. ASSERT_FALSE(svr.is_running());
  9044. });
  9045. svr.wait_until_ready();
  9046. {
  9047. Client cli(HOST, PORT);
  9048. cli.Post("/test1", "A=B",
  9049. "application/x-www-form-urlencoded\r\nevil: hello1");
  9050. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9051. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9052. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9053. }
  9054. }
  9055. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9056. auto server_thread = std::thread([] {
  9057. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9058. default_socket_options(srv);
  9059. sockaddr_in addr{};
  9060. addr.sin_family = AF_INET;
  9061. addr.sin_port = htons(PORT + 1);
  9062. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9063. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9064. ::listen(srv, 1);
  9065. sockaddr_in cli_addr{};
  9066. socklen_t cli_len = sizeof(cli_addr);
  9067. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9068. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9069. std::string buf_all;
  9070. char buf[2048];
  9071. ssize_t n;
  9072. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9073. buf_all.append(buf, static_cast<size_t>(n));
  9074. size_t pos;
  9075. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9076. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9077. auto e = request_block.find("\r\n");
  9078. if (e != std::string::npos) {
  9079. auto request_line = request_block.substr(0, e);
  9080. std::string msg =
  9081. "CRLF injection detected in request line: '" + request_line + "'";
  9082. EXPECT_FALSE(true) << msg;
  9083. }
  9084. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9085. ::send(cli,
  9086. #ifdef _WIN32
  9087. static_cast<const char *>(resp.c_str()),
  9088. static_cast<int>(resp.size()),
  9089. #else
  9090. resp.c_str(), resp.size(),
  9091. #endif
  9092. 0);
  9093. buf_all.erase(0, pos + 4);
  9094. }
  9095. }
  9096. detail::close_socket(cli);
  9097. detail::close_socket(srv);
  9098. });
  9099. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9100. auto cli = Client("127.0.0.1", PORT + 1);
  9101. auto headers = Headers{
  9102. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9103. {"Connection", "keep-alive"}};
  9104. auto res = cli.Get("/hi", headers);
  9105. EXPECT_FALSE(res);
  9106. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9107. server_thread.join();
  9108. }
  9109. TEST(PathParamsTest, StaticMatch) {
  9110. const auto pattern = "/users/all";
  9111. detail::PathParamsMatcher matcher(pattern);
  9112. Request request;
  9113. request.path = "/users/all";
  9114. ASSERT_TRUE(matcher.match(request));
  9115. std::unordered_map<std::string, std::string> expected_params = {};
  9116. EXPECT_EQ(request.path_params, expected_params);
  9117. }
  9118. TEST(PathParamsTest, StaticMismatch) {
  9119. const auto pattern = "/users/all";
  9120. detail::PathParamsMatcher matcher(pattern);
  9121. Request request;
  9122. request.path = "/users/1";
  9123. ASSERT_FALSE(matcher.match(request));
  9124. }
  9125. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9126. const auto pattern = "/users/:id/subscriptions";
  9127. detail::PathParamsMatcher matcher(pattern);
  9128. Request request;
  9129. request.path = "/users/42/subscriptions";
  9130. ASSERT_TRUE(matcher.match(request));
  9131. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9132. EXPECT_EQ(request.path_params, expected_params);
  9133. }
  9134. TEST(PathParamsTest, SingleParamInTheEnd) {
  9135. const auto pattern = "/users/:id";
  9136. detail::PathParamsMatcher matcher(pattern);
  9137. Request request;
  9138. request.path = "/users/24";
  9139. ASSERT_TRUE(matcher.match(request));
  9140. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9141. EXPECT_EQ(request.path_params, expected_params);
  9142. }
  9143. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9144. const auto pattern = "/users/:id/";
  9145. detail::PathParamsMatcher matcher(pattern);
  9146. Request request;
  9147. request.path = "/users/42/";
  9148. ASSERT_TRUE(matcher.match(request));
  9149. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9150. EXPECT_EQ(request.path_params, expected_params);
  9151. }
  9152. TEST(PathParamsTest, EmptyParam) {
  9153. const auto pattern = "/users/:id/";
  9154. detail::PathParamsMatcher matcher(pattern);
  9155. Request request;
  9156. request.path = "/users//";
  9157. ASSERT_TRUE(matcher.match(request));
  9158. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9159. EXPECT_EQ(request.path_params, expected_params);
  9160. }
  9161. TEST(PathParamsTest, FragmentMismatch) {
  9162. const auto pattern = "/users/:id/";
  9163. detail::PathParamsMatcher matcher(pattern);
  9164. Request request;
  9165. request.path = "/admins/24/";
  9166. ASSERT_FALSE(matcher.match(request));
  9167. }
  9168. TEST(PathParamsTest, ExtraFragments) {
  9169. const auto pattern = "/users/:id";
  9170. detail::PathParamsMatcher matcher(pattern);
  9171. Request request;
  9172. request.path = "/users/42/subscriptions";
  9173. ASSERT_FALSE(matcher.match(request));
  9174. }
  9175. TEST(PathParamsTest, MissingTrailingParam) {
  9176. const auto pattern = "/users/:id";
  9177. detail::PathParamsMatcher matcher(pattern);
  9178. Request request;
  9179. request.path = "/users";
  9180. ASSERT_FALSE(matcher.match(request));
  9181. }
  9182. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9183. const auto pattern = "/users/:id/subscriptions";
  9184. detail::PathParamsMatcher matcher(pattern);
  9185. Request request;
  9186. request.path = "/users/subscriptions";
  9187. ASSERT_FALSE(matcher.match(request));
  9188. }
  9189. TEST(PathParamsTest, MultipleParams) {
  9190. const auto pattern = "/users/:userid/subscriptions/:subid";
  9191. detail::PathParamsMatcher matcher(pattern);
  9192. Request request;
  9193. request.path = "/users/42/subscriptions/2";
  9194. ASSERT_TRUE(matcher.match(request));
  9195. std::unordered_map<std::string, std::string> expected_params = {
  9196. {"userid", "42"}, {"subid", "2"}};
  9197. EXPECT_EQ(request.path_params, expected_params);
  9198. }
  9199. TEST(PathParamsTest, SequenceOfParams) {
  9200. const auto pattern = "/values/:x/:y/:z";
  9201. detail::PathParamsMatcher matcher(pattern);
  9202. Request request;
  9203. request.path = "/values/1/2/3";
  9204. ASSERT_TRUE(matcher.match(request));
  9205. std::unordered_map<std::string, std::string> expected_params = {
  9206. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9207. EXPECT_EQ(request.path_params, expected_params);
  9208. }
  9209. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9210. const auto pattern = "/prefix:suffix";
  9211. detail::PathParamsMatcher matcher(pattern);
  9212. Request request;
  9213. request.path = "/prefix:suffix";
  9214. ASSERT_TRUE(matcher.match(request));
  9215. const std::unordered_map<std::string, std::string> expected_params = {};
  9216. EXPECT_EQ(request.path_params, expected_params);
  9217. }
  9218. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9219. // If ipv6 regex working, regex match codepath is taken.
  9220. // else port will default to 80 in Client impl
  9221. int clientImplMagicPort = 80;
  9222. int port = 4321;
  9223. // above ports must be different to avoid false negative
  9224. EXPECT_NE(clientImplMagicPort, port);
  9225. std::string ipV6TestURL = "http://[ff06::c3]";
  9226. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9227. CLIENT_PRIVATE_KEY_FILE);
  9228. EXPECT_EQ(cli.port(), port);
  9229. }
  9230. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9231. auto file_path = "./www/dir/index.html";
  9232. auto dir_path = "./www/dir";
  9233. detail::FileStat stat_file(file_path);
  9234. EXPECT_TRUE(stat_file.is_file());
  9235. EXPECT_FALSE(stat_file.is_dir());
  9236. detail::FileStat stat_dir(dir_path);
  9237. EXPECT_FALSE(stat_dir.is_file());
  9238. EXPECT_TRUE(stat_dir.is_dir());
  9239. }
  9240. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9241. // IPv4 with default HTTP port (80)
  9242. EXPECT_EQ("example.com",
  9243. detail::make_host_and_port_string("example.com", 80, false));
  9244. // IPv4 with default HTTPS port (443)
  9245. EXPECT_EQ("example.com",
  9246. detail::make_host_and_port_string("example.com", 443, true));
  9247. // IPv4 with non-default HTTP port
  9248. EXPECT_EQ("example.com:8080",
  9249. detail::make_host_and_port_string("example.com", 8080, false));
  9250. // IPv4 with non-default HTTPS port
  9251. EXPECT_EQ("example.com:8443",
  9252. detail::make_host_and_port_string("example.com", 8443, true));
  9253. // IPv6 with default HTTP port (80)
  9254. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9255. // IPv6 with default HTTPS port (443)
  9256. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9257. // IPv6 with non-default HTTP port
  9258. EXPECT_EQ("[::1]:8080",
  9259. detail::make_host_and_port_string("::1", 8080, false));
  9260. // IPv6 with non-default HTTPS port
  9261. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9262. // IPv6 full address with default port
  9263. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9264. detail::make_host_and_port_string(
  9265. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9266. // IPv6 full address with non-default port
  9267. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9268. detail::make_host_and_port_string(
  9269. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9270. // IPv6 localhost with non-default port
  9271. EXPECT_EQ("[::1]:3000",
  9272. detail::make_host_and_port_string("::1", 3000, false));
  9273. // IPv6 with zone ID (link-local address) with default port
  9274. EXPECT_EQ("[fe80::1%eth0]",
  9275. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9276. // IPv6 with zone ID (link-local address) with non-default port
  9277. EXPECT_EQ("[fe80::1%eth0]:8080",
  9278. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9279. // Edge case: Port 443 with is_ssl=false (should add port)
  9280. EXPECT_EQ("example.com:443",
  9281. detail::make_host_and_port_string("example.com", 443, false));
  9282. // Edge case: Port 80 with is_ssl=true (should add port)
  9283. EXPECT_EQ("example.com:80",
  9284. detail::make_host_and_port_string("example.com", 80, true));
  9285. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9286. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9287. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9288. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9289. // Security fix: Already bracketed IPv6 should not get double brackets
  9290. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9291. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9292. EXPECT_EQ("[::1]:8080",
  9293. detail::make_host_and_port_string("[::1]", 8080, false));
  9294. EXPECT_EQ("[2001:db8::1]:8080",
  9295. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9296. EXPECT_EQ("[fe80::1%eth0]",
  9297. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9298. EXPECT_EQ("[fe80::1%eth0]:8080",
  9299. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9300. // Edge case: Empty host (should return as-is)
  9301. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9302. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9303. // This is a known limitation but shouldn't crash
  9304. EXPECT_EQ("[host:name]",
  9305. detail::make_host_and_port_string("host:name", 80, false));
  9306. // Port number edge cases (no validation, but should not crash)
  9307. EXPECT_EQ("example.com:0",
  9308. detail::make_host_and_port_string("example.com", 0, false));
  9309. EXPECT_EQ("example.com:-1",
  9310. detail::make_host_and_port_string("example.com", -1, false));
  9311. EXPECT_EQ("example.com:65535",
  9312. detail::make_host_and_port_string("example.com", 65535, false));
  9313. EXPECT_EQ("example.com:65536",
  9314. detail::make_host_and_port_string("example.com", 65536, false));
  9315. }
  9316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9317. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9318. httplib::SSLClient cli("roblox.com", 443);
  9319. cli.set_follow_location(true);
  9320. auto res = cli.Get("/");
  9321. ASSERT_TRUE(res);
  9322. EXPECT_EQ(StatusCode::OK_200, res->status);
  9323. }
  9324. #endif
  9325. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9326. Server svr;
  9327. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9328. EXPECT_EQ(res.status, 400);
  9329. });
  9330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9331. auto se = detail::scope_exit([&] {
  9332. svr.stop();
  9333. thread.join();
  9334. ASSERT_FALSE(svr.is_running());
  9335. });
  9336. svr.wait_until_ready();
  9337. Client cli(HOST, PORT);
  9338. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9339. }
  9340. TEST(InvalidHeaderCharsTest, is_field_name) {
  9341. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9342. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9343. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9344. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9345. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9346. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9347. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9348. EXPECT_FALSE(detail::fields::is_field_name(""));
  9349. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9350. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9351. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9352. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9353. }
  9354. TEST(InvalidHeaderCharsTest, is_field_value) {
  9355. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9356. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9357. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9358. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9359. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9360. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9361. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9362. EXPECT_TRUE(detail::fields::is_field_value(""));
  9363. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9364. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9365. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9366. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9367. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9368. }
  9369. TEST(InvalidHeaderCharsTest, OnServer) {
  9370. Server svr;
  9371. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9372. std::string header = "Not Set";
  9373. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9374. res.set_header(header, "value");
  9375. res.set_content("Page Content Page Content", "text/plain");
  9376. });
  9377. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9378. std::string header = "Not Set";
  9379. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9380. res.set_header("X-Test", header);
  9381. res.set_content("Page Content Page Content", "text/plain");
  9382. });
  9383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9384. auto se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. thread.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. Client cli(HOST, PORT);
  9391. {
  9392. auto res = cli.Get(
  9393. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9394. ASSERT_TRUE(res);
  9395. EXPECT_EQ("Page Content Page Content", res->body);
  9396. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9397. }
  9398. {
  9399. auto res = cli.Get(
  9400. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9401. ASSERT_TRUE(res);
  9402. EXPECT_EQ("Page Content Page Content", res->body);
  9403. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9404. }
  9405. }
  9406. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9407. auto handled = false;
  9408. Server svr;
  9409. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9410. thread t = thread([&] { svr.listen(HOST, PORT); });
  9411. auto se = detail::scope_exit([&] {
  9412. svr.stop();
  9413. t.join();
  9414. ASSERT_FALSE(svr.is_running());
  9415. ASSERT_FALSE(handled);
  9416. });
  9417. svr.wait_until_ready();
  9418. auto req = "POST /test HTTP/1.1\r\n"
  9419. "Content-Length: x\r\n"
  9420. "\r\n";
  9421. std::string response;
  9422. ASSERT_TRUE(send_request(1, req, &response));
  9423. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9424. response.substr(0, response.find("\r\n")));
  9425. }
  9426. #ifndef _WIN32
  9427. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9428. static constexpr char reject[] = "Unauthorized";
  9429. static constexpr char accept[] = "Upload accepted";
  9430. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9431. Server svr;
  9432. svr.set_expect_100_continue_handler(
  9433. [](const Request & /*req*/, Response &res) {
  9434. res.status = StatusCode::Unauthorized_401;
  9435. res.set_content(reject, "text/plain");
  9436. return res.status;
  9437. });
  9438. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9439. res.set_content(accept, "text/plain");
  9440. });
  9441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9442. auto se = detail::scope_exit([&] {
  9443. svr.stop();
  9444. thread.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. });
  9447. svr.wait_until_ready();
  9448. {
  9449. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9450. curl_easy_init(), &curl_easy_cleanup};
  9451. ASSERT_NE(curl, nullptr);
  9452. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9453. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9454. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9455. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9456. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9457. &curl_slist_free_all};
  9458. ASSERT_NE(list, nullptr);
  9459. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9460. struct read_data {
  9461. size_t read_size;
  9462. size_t total_size;
  9463. } data = {0, total_size};
  9464. using read_callback_t =
  9465. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9466. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9467. void *userdata) -> size_t {
  9468. read_data *data = (read_data *)userdata;
  9469. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9470. std::fill_n(ptr, size * nmemb, 'A');
  9471. data->read_size += size * nmemb;
  9472. return size * nmemb;
  9473. };
  9474. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9475. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9476. std::vector<char> buffer;
  9477. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9478. using write_callback_t =
  9479. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9480. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9481. void *userdata) -> size_t {
  9482. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9483. buffer->reserve(buffer->size() + size * nmemb + 1);
  9484. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9485. return size * nmemb;
  9486. };
  9487. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9488. {
  9489. const auto res = curl_easy_perform(curl.get());
  9490. ASSERT_EQ(res, CURLE_OK);
  9491. }
  9492. {
  9493. auto response_code = long{};
  9494. const auto res =
  9495. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9496. ASSERT_EQ(res, CURLE_OK);
  9497. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9498. }
  9499. {
  9500. auto dl = curl_off_t{};
  9501. const auto res =
  9502. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9503. ASSERT_EQ(res, CURLE_OK);
  9504. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9505. }
  9506. {
  9507. buffer.push_back('\0');
  9508. ASSERT_STRCASEEQ(buffer.data(), reject);
  9509. }
  9510. }
  9511. }
  9512. #endif
  9513. template <typename S, typename C>
  9514. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9515. svr.Get("/stream", [&](const Request &, Response &res) {
  9516. auto data = new std::string("01234567890123456789");
  9517. res.set_content_provider(
  9518. data->size(), "text/plain",
  9519. [&, data](size_t offset, size_t length, DataSink &sink) {
  9520. const size_t DATA_CHUNK_SIZE = 4;
  9521. const auto &d = *data;
  9522. std::this_thread::sleep_for(std::chrono::seconds(1));
  9523. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9524. return true;
  9525. },
  9526. [data](bool success) {
  9527. EXPECT_FALSE(success);
  9528. delete data;
  9529. });
  9530. });
  9531. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9532. auto i = new size_t(0);
  9533. res.set_content_provider(
  9534. "text/plain",
  9535. [i](size_t, DataSink &sink) {
  9536. if (*i < 5) {
  9537. std::this_thread::sleep_for(std::chrono::seconds(1));
  9538. sink.write("abcd", 4);
  9539. (*i)++;
  9540. } else {
  9541. sink.done();
  9542. }
  9543. return true;
  9544. },
  9545. [i](bool success) {
  9546. EXPECT_FALSE(success);
  9547. delete i;
  9548. });
  9549. });
  9550. svr.Get("/chunked", [&](const Request &, Response &res) {
  9551. auto i = new size_t(0);
  9552. res.set_chunked_content_provider(
  9553. "text/plain",
  9554. [i](size_t, DataSink &sink) {
  9555. if (*i < 5) {
  9556. std::this_thread::sleep_for(std::chrono::seconds(1));
  9557. sink.os << "abcd";
  9558. (*i)++;
  9559. } else {
  9560. sink.done();
  9561. }
  9562. return true;
  9563. },
  9564. [i](bool success) {
  9565. EXPECT_FALSE(success);
  9566. delete i;
  9567. });
  9568. });
  9569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9570. auto se = detail::scope_exit([&] {
  9571. svr.stop();
  9572. listen_thread.join();
  9573. ASSERT_FALSE(svr.is_running());
  9574. });
  9575. svr.wait_until_ready();
  9576. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9577. {
  9578. auto start = std::chrono::steady_clock::now();
  9579. auto res = cli.Get("/stream");
  9580. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9581. std::chrono::steady_clock::now() - start)
  9582. .count();
  9583. ASSERT_FALSE(res);
  9584. EXPECT_EQ(Error::Read, res.error());
  9585. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9586. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9587. }
  9588. {
  9589. auto start = std::chrono::steady_clock::now();
  9590. auto res = cli.Get("/stream_without_length");
  9591. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9592. std::chrono::steady_clock::now() - start)
  9593. .count();
  9594. ASSERT_FALSE(res);
  9595. EXPECT_EQ(Error::Read, res.error());
  9596. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9597. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9598. }
  9599. {
  9600. auto start = std::chrono::steady_clock::now();
  9601. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9602. EXPECT_EQ("abcd", string(data, data_length));
  9603. return true;
  9604. });
  9605. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9606. std::chrono::steady_clock::now() - start)
  9607. .count();
  9608. ASSERT_FALSE(res);
  9609. EXPECT_EQ(Error::Read, res.error());
  9610. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9611. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9612. }
  9613. }
  9614. TEST(MaxTimeoutTest, ContentStream) {
  9615. time_t timeout = 2000;
  9616. time_t threshold = 200;
  9617. Server svr;
  9618. Client cli("localhost", PORT);
  9619. max_timeout_test(svr, cli, timeout, threshold);
  9620. }
  9621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9622. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9623. time_t timeout = 2000;
  9624. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9626. SSLClient cli("localhost", PORT);
  9627. cli.enable_server_certificate_verification(false);
  9628. max_timeout_test(svr, cli, timeout, threshold);
  9629. }
  9630. #endif
  9631. class EventDispatcher {
  9632. public:
  9633. EventDispatcher() {}
  9634. bool wait_event(DataSink *sink) {
  9635. unique_lock<mutex> lk(m_);
  9636. int id = id_;
  9637. // Wait with timeout to prevent hanging if client disconnects
  9638. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9639. [&] { return cid_ == id; })) {
  9640. return false; // Timeout occurred
  9641. }
  9642. sink->write(message_.data(), message_.size());
  9643. return true;
  9644. }
  9645. void send_event(const string &message) {
  9646. lock_guard<mutex> lk(m_);
  9647. cid_ = id_++;
  9648. message_ = message;
  9649. cv_.notify_all();
  9650. }
  9651. private:
  9652. mutex m_;
  9653. condition_variable cv_;
  9654. atomic_int id_{0};
  9655. atomic_int cid_{-1};
  9656. string message_;
  9657. };
  9658. TEST(ClientInThreadTest, Issue2068) {
  9659. EventDispatcher ed;
  9660. Server svr;
  9661. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9662. res.set_chunked_content_provider("text/event-stream",
  9663. [&](size_t /*offset*/, DataSink &sink) {
  9664. return ed.wait_event(&sink);
  9665. });
  9666. });
  9667. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9668. svr.wait_until_ready();
  9669. thread event_thread([&] {
  9670. int id = 0;
  9671. while (svr.is_running()) {
  9672. this_thread::sleep_for(chrono::milliseconds(500));
  9673. std::stringstream ss;
  9674. ss << "data: " << id << "\n\n";
  9675. ed.send_event(ss.str());
  9676. id++;
  9677. }
  9678. });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. listen_thread.join();
  9682. event_thread.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. {
  9686. auto client = detail::make_unique<Client>(HOST, PORT);
  9687. client->set_read_timeout(std::chrono::minutes(10));
  9688. std::atomic<bool> stop{false};
  9689. std::thread t([&] {
  9690. client->Get("/event1",
  9691. [&](const char *, size_t) -> bool { return !stop; });
  9692. });
  9693. std::this_thread::sleep_for(std::chrono::seconds(2));
  9694. stop = true;
  9695. client->stop();
  9696. t.join();
  9697. // Reset client after thread has finished
  9698. client.reset();
  9699. }
  9700. }
  9701. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9702. Server svr;
  9703. svr.Get("/", [](const Request &req, Response &res) {
  9704. EXPECT_EQ(2U, req.trailers.size());
  9705. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9706. // Denied
  9707. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9708. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9709. // Accepted
  9710. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9711. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9712. EXPECT_TRUE(req.has_trailer("X-World"));
  9713. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9714. res.set_content("ok", "text/plain");
  9715. });
  9716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. const std::string req = "GET / HTTP/1.1\r\n"
  9724. "Transfer-Encoding: chunked\r\n"
  9725. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9726. "\r\n"
  9727. "0\r\n"
  9728. "Content-Length: 10\r\n"
  9729. "Host: internal.local\r\n"
  9730. "Content-Type: malicious/content\r\n"
  9731. "Cookie: any\r\n"
  9732. "Set-Cookie: any\r\n"
  9733. "X-Forwarded-For: attacker.com\r\n"
  9734. "X-Real-Ip: 1.1.1.1\r\n"
  9735. "X-Hello: hello\r\n"
  9736. "X-World: world\r\n"
  9737. "\r\n";
  9738. std::string res;
  9739. ASSERT_TRUE(send_request(1, req, &res));
  9740. }
  9741. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9742. Server svr;
  9743. std::string observed_remote_addr;
  9744. std::string observed_xff;
  9745. svr.Get("/ip", [&](const Request &req, Response &res) {
  9746. observed_remote_addr = req.remote_addr;
  9747. observed_xff = req.get_header_value("X-Forwarded-For");
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. t.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. Client cli(HOST, PORT);
  9758. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9759. ASSERT_TRUE(res);
  9760. EXPECT_EQ(StatusCode::OK_200, res->status);
  9761. EXPECT_EQ(observed_xff, "203.0.113.66");
  9762. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9763. observed_remote_addr == "127.0.0.1");
  9764. }
  9765. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9766. Server svr;
  9767. svr.set_trusted_proxies({"203.0.113.66"});
  9768. std::string observed_remote_addr;
  9769. std::string observed_xff;
  9770. svr.Get("/ip", [&](const Request &req, Response &res) {
  9771. observed_remote_addr = req.remote_addr;
  9772. observed_xff = req.get_header_value("X-Forwarded-For");
  9773. res.set_content("ok", "text/plain");
  9774. });
  9775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9776. auto se = detail::scope_exit([&] {
  9777. svr.stop();
  9778. t.join();
  9779. ASSERT_FALSE(svr.is_running());
  9780. });
  9781. svr.wait_until_ready();
  9782. Client cli(HOST, PORT);
  9783. auto res = cli.Get("/ip");
  9784. ASSERT_TRUE(res);
  9785. EXPECT_EQ(StatusCode::OK_200, res->status);
  9786. EXPECT_EQ(observed_xff, "");
  9787. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9788. observed_remote_addr == "127.0.0.1");
  9789. }
  9790. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9791. Server svr;
  9792. svr.set_trusted_proxies({"203.0.113.66"});
  9793. std::string observed_remote_addr;
  9794. std::string observed_xff;
  9795. svr.Get("/ip", [&](const Request &req, Response &res) {
  9796. observed_remote_addr = req.remote_addr;
  9797. observed_xff = req.get_header_value("X-Forwarded-For");
  9798. res.set_content("ok", "text/plain");
  9799. });
  9800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9801. auto se = detail::scope_exit([&] {
  9802. svr.stop();
  9803. t.join();
  9804. ASSERT_FALSE(svr.is_running());
  9805. });
  9806. svr.wait_until_ready();
  9807. Client cli(HOST, PORT);
  9808. auto res =
  9809. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9810. ASSERT_TRUE(res);
  9811. EXPECT_EQ(StatusCode::OK_200, res->status);
  9812. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9813. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9814. }
  9815. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9816. Server svr;
  9817. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9818. std::string observed_remote_addr;
  9819. std::string observed_xff;
  9820. svr.Get("/ip", [&](const Request &req, Response &res) {
  9821. observed_remote_addr = req.remote_addr;
  9822. observed_xff = req.get_header_value("X-Forwarded-For");
  9823. res.set_content("ok", "text/plain");
  9824. });
  9825. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9826. auto se = detail::scope_exit([&] {
  9827. svr.stop();
  9828. t.join();
  9829. ASSERT_FALSE(svr.is_running());
  9830. });
  9831. svr.wait_until_ready();
  9832. Client cli(HOST, PORT);
  9833. auto res = cli.Get(
  9834. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9835. ASSERT_TRUE(res);
  9836. EXPECT_EQ(StatusCode::OK_200, res->status);
  9837. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9838. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9839. }
  9840. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9841. Server svr;
  9842. svr.set_trusted_proxies({"192.0.2.45"});
  9843. std::string observed_remote_addr;
  9844. std::string observed_xff;
  9845. svr.Get("/ip", [&](const Request &req, Response &res) {
  9846. observed_remote_addr = req.remote_addr;
  9847. observed_xff = req.get_header_value("X-Forwarded-For");
  9848. res.set_content("ok", "text/plain");
  9849. });
  9850. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9851. auto se = detail::scope_exit([&] {
  9852. svr.stop();
  9853. t.join();
  9854. ASSERT_FALSE(svr.is_running());
  9855. });
  9856. svr.wait_until_ready();
  9857. Client cli(HOST, PORT);
  9858. auto res =
  9859. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9860. ASSERT_TRUE(res);
  9861. EXPECT_EQ(StatusCode::OK_200, res->status);
  9862. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9863. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9864. }
  9865. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9866. Server svr;
  9867. svr.set_trusted_proxies({"192.0.2.45"});
  9868. std::string observed_remote_addr;
  9869. std::string observed_xff;
  9870. svr.Get("/ip", [&](const Request &req, Response &res) {
  9871. observed_remote_addr = req.remote_addr;
  9872. observed_xff = req.get_header_value("X-Forwarded-For");
  9873. res.set_content("ok", "text/plain");
  9874. });
  9875. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9876. auto se = detail::scope_exit([&] {
  9877. svr.stop();
  9878. t.join();
  9879. ASSERT_FALSE(svr.is_running());
  9880. });
  9881. svr.wait_until_ready();
  9882. Client cli(HOST, PORT);
  9883. auto res = cli.Get(
  9884. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9885. ASSERT_TRUE(res);
  9886. EXPECT_EQ(StatusCode::OK_200, res->status);
  9887. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9888. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9889. }
  9890. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9891. Server svr;
  9892. svr.set_trusted_proxies({"192.0.2.45"});
  9893. std::string observed_remote_addr;
  9894. std::string observed_xff;
  9895. svr.Get("/ip", [&](const Request &req, Response &res) {
  9896. observed_remote_addr = req.remote_addr;
  9897. observed_xff = req.get_header_value("X-Forwarded-For");
  9898. res.set_content("ok", "text/plain");
  9899. });
  9900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. });
  9906. svr.wait_until_ready();
  9907. std::string raw_req =
  9908. "GET /ip HTTP/1.1\r\n"
  9909. "Host: localhost\r\n"
  9910. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9911. "Connection: close\r\n"
  9912. "\r\n";
  9913. std::string out;
  9914. ASSERT_TRUE(send_request(5, raw_req, &out));
  9915. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9916. // Header parser trims surrounding whitespace of the header value
  9917. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9918. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9919. }
  9920. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9921. Server svr;
  9922. svr.Post("/post", [&](const Request &req, Response &res) {
  9923. res.set_content(req.body, "text/plain");
  9924. });
  9925. svr.Put("/put", [&](const Request &req, Response &res) {
  9926. res.set_content(req.body, "text/plain");
  9927. });
  9928. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9929. res.set_content(req.body, "text/plain");
  9930. });
  9931. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9932. res.set_content(req.body, "text/plain");
  9933. });
  9934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9935. auto se = detail::scope_exit([&] {
  9936. svr.stop();
  9937. t.join();
  9938. ASSERT_FALSE(svr.is_running());
  9939. });
  9940. svr.wait_until_ready();
  9941. std::string resp;
  9942. // POST without Content-Length
  9943. ASSERT_TRUE(send_request(5,
  9944. "POST /post HTTP/1.1\r\n"
  9945. "Host: localhost\r\n"
  9946. "Connection: close\r\n"
  9947. "\r\n",
  9948. &resp));
  9949. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9950. // PUT without Content-Length
  9951. resp.clear();
  9952. ASSERT_TRUE(send_request(5,
  9953. "PUT /put HTTP/1.1\r\n"
  9954. "Host: localhost\r\n"
  9955. "Connection: close\r\n"
  9956. "\r\n",
  9957. &resp));
  9958. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9959. // PATCH without Content-Length
  9960. resp.clear();
  9961. ASSERT_TRUE(send_request(5,
  9962. "PATCH /patch HTTP/1.1\r\n"
  9963. "Host: localhost\r\n"
  9964. "Connection: close\r\n"
  9965. "\r\n",
  9966. &resp));
  9967. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9968. // DELETE without Content-Length
  9969. resp.clear();
  9970. ASSERT_TRUE(send_request(5,
  9971. "DELETE /delete HTTP/1.1\r\n"
  9972. "Host: localhost\r\n"
  9973. "Connection: close\r\n"
  9974. "\r\n",
  9975. &resp));
  9976. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9977. }
  9978. //==============================================================================
  9979. // open_stream() Tests
  9980. //==============================================================================
  9981. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9982. std::string result;
  9983. char buf[8192];
  9984. ssize_t n;
  9985. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9986. result.append(buf, static_cast<size_t>(n));
  9987. }
  9988. return result;
  9989. }
  9990. // Mock stream for unit tests
  9991. class MockStream : public Stream {
  9992. public:
  9993. std::string data;
  9994. size_t pos = 0;
  9995. ssize_t error_after = -1; // -1 = no error
  9996. explicit MockStream(const std::string &d, ssize_t err = -1)
  9997. : data(d), error_after(err) {}
  9998. bool is_readable() const override { return true; }
  9999. bool wait_readable() const override { return true; }
  10000. bool wait_writable() const override { return true; }
  10001. ssize_t read(char *ptr, size_t size) override {
  10002. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10003. if (pos >= data.size()) return 0;
  10004. size_t limit =
  10005. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10006. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10007. std::memcpy(ptr, data.data() + pos, to_read);
  10008. pos += to_read;
  10009. return static_cast<ssize_t>(to_read);
  10010. }
  10011. ssize_t write(const char *, size_t) override { return -1; }
  10012. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10013. ip = "127.0.0.1";
  10014. port = 0;
  10015. }
  10016. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10017. ip = "127.0.0.1";
  10018. port = 0;
  10019. }
  10020. socket_t socket() const override { return INVALID_SOCKET; }
  10021. time_t duration() const override { return 0; }
  10022. };
  10023. TEST(StreamHandleTest, Basic) {
  10024. ClientImpl::StreamHandle handle;
  10025. EXPECT_FALSE(handle.is_valid());
  10026. handle.response = detail::make_unique<Response>();
  10027. handle.error = Error::Connection;
  10028. EXPECT_FALSE(handle.is_valid());
  10029. handle.error = Error::Success;
  10030. EXPECT_TRUE(handle.is_valid());
  10031. }
  10032. TEST(BodyReaderTest, Basic) {
  10033. MockStream stream("Hello, World!");
  10034. detail::BodyReader reader;
  10035. reader.stream = &stream;
  10036. reader.content_length = 13;
  10037. char buf[32];
  10038. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10039. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10040. EXPECT_TRUE(reader.eof);
  10041. }
  10042. TEST(BodyReaderTest, NoStream) {
  10043. detail::BodyReader reader;
  10044. char buf[32];
  10045. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10046. EXPECT_EQ(Error::Connection, reader.last_error);
  10047. }
  10048. TEST(BodyReaderTest, Error) {
  10049. MockStream stream("Hello, World!", 5);
  10050. detail::BodyReader reader;
  10051. reader.stream = &stream;
  10052. reader.content_length = 13;
  10053. char buf[32];
  10054. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10055. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10056. EXPECT_EQ(Error::Read, reader.last_error);
  10057. }
  10058. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10059. // Mock-based StreamHandle tests relying on private internals are removed.
  10060. class OpenStreamTest : public ::testing::Test {
  10061. protected:
  10062. void SetUp() override {
  10063. svr_.Get("/hello", [](const Request &, Response &res) {
  10064. res.set_content("Hello World!", "text/plain");
  10065. });
  10066. svr_.Get("/large", [](const Request &, Response &res) {
  10067. res.set_content(std::string(10000, 'X'), "text/plain");
  10068. });
  10069. svr_.Get("/chunked", [](const Request &, Response &res) {
  10070. res.set_chunked_content_provider("text/plain",
  10071. [](size_t offset, DataSink &sink) {
  10072. if (offset < 15) {
  10073. sink.write("chunk", 5);
  10074. return true;
  10075. }
  10076. sink.done();
  10077. return true;
  10078. });
  10079. });
  10080. svr_.Get("/compressible", [](const Request &, Response &res) {
  10081. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10082. DataSink &sink) {
  10083. if (offset < 100 * 1024) {
  10084. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10085. sink.write(chunk.data(), chunk.size());
  10086. return true;
  10087. }
  10088. sink.done();
  10089. return true;
  10090. });
  10091. });
  10092. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10093. [](const Request & /*req*/, Response &res) {
  10094. auto i = new int(0);
  10095. res.set_header("Trailer", "Content-Length, X-Allowed");
  10096. res.set_chunked_content_provider(
  10097. "text/plain",
  10098. [i](size_t /*offset*/, DataSink &sink) {
  10099. switch (*i) {
  10100. case 0: sink.os << "123"; break;
  10101. case 1: sink.os << "456"; break;
  10102. case 2: sink.os << "789"; break;
  10103. case 3: {
  10104. sink.done_with_trailer(
  10105. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10106. } break;
  10107. }
  10108. (*i)++;
  10109. return true;
  10110. },
  10111. [i](bool success) {
  10112. EXPECT_TRUE(success);
  10113. delete i;
  10114. });
  10115. });
  10116. // Echo headers endpoint for header-related tests
  10117. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10118. std::string body;
  10119. for (const auto &h : req.headers) {
  10120. body.append(h.first);
  10121. body.push_back(':');
  10122. body.append(h.second);
  10123. body.push_back('\n');
  10124. }
  10125. res.set_content(body, "text/plain");
  10126. });
  10127. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10128. std::string body;
  10129. for (const auto &h : req.headers) {
  10130. body.append(h.first);
  10131. body.push_back(':');
  10132. body.append(h.second);
  10133. body.push_back('\n');
  10134. }
  10135. res.set_content(body, "text/plain");
  10136. });
  10137. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10138. svr_.wait_until_ready();
  10139. }
  10140. void TearDown() override {
  10141. svr_.stop();
  10142. if (thread_.joinable()) thread_.join();
  10143. }
  10144. Server svr_;
  10145. std::thread thread_;
  10146. };
  10147. TEST_F(OpenStreamTest, Basic) {
  10148. Client cli("127.0.0.1", 8787);
  10149. auto handle = cli.open_stream("GET", "/hello");
  10150. EXPECT_TRUE(handle.is_valid());
  10151. EXPECT_EQ("Hello World!", read_all(handle));
  10152. }
  10153. TEST_F(OpenStreamTest, SmallBuffer) {
  10154. Client cli("127.0.0.1", 8787);
  10155. auto handle = cli.open_stream("GET", "/hello");
  10156. std::string result;
  10157. char buf[4];
  10158. ssize_t n;
  10159. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10160. result.append(buf, static_cast<size_t>(n));
  10161. EXPECT_EQ("Hello World!", result);
  10162. }
  10163. TEST_F(OpenStreamTest, DefaultHeaders) {
  10164. Client cli("127.0.0.1", 8787);
  10165. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10166. {
  10167. auto handle = cli.open_stream("GET", "/echo-headers");
  10168. ASSERT_TRUE(handle.is_valid());
  10169. auto body = read_all(handle);
  10170. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10171. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10172. std::string::npos);
  10173. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10174. }
  10175. // open_stream POST with body and no explicit content_type should NOT add
  10176. // text/plain Content-Type (behavior differs from non-streaming path), but
  10177. // should include Content-Length
  10178. {
  10179. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10180. ASSERT_TRUE(handle.is_valid());
  10181. auto body = read_all(handle);
  10182. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10183. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10184. }
  10185. // open_stream POST with explicit Content-Type should preserve it
  10186. {
  10187. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10188. {{"Content-Type", "application/custom"}},
  10189. "{}", "application/custom");
  10190. ASSERT_TRUE(handle.is_valid());
  10191. auto body = read_all(handle);
  10192. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10193. }
  10194. // User-specified User-Agent must not be overwritten for stream API
  10195. {
  10196. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10197. {{"User-Agent", "MyAgent/1.2"}});
  10198. ASSERT_TRUE(handle.is_valid());
  10199. auto body = read_all(handle);
  10200. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10201. }
  10202. }
  10203. TEST_F(OpenStreamTest, Large) {
  10204. Client cli("127.0.0.1", 8787);
  10205. auto handle = cli.open_stream("GET", "/large");
  10206. EXPECT_EQ(10000u, read_all(handle).size());
  10207. }
  10208. TEST_F(OpenStreamTest, ConnectionError) {
  10209. Client cli("127.0.0.1", 9999);
  10210. auto handle = cli.open_stream("GET", "/hello");
  10211. EXPECT_FALSE(handle.is_valid());
  10212. }
  10213. TEST_F(OpenStreamTest, Chunked) {
  10214. Client cli("127.0.0.1", 8787);
  10215. auto handle = cli.open_stream("GET", "/chunked");
  10216. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10217. "Transfer-Encoding") == "chunked");
  10218. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10219. }
  10220. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10221. Client cli("127.0.0.1", 8787);
  10222. auto handle =
  10223. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10224. ASSERT_TRUE(handle.is_valid());
  10225. // Consume body to allow trailers to be received/parsed
  10226. auto body = read_all(handle);
  10227. // Explicitly parse trailers (ensure trailers are available for assertion)
  10228. handle.parse_trailers_if_needed();
  10229. EXPECT_EQ(std::string("123456789"), body);
  10230. // The response should include a Trailer header declaring both names
  10231. ASSERT_TRUE(handle.response);
  10232. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10233. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10234. handle.response->get_header_value("Trailer"));
  10235. // Prohibited trailer must not be present
  10236. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10237. // Allowed trailer should be present
  10238. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10239. EXPECT_EQ(std::string("yes"),
  10240. handle.response->get_trailer_value("X-Allowed"));
  10241. // Verify trailers are NOT present as regular headers
  10242. EXPECT_EQ(std::string(""),
  10243. handle.response->get_header_value("Content-Length"));
  10244. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10245. }
  10246. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10247. TEST_F(OpenStreamTest, Gzip) {
  10248. Client cli("127.0.0.1", 8787);
  10249. auto handle = cli.open_stream("GET", "/compressible", {},
  10250. {{"Accept-Encoding", "gzip"}});
  10251. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10252. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10253. }
  10254. #endif
  10255. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10256. TEST_F(OpenStreamTest, Brotli) {
  10257. Client cli("127.0.0.1", 8787);
  10258. auto handle =
  10259. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10260. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10261. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10262. }
  10263. #endif
  10264. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10265. TEST_F(OpenStreamTest, Zstd) {
  10266. Client cli("127.0.0.1", 8787);
  10267. auto handle = cli.open_stream("GET", "/compressible", {},
  10268. {{"Accept-Encoding", "zstd"}});
  10269. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10270. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10271. }
  10272. #endif
  10273. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10274. class SSLOpenStreamTest : public ::testing::Test {
  10275. protected:
  10276. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10277. void SetUp() override {
  10278. svr_.Get("/hello", [](const Request &, Response &res) {
  10279. res.set_content("Hello SSL World!", "text/plain");
  10280. });
  10281. svr_.Get("/chunked", [](const Request &, Response &res) {
  10282. res.set_chunked_content_provider("text/plain",
  10283. [](size_t offset, DataSink &sink) {
  10284. if (offset < 15) {
  10285. sink.write("chunk", 5);
  10286. return true;
  10287. }
  10288. sink.done();
  10289. return true;
  10290. });
  10291. });
  10292. svr_.Post("/echo", [](const Request &req, Response &res) {
  10293. res.set_content(req.body, req.get_header_value("Content-Type"));
  10294. });
  10295. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10296. std::string body = req.body;
  10297. res.set_chunked_content_provider(
  10298. "text/plain", [body](size_t offset, DataSink &sink) {
  10299. if (offset < body.size()) {
  10300. sink.write(body.data() + offset, body.size() - offset);
  10301. }
  10302. sink.done();
  10303. return true;
  10304. });
  10305. });
  10306. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10307. svr_.wait_until_ready();
  10308. }
  10309. void TearDown() override {
  10310. svr_.stop();
  10311. if (thread_.joinable()) thread_.join();
  10312. }
  10313. SSLServer svr_;
  10314. std::thread thread_;
  10315. };
  10316. TEST_F(SSLOpenStreamTest, Basic) {
  10317. SSLClient cli("127.0.0.1", 8788);
  10318. cli.enable_server_certificate_verification(false);
  10319. auto handle = cli.open_stream("GET", "/hello");
  10320. ASSERT_TRUE(handle.is_valid());
  10321. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10322. }
  10323. TEST_F(SSLOpenStreamTest, Chunked) {
  10324. SSLClient cli("127.0.0.1", 8788);
  10325. cli.enable_server_certificate_verification(false);
  10326. auto handle = cli.open_stream("GET", "/chunked");
  10327. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10328. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10329. "Transfer-Encoding") == "chunked");
  10330. auto body = read_all(handle);
  10331. EXPECT_EQ("chunkchunkchunk", body);
  10332. }
  10333. TEST_F(SSLOpenStreamTest, Post) {
  10334. SSLClient cli("127.0.0.1", 8788);
  10335. cli.enable_server_certificate_verification(false);
  10336. auto handle =
  10337. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10338. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10339. EXPECT_EQ(200, handle.response->status);
  10340. auto body = read_all(handle);
  10341. EXPECT_EQ("Hello SSL POST", body);
  10342. }
  10343. TEST_F(SSLOpenStreamTest, PostChunked) {
  10344. SSLClient cli("127.0.0.1", 8788);
  10345. cli.enable_server_certificate_verification(false);
  10346. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10347. "Chunked SSL Data", "text/plain");
  10348. ASSERT_TRUE(handle.is_valid());
  10349. EXPECT_EQ(200, handle.response->status);
  10350. auto body = read_all(handle);
  10351. EXPECT_EQ("Chunked SSL Data", body);
  10352. }
  10353. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10354. //==============================================================================
  10355. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10356. // results for various scenarios.
  10357. //==============================================================================
  10358. TEST(ParityTest, GetVsOpenStream) {
  10359. Server svr;
  10360. const std::string path = "/parity";
  10361. const std::string content = "Parity test content: hello world";
  10362. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10363. res.set_content(content, "text/plain");
  10364. });
  10365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. t.join();
  10369. ASSERT_FALSE(svr.is_running());
  10370. });
  10371. svr.wait_until_ready();
  10372. Client cli(HOST, PORT);
  10373. // Non-stream path
  10374. auto r1 = cli.Get(path);
  10375. ASSERT_TRUE(r1);
  10376. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10377. // Stream path
  10378. auto h = cli.open_stream("GET", path);
  10379. ASSERT_TRUE(h.is_valid());
  10380. EXPECT_EQ(r1->body, read_all(h));
  10381. }
  10382. // Helper to compress data with provided compressor type T
  10383. template <typename Compressor>
  10384. static std::string compress_payload_for_parity(const std::string &in) {
  10385. std::string out;
  10386. Compressor compressor;
  10387. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10388. [&](const char *data, size_t n) {
  10389. out.append(data, n);
  10390. return true;
  10391. });
  10392. EXPECT_TRUE(ok);
  10393. return out;
  10394. }
  10395. // Helper function for compression parity tests
  10396. template <typename Compressor>
  10397. static void test_compression_parity(const std::string &original,
  10398. const std::string &path,
  10399. const std::string &encoding) {
  10400. const std::string compressed =
  10401. compress_payload_for_parity<Compressor>(original);
  10402. Server svr;
  10403. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10404. res.set_content(compressed, "application/octet-stream");
  10405. res.set_header("Content-Encoding", encoding);
  10406. });
  10407. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10408. auto se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. t.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. Client cli(HOST, PORT);
  10415. // Non-streaming
  10416. {
  10417. auto res = cli.Get(path);
  10418. ASSERT_TRUE(res);
  10419. EXPECT_EQ(StatusCode::OK_200, res->status);
  10420. EXPECT_EQ(original, res->body);
  10421. }
  10422. // Streaming
  10423. {
  10424. auto h = cli.open_stream("GET", path);
  10425. ASSERT_TRUE(h.is_valid());
  10426. EXPECT_EQ(original, read_all(h));
  10427. }
  10428. }
  10429. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10430. TEST(ParityTest, Gzip) {
  10431. test_compression_parity<detail::gzip_compressor>(
  10432. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10433. }
  10434. #endif
  10435. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10436. TEST(ParityTest, Brotli) {
  10437. test_compression_parity<detail::brotli_compressor>(
  10438. "Hello, brotli parity test payload", "/parity-br", "br");
  10439. }
  10440. #endif
  10441. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10442. TEST(ParityTest, Zstd) {
  10443. test_compression_parity<detail::zstd_compressor>(
  10444. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10445. }
  10446. #endif
  10447. //==============================================================================
  10448. // New Stream API Tests
  10449. //==============================================================================
  10450. inline std::string read_body(httplib::stream::Result &result) {
  10451. std::string body;
  10452. while (result.next()) {
  10453. body.append(result.data(), result.size());
  10454. }
  10455. return body;
  10456. }
  10457. TEST(ClientConnectionTest, Basic) {
  10458. httplib::ClientConnection conn;
  10459. EXPECT_FALSE(conn.is_open());
  10460. conn.sock = 1;
  10461. EXPECT_TRUE(conn.is_open());
  10462. httplib::ClientConnection conn2(std::move(conn));
  10463. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10464. conn2.sock = INVALID_SOCKET;
  10465. }
  10466. // Unified test server for all stream::* tests
  10467. class StreamApiTest : public ::testing::Test {
  10468. protected:
  10469. void SetUp() override {
  10470. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10471. res.set_content("Hello World!", "text/plain");
  10472. });
  10473. svr_.Get("/echo-params",
  10474. [](const httplib::Request &req, httplib::Response &res) {
  10475. std::string r;
  10476. for (const auto &p : req.params) {
  10477. if (!r.empty()) r += "&";
  10478. r += p.first + "=" + p.second;
  10479. }
  10480. res.set_content(r, "text/plain");
  10481. });
  10482. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10483. res.set_content(req.body, req.get_header_value("Content-Type"));
  10484. });
  10485. svr_.Post("/echo-headers",
  10486. [](const httplib::Request &req, httplib::Response &res) {
  10487. std::string r;
  10488. for (const auto &h : req.headers)
  10489. r += h.first + ": " + h.second + "\n";
  10490. res.set_content(r, "text/plain");
  10491. });
  10492. svr_.Post("/echo-params",
  10493. [](const httplib::Request &req, httplib::Response &res) {
  10494. std::string r = "params:";
  10495. for (const auto &p : req.params)
  10496. r += p.first + "=" + p.second + ";";
  10497. res.set_content(r + " body:" + req.body, "text/plain");
  10498. });
  10499. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10500. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10501. });
  10502. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10503. res.set_content("PUT:" + req.body, "text/plain");
  10504. });
  10505. svr_.Patch("/echo",
  10506. [](const httplib::Request &req, httplib::Response &res) {
  10507. res.set_content("PATCH:" + req.body, "text/plain");
  10508. });
  10509. svr_.Delete(
  10510. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10511. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10512. "text/plain");
  10513. });
  10514. svr_.Get("/head-test",
  10515. [](const httplib::Request &, httplib::Response &res) {
  10516. res.set_content("body for HEAD", "text/plain");
  10517. });
  10518. svr_.Options("/options",
  10519. [](const httplib::Request &, httplib::Response &res) {
  10520. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10521. });
  10522. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10523. svr_.wait_until_ready();
  10524. }
  10525. void TearDown() override {
  10526. svr_.stop();
  10527. if (thread_.joinable()) thread_.join();
  10528. }
  10529. httplib::Server svr_;
  10530. std::thread thread_;
  10531. };
  10532. // stream::Get tests
  10533. TEST_F(StreamApiTest, GetBasic) {
  10534. httplib::Client cli(HOST, PORT);
  10535. auto result = httplib::stream::Get(cli, "/hello");
  10536. ASSERT_TRUE(result.is_valid());
  10537. EXPECT_EQ(200, result.status());
  10538. EXPECT_EQ("Hello World!", read_body(result));
  10539. }
  10540. TEST_F(StreamApiTest, GetWithParams) {
  10541. httplib::Client cli(HOST, PORT);
  10542. httplib::Params params{{"foo", "bar"}};
  10543. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10544. ASSERT_TRUE(result.is_valid());
  10545. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10546. }
  10547. TEST_F(StreamApiTest, GetConnectionError) {
  10548. httplib::Client cli(HOST, 9999);
  10549. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10550. }
  10551. TEST_F(StreamApiTest, Get404) {
  10552. httplib::Client cli(HOST, PORT);
  10553. auto result = httplib::stream::Get(cli, "/nonexistent");
  10554. EXPECT_TRUE(result.is_valid());
  10555. EXPECT_EQ(404, result.status());
  10556. }
  10557. // stream::Post tests
  10558. TEST_F(StreamApiTest, PostBasic) {
  10559. httplib::Client cli(HOST, PORT);
  10560. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10561. "application/json");
  10562. ASSERT_TRUE(result.is_valid());
  10563. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10564. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10565. }
  10566. TEST_F(StreamApiTest, PostWithHeaders) {
  10567. httplib::Client cli(HOST, PORT);
  10568. httplib::Headers headers{{"X-Custom", "value"}};
  10569. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10570. "text/plain");
  10571. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10572. }
  10573. TEST_F(StreamApiTest, PostWithParams) {
  10574. httplib::Client cli(HOST, PORT);
  10575. httplib::Params params{{"k", "v"}};
  10576. auto result =
  10577. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10578. auto body = read_body(result);
  10579. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10580. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10581. }
  10582. TEST_F(StreamApiTest, PostLarge) {
  10583. httplib::Client cli(HOST, PORT);
  10584. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10585. size_t total = 0;
  10586. while (result.next()) {
  10587. total += result.size();
  10588. }
  10589. EXPECT_EQ(100u * 1024u, total);
  10590. }
  10591. // stream::Put/Patch tests
  10592. TEST_F(StreamApiTest, PutAndPatch) {
  10593. httplib::Client cli(HOST, PORT);
  10594. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10595. EXPECT_EQ("PUT:test", read_body(put));
  10596. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10597. EXPECT_EQ("PATCH:test", read_body(patch));
  10598. }
  10599. // stream::Delete tests
  10600. TEST_F(StreamApiTest, Delete) {
  10601. httplib::Client cli(HOST, PORT);
  10602. auto del1 = httplib::stream::Delete(cli, "/resource");
  10603. EXPECT_EQ("Deleted", read_body(del1));
  10604. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10605. EXPECT_EQ("Deleted:data", read_body(del2));
  10606. }
  10607. // stream::Head/Options tests
  10608. TEST_F(StreamApiTest, HeadAndOptions) {
  10609. httplib::Client cli(HOST, PORT);
  10610. auto head = httplib::stream::Head(cli, "/head-test");
  10611. EXPECT_TRUE(head.is_valid());
  10612. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10613. auto opts = httplib::stream::Options(cli, "/options");
  10614. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10615. }
  10616. // SSL stream::* tests
  10617. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10618. class SSLStreamApiTest : public ::testing::Test {
  10619. protected:
  10620. void SetUp() override {
  10621. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10622. res.set_content("Hello SSL!", "text/plain");
  10623. });
  10624. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10625. res.set_content(req.body, "text/plain");
  10626. });
  10627. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10628. svr_.wait_until_ready();
  10629. }
  10630. void TearDown() override {
  10631. svr_.stop();
  10632. if (thread_.joinable()) thread_.join();
  10633. }
  10634. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10635. std::thread thread_;
  10636. };
  10637. TEST_F(SSLStreamApiTest, GetAndPost) {
  10638. httplib::SSLClient cli("127.0.0.1", 8803);
  10639. cli.enable_server_certificate_verification(false);
  10640. auto get = httplib::stream::Get(cli, "/hello");
  10641. EXPECT_EQ("Hello SSL!", read_body(get));
  10642. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10643. EXPECT_EQ("test", read_body(post));
  10644. }
  10645. #endif
  10646. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10647. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10648. // BodyReader
  10649. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10650. // Test that read timeout during streaming is detected
  10651. // Use a large content-length response where server delays mid-stream
  10652. Server svr;
  10653. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10654. // Send a large response with delay in the middle
  10655. res.set_content_provider(
  10656. 1000, // content_length
  10657. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10658. if (offset < 100) {
  10659. // Send first 100 bytes immediately
  10660. std::string data(100, 'A');
  10661. sink.write(data.c_str(), data.size());
  10662. return true;
  10663. }
  10664. // Then delay longer than client timeout
  10665. std::this_thread::sleep_for(std::chrono::seconds(3));
  10666. std::string data(900, 'B');
  10667. sink.write(data.c_str(), data.size());
  10668. return true;
  10669. });
  10670. });
  10671. auto port = 8091;
  10672. std::thread t([&]() { svr.listen("localhost", port); });
  10673. svr.wait_until_ready();
  10674. Client cli("localhost", port);
  10675. cli.set_read_timeout(1, 0); // 1 second timeout
  10676. auto handle = cli.open_stream("GET", "/slow-stream");
  10677. ASSERT_TRUE(handle.is_valid());
  10678. char buf[256];
  10679. ssize_t total = 0;
  10680. ssize_t n;
  10681. bool got_error = false;
  10682. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10683. total += n;
  10684. }
  10685. if (n < 0) {
  10686. got_error = true;
  10687. // Should be timeout or read error
  10688. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10689. handle.get_read_error() == Error::Read)
  10690. << "Actual error: " << to_string(handle.get_read_error());
  10691. }
  10692. // Either we got an error, or we got less data than expected
  10693. EXPECT_TRUE(got_error || total < 1000)
  10694. << "Expected timeout but got all " << total << " bytes";
  10695. svr.stop();
  10696. t.join();
  10697. }
  10698. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10699. // Test connection closed detection via BodyReader
  10700. Server svr;
  10701. std::atomic<bool> close_now{false};
  10702. svr.Get("/will-close", [&](const Request &, Response &res) {
  10703. res.set_content_provider(
  10704. 10000, // Large content_length that we won't fully send
  10705. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10706. if (offset < 100) {
  10707. std::string data(100, 'X');
  10708. sink.write(data.c_str(), data.size());
  10709. return true;
  10710. }
  10711. // Wait for signal then abort
  10712. while (!close_now) {
  10713. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10714. }
  10715. return false; // Abort - server will close connection
  10716. });
  10717. });
  10718. auto port = 8092;
  10719. std::thread t([&]() { svr.listen("localhost", port); });
  10720. svr.wait_until_ready();
  10721. Client cli("localhost", port);
  10722. auto handle = cli.open_stream("GET", "/will-close");
  10723. ASSERT_TRUE(handle.is_valid());
  10724. char buf[256];
  10725. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10726. EXPECT_GT(n, 0) << "First read should succeed";
  10727. // Signal server to close
  10728. close_now = true;
  10729. // Keep reading until error or EOF
  10730. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10731. // Keep reading
  10732. }
  10733. // Should get an error since content_length wasn't satisfied
  10734. if (n < 0) {
  10735. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10736. handle.get_read_error() == Error::Read)
  10737. << "Actual error: " << to_string(handle.get_read_error());
  10738. }
  10739. svr.stop();
  10740. t.join();
  10741. }
  10742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10743. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10744. // Test that read timeout during SSL streaming is detected
  10745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10746. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10747. res.set_content_provider(
  10748. 1000, "text/plain",
  10749. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10750. if (offset < 100) {
  10751. std::string data(100, 'A');
  10752. sink.write(data.c_str(), data.size());
  10753. return true;
  10754. }
  10755. std::this_thread::sleep_for(std::chrono::seconds(3));
  10756. std::string data(900, 'B');
  10757. sink.write(data.c_str(), data.size());
  10758. return true;
  10759. });
  10760. });
  10761. auto port = 8093;
  10762. std::thread t([&]() { svr.listen("localhost", port); });
  10763. svr.wait_until_ready();
  10764. SSLClient cli("localhost", port);
  10765. cli.enable_server_certificate_verification(false);
  10766. cli.set_read_timeout(1, 0); // 1 second timeout
  10767. auto handle = cli.open_stream("GET", "/slow-stream");
  10768. ASSERT_TRUE(handle.is_valid());
  10769. char buf[256];
  10770. ssize_t total = 0;
  10771. ssize_t n;
  10772. bool got_error = false;
  10773. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10774. total += n;
  10775. }
  10776. if (n < 0) {
  10777. got_error = true;
  10778. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10779. handle.get_read_error() == Error::Read)
  10780. << "Actual error: " << to_string(handle.get_read_error());
  10781. }
  10782. EXPECT_TRUE(got_error || total < 1000)
  10783. << "Expected timeout but got all " << total << " bytes";
  10784. svr.stop();
  10785. t.join();
  10786. }
  10787. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10788. // Test SSL connection closed detection
  10789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10790. std::atomic<bool> close_now{false};
  10791. svr.Get("/will-close", [&](const Request &, Response &res) {
  10792. res.set_content_provider(
  10793. 10000, "text/plain",
  10794. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10795. if (offset < 100) {
  10796. std::string data(100, 'X');
  10797. sink.write(data.c_str(), data.size());
  10798. return true;
  10799. }
  10800. while (!close_now) {
  10801. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10802. }
  10803. return false;
  10804. });
  10805. });
  10806. auto port = 8094;
  10807. std::thread t([&]() { svr.listen("localhost", port); });
  10808. svr.wait_until_ready();
  10809. SSLClient cli("localhost", port);
  10810. cli.enable_server_certificate_verification(false);
  10811. auto handle = cli.open_stream("GET", "/will-close");
  10812. ASSERT_TRUE(handle.is_valid());
  10813. char buf[256];
  10814. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10815. EXPECT_GT(n, 0);
  10816. // Signal server to close
  10817. close_now = true;
  10818. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10819. // Keep reading
  10820. }
  10821. if (n < 0) {
  10822. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10823. handle.get_read_error() == Error::Read)
  10824. << "Actual error: " << to_string(handle.get_read_error());
  10825. }
  10826. svr.stop();
  10827. t.join();
  10828. }
  10829. #endif
  10830. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10831. using namespace httplib;
  10832. // Create a test file
  10833. const char *fname = "etag_testfile.txt";
  10834. const char *content = "etag-content";
  10835. {
  10836. std::ofstream ofs(fname);
  10837. ofs << content;
  10838. ASSERT_TRUE(ofs.good());
  10839. }
  10840. Server svr;
  10841. svr.set_mount_point("/static", ".");
  10842. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10843. svr.wait_until_ready();
  10844. Client cli(HOST, PORT);
  10845. // First request: should get 200 with ETag header
  10846. auto res1 = cli.Get("/static/etag_testfile.txt");
  10847. ASSERT_TRUE(res1);
  10848. ASSERT_EQ(200, res1->status);
  10849. ASSERT_TRUE(res1->has_header("ETag"));
  10850. std::string etag = res1->get_header_value("ETag");
  10851. EXPECT_FALSE(etag.empty());
  10852. // Verify ETag format: W/"hex-hex"
  10853. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10854. EXPECT_EQ('W', etag[0]);
  10855. EXPECT_EQ('/', etag[1]);
  10856. EXPECT_EQ('"', etag[2]);
  10857. EXPECT_EQ('"', etag.back());
  10858. // Exact match: expect 304 Not Modified
  10859. Headers h2 = {{"If-None-Match", etag}};
  10860. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10861. ASSERT_TRUE(res2);
  10862. EXPECT_EQ(304, res2->status);
  10863. // Wildcard match: expect 304 Not Modified
  10864. Headers h3 = {{"If-None-Match", "*"}};
  10865. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10866. ASSERT_TRUE(res3);
  10867. EXPECT_EQ(304, res3->status);
  10868. // Non-matching ETag: expect 200
  10869. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10870. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10871. ASSERT_TRUE(res4);
  10872. EXPECT_EQ(200, res4->status);
  10873. // Multiple ETags with one matching: expect 304
  10874. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10875. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10876. ASSERT_TRUE(res5);
  10877. EXPECT_EQ(304, res5->status);
  10878. svr.stop();
  10879. t.join();
  10880. std::remove(fname);
  10881. }
  10882. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10883. using namespace httplib;
  10884. Server svr;
  10885. svr.set_mount_point("/static", ".");
  10886. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10887. svr.wait_until_ready();
  10888. Client cli(HOST, PORT);
  10889. // Send If-None-Match: * to a non-existent file
  10890. Headers h = {{"If-None-Match", "*"}};
  10891. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10892. ASSERT_TRUE(res);
  10893. EXPECT_EQ(404, res->status);
  10894. svr.stop();
  10895. t.join();
  10896. }
  10897. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10898. using namespace httplib;
  10899. // Create a test file
  10900. const char *fname = "ims_testfile.txt";
  10901. const char *content = "if-modified-since-test";
  10902. {
  10903. std::ofstream ofs(fname);
  10904. ofs << content;
  10905. ASSERT_TRUE(ofs.good());
  10906. }
  10907. Server svr;
  10908. svr.set_mount_point("/static", ".");
  10909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10910. svr.wait_until_ready();
  10911. Client cli(HOST, PORT);
  10912. // First request: should get 200 with Last-Modified header
  10913. auto res1 = cli.Get("/static/ims_testfile.txt");
  10914. ASSERT_TRUE(res1);
  10915. ASSERT_EQ(200, res1->status);
  10916. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10917. std::string last_modified = res1->get_header_value("Last-Modified");
  10918. EXPECT_FALSE(last_modified.empty());
  10919. // If-Modified-Since with same time: expect 304
  10920. Headers h2 = {{"If-Modified-Since", last_modified}};
  10921. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10922. ASSERT_TRUE(res2);
  10923. EXPECT_EQ(304, res2->status);
  10924. // If-Modified-Since with future time: expect 304
  10925. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10926. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10927. ASSERT_TRUE(res3);
  10928. EXPECT_EQ(304, res3->status);
  10929. // If-Modified-Since with past time: expect 200
  10930. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10931. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10932. ASSERT_TRUE(res4);
  10933. EXPECT_EQ(200, res4->status);
  10934. // If-None-Match takes precedence over If-Modified-Since
  10935. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10936. ASSERT_TRUE(res1->has_header("ETag"));
  10937. std::string etag = res1->get_header_value("ETag");
  10938. Headers h5 = {{"If-None-Match", etag},
  10939. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10940. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10941. ASSERT_TRUE(res5);
  10942. EXPECT_EQ(304, res5->status);
  10943. svr.stop();
  10944. t.join();
  10945. std::remove(fname);
  10946. }
  10947. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10948. using namespace httplib;
  10949. Server svr;
  10950. // Endpoint that returns compressible content
  10951. svr.Get("/compressible", [](const Request &, Response &res) {
  10952. // Return a large enough body to trigger compression
  10953. std::string body(1000, 'a');
  10954. res.set_content(body, "text/plain");
  10955. });
  10956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10957. svr.wait_until_ready();
  10958. Client cli(HOST, PORT);
  10959. // Request with gzip support: should get Vary header when compressed
  10960. cli.set_compress(true);
  10961. auto res1 = cli.Get("/compressible");
  10962. ASSERT_TRUE(res1);
  10963. EXPECT_EQ(200, res1->status);
  10964. // If Content-Encoding is set, Vary should also be set
  10965. if (res1->has_header("Content-Encoding")) {
  10966. EXPECT_TRUE(res1->has_header("Vary"));
  10967. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10968. }
  10969. // Request without Accept-Encoding header: should not have compression
  10970. Headers h_no_compress;
  10971. auto res2 = cli.Get("/compressible", h_no_compress);
  10972. ASSERT_TRUE(res2);
  10973. EXPECT_EQ(200, res2->status);
  10974. // Verify Vary header is present when compression is applied
  10975. // (the exact behavior depends on server configuration)
  10976. svr.stop();
  10977. t.join();
  10978. }
  10979. TEST(ETagTest, IfRangeWithETag) {
  10980. using namespace httplib;
  10981. // Create a test file with known content
  10982. const char *fname = "if_range_testfile.txt";
  10983. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10984. {
  10985. std::ofstream ofs(fname);
  10986. ofs << content;
  10987. ASSERT_TRUE(ofs.good());
  10988. }
  10989. Server svr;
  10990. svr.set_mount_point("/static", ".");
  10991. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10992. svr.wait_until_ready();
  10993. Client cli(HOST, PORT);
  10994. // First request: get ETag
  10995. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10996. ASSERT_TRUE(res1);
  10997. ASSERT_EQ(200, res1->status);
  10998. ASSERT_TRUE(res1->has_header("ETag"));
  10999. std::string etag = res1->get_header_value("ETag");
  11000. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11001. // Since our server generates weak ETags (W/"..."), If-Range with our
  11002. // ETag should NOT result in partial content - it should return full content.
  11003. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11004. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11005. ASSERT_TRUE(res2);
  11006. // Weak ETag in If-Range -> full content (200), not partial (206)
  11007. EXPECT_EQ(200, res2->status);
  11008. EXPECT_EQ(content, res2->body);
  11009. EXPECT_FALSE(res2->has_header("Content-Range"));
  11010. // Range request with non-matching If-Range (ETag): should get 200 (full
  11011. // content)
  11012. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11013. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11014. ASSERT_TRUE(res3);
  11015. EXPECT_EQ(200, res3->status);
  11016. EXPECT_EQ(content, res3->body);
  11017. EXPECT_FALSE(res3->has_header("Content-Range"));
  11018. // Range request with strong ETag (hypothetical - our server doesn't generate
  11019. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11020. // should return full content)
  11021. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11022. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11023. ASSERT_TRUE(res4);
  11024. EXPECT_EQ(200, res4->status);
  11025. EXPECT_EQ(content, res4->body);
  11026. EXPECT_FALSE(res4->has_header("Content-Range"));
  11027. svr.stop();
  11028. t.join();
  11029. std::remove(fname);
  11030. }
  11031. TEST(ETagTest, IfRangeWithDate) {
  11032. using namespace httplib;
  11033. // Create a test file
  11034. const char *fname = "if_range_date_testfile.txt";
  11035. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11036. {
  11037. std::ofstream ofs(fname);
  11038. ofs << content;
  11039. ASSERT_TRUE(ofs.good());
  11040. }
  11041. Server svr;
  11042. svr.set_mount_point("/static", ".");
  11043. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11044. svr.wait_until_ready();
  11045. Client cli(HOST, PORT);
  11046. // First request: get Last-Modified
  11047. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11048. ASSERT_TRUE(res1);
  11049. ASSERT_EQ(200, res1->status);
  11050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11051. std::string last_modified = res1->get_header_value("Last-Modified");
  11052. // Range request with matching If-Range (date): should get 206
  11053. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11054. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11055. ASSERT_TRUE(res2);
  11056. EXPECT_EQ(206, res2->status);
  11057. EXPECT_EQ("FGHIJ", res2->body);
  11058. // Range request with old If-Range date: should get 200 (full content)
  11059. Headers h3 = {{"Range", "bytes=5-9"},
  11060. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11061. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11062. ASSERT_TRUE(res3);
  11063. EXPECT_EQ(200, res3->status);
  11064. EXPECT_EQ(content, res3->body);
  11065. // Range request with future If-Range date: should get 206
  11066. Headers h4 = {{"Range", "bytes=0-4"},
  11067. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11068. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11069. ASSERT_TRUE(res4);
  11070. EXPECT_EQ(206, res4->status);
  11071. EXPECT_EQ("ABCDE", res4->body);
  11072. svr.stop();
  11073. t.join();
  11074. std::remove(fname);
  11075. }
  11076. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11077. using namespace httplib;
  11078. const char *fname = "etag_malformed.txt";
  11079. const char *content = "malformed-etag";
  11080. {
  11081. std::ofstream ofs(fname);
  11082. ofs << content;
  11083. ASSERT_TRUE(ofs.good());
  11084. }
  11085. Server svr;
  11086. svr.set_mount_point("/static", ".");
  11087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11088. svr.wait_until_ready();
  11089. Client cli(HOST, PORT);
  11090. // baseline: should get 200 and an ETag
  11091. auto res1 = cli.Get("/static/etag_malformed.txt");
  11092. ASSERT_TRUE(res1);
  11093. ASSERT_EQ(200, res1->status);
  11094. ASSERT_TRUE(res1->has_header("ETag"));
  11095. // Malformed ETag value (missing quotes) should be treated as non-matching
  11096. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11097. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11098. ASSERT_TRUE(res_bad);
  11099. EXPECT_EQ(200, res_bad->status);
  11100. // Whitespace-only header value should be considered invalid / non-matching
  11101. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11102. "Host: localhost\r\n"
  11103. "If-None-Match: \r\n"
  11104. "Connection: close\r\n"
  11105. "\r\n";
  11106. std::string out;
  11107. ASSERT_TRUE(send_request(5, raw_req, &out));
  11108. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11109. svr.stop();
  11110. t.join();
  11111. std::remove(fname);
  11112. }
  11113. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11114. using namespace httplib;
  11115. const char *fname = "ims_invalid_format.txt";
  11116. const char *content = "ims-bad-format";
  11117. {
  11118. std::ofstream ofs(fname);
  11119. ofs << content;
  11120. ASSERT_TRUE(ofs.good());
  11121. }
  11122. Server svr;
  11123. svr.set_mount_point("/static", ".");
  11124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11125. svr.wait_until_ready();
  11126. Client cli(HOST, PORT);
  11127. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11128. ASSERT_TRUE(res1);
  11129. ASSERT_EQ(200, res1->status);
  11130. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11131. // If-Modified-Since with invalid format should not result in 304
  11132. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11133. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11134. ASSERT_TRUE(res_bad);
  11135. EXPECT_EQ(200, res_bad->status);
  11136. // If-Range with invalid date format should be treated as mismatch -> full
  11137. // content (200)
  11138. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11139. {"If-Range", "invalid-date"}};
  11140. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11141. ASSERT_TRUE(res_ifrange);
  11142. EXPECT_EQ(200, res_ifrange->status);
  11143. svr.stop();
  11144. t.join();
  11145. std::remove(fname);
  11146. }
  11147. TEST(ETagTest, IfRangeWithMalformedETag) {
  11148. using namespace httplib;
  11149. const char *fname = "ifrange_malformed.txt";
  11150. const std::string content = "0123456789";
  11151. {
  11152. std::ofstream ofs(fname);
  11153. ofs << content;
  11154. ASSERT_TRUE(ofs.good());
  11155. }
  11156. Server svr;
  11157. svr.set_mount_point("/static", ".");
  11158. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11159. svr.wait_until_ready();
  11160. Client cli(HOST, PORT);
  11161. // First request: get ETag
  11162. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11163. ASSERT_TRUE(res1);
  11164. ASSERT_EQ(200, res1->status);
  11165. ASSERT_TRUE(res1->has_header("ETag"));
  11166. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11167. // full content (200)
  11168. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11169. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11170. ASSERT_TRUE(res2);
  11171. EXPECT_EQ(200, res2->status);
  11172. EXPECT_EQ(content, res2->body);
  11173. svr.stop();
  11174. t.join();
  11175. std::remove(fname);
  11176. }
  11177. TEST(ETagTest, ExtremeLargeDateValues) {
  11178. using namespace httplib;
  11179. const char *fname = "ims_extreme_date.txt";
  11180. const char *content = "ims-extreme-date";
  11181. {
  11182. std::ofstream ofs(fname);
  11183. ofs << content;
  11184. ASSERT_TRUE(ofs.good());
  11185. }
  11186. Server svr;
  11187. svr.set_mount_point("/static", ".");
  11188. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. auto res1 = cli.Get(std::string("/static/") + fname);
  11192. ASSERT_TRUE(res1);
  11193. ASSERT_EQ(200, res1->status);
  11194. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11195. // Extremely large year that may overflow date parsing routines.
  11196. Headers h_large_date = {
  11197. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11198. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11199. ASSERT_TRUE(res_bad);
  11200. // Expect server to treat this as invalid/mismatch and return full content
  11201. EXPECT_EQ(200, res_bad->status);
  11202. // If-Range with extremely large date should be treated as mismatch -> full
  11203. // content (200)
  11204. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11205. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11206. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11207. ASSERT_TRUE(res_ifrange);
  11208. EXPECT_EQ(200, res_ifrange->status);
  11209. svr.stop();
  11210. t.join();
  11211. std::remove(fname);
  11212. }
  11213. TEST(ETagTest, NegativeFileModificationTime) {
  11214. using namespace httplib;
  11215. const char *fname = "ims_negative_mtime.txt";
  11216. const std::string content = "negative-mtime";
  11217. {
  11218. std::ofstream ofs(fname);
  11219. ofs << content;
  11220. ASSERT_TRUE(ofs.good());
  11221. }
  11222. // Try to set file mtime to a negative value. This may fail on some
  11223. // platforms/filesystems; if it fails, the test will still verify server
  11224. // behaves safely by performing a regular conditional request.
  11225. #if defined(__APPLE__) || defined(__linux__)
  11226. bool set_negative = false;
  11227. do {
  11228. struct timeval times[2];
  11229. // access time: now
  11230. times[0].tv_sec = time(nullptr);
  11231. times[0].tv_usec = 0;
  11232. // modification time: negative (e.g., -1)
  11233. times[1].tv_sec = -1;
  11234. times[1].tv_usec = 0;
  11235. if (utimes(fname, times) == 0) { set_negative = true; }
  11236. } while (0);
  11237. #else
  11238. bool set_negative = false;
  11239. #endif
  11240. Server svr;
  11241. svr.set_mount_point("/static", ".");
  11242. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11243. svr.wait_until_ready();
  11244. Client cli(HOST, PORT);
  11245. auto res1 = cli.Get(std::string("/static/") + fname);
  11246. ASSERT_TRUE(res1);
  11247. ASSERT_EQ(200, res1->status);
  11248. bool has_last_modified = res1->has_header("Last-Modified");
  11249. std::string last_modified;
  11250. if (has_last_modified) {
  11251. last_modified = res1->get_header_value("Last-Modified");
  11252. }
  11253. if (set_negative) {
  11254. // If we successfully set a negative mtime, ensure server returns a
  11255. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11256. // with an old date and ensure server handles it without crash.
  11257. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11258. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11259. ASSERT_TRUE(res2);
  11260. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11261. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11262. } else {
  11263. // Could not set negative mtime on this platform; fall back to verifying
  11264. // that normal invalid/malformed dates are treated safely (non-304).
  11265. Headers h_bad_date = {
  11266. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11267. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11268. ASSERT_TRUE(res_bad);
  11269. EXPECT_EQ(200, res_bad->status);
  11270. }
  11271. svr.stop();
  11272. t.join();
  11273. std::remove(fname);
  11274. }
  11275. //==============================================================================
  11276. // SSE Parsing Tests
  11277. //==============================================================================
  11278. class SSEParsingTest : public ::testing::Test {
  11279. protected:
  11280. // Test helper that mimics SSE parsing behavior
  11281. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11282. int &retry_ms) {
  11283. // Blank line signals end of event
  11284. if (line.empty() || line == "\r") { return true; }
  11285. // Lines starting with ':' are comments (ignored)
  11286. if (!line.empty() && line[0] == ':') { return false; }
  11287. // Find the colon separator
  11288. auto colon_pos = line.find(':');
  11289. if (colon_pos == std::string::npos) {
  11290. // Line with no colon is treated as field name with empty value
  11291. return false;
  11292. }
  11293. std::string field = line.substr(0, colon_pos);
  11294. std::string value;
  11295. // Value starts after colon, skip optional single space
  11296. if (colon_pos + 1 < line.size()) {
  11297. size_t value_start = colon_pos + 1;
  11298. if (line[value_start] == ' ') { value_start++; }
  11299. value = line.substr(value_start);
  11300. // Remove trailing \r if present
  11301. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11302. }
  11303. // Handle known fields
  11304. if (field == "event") {
  11305. msg.event = value;
  11306. } else if (field == "data") {
  11307. // Multiple data lines are concatenated with newlines
  11308. if (!msg.data.empty()) { msg.data += "\n"; }
  11309. msg.data += value;
  11310. } else if (field == "id") {
  11311. // Empty id is valid (clears the last event ID)
  11312. msg.id = value;
  11313. } else if (field == "retry") {
  11314. // Parse retry interval in milliseconds
  11315. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11316. {
  11317. std::istringstream iss(value);
  11318. int v;
  11319. iss >> v;
  11320. if (!iss.fail()) { retry_ms = v; }
  11321. }
  11322. #else
  11323. try {
  11324. retry_ms = std::stoi(value);
  11325. } catch (...) {
  11326. // Invalid retry value, ignore
  11327. }
  11328. #endif
  11329. }
  11330. // Unknown fields are ignored per SSE spec
  11331. return false;
  11332. }
  11333. };
  11334. // Test: Single-line data
  11335. TEST_F(SSEParsingTest, SingleLineData) {
  11336. sse::SSEMessage msg;
  11337. int retry_ms = 3000;
  11338. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11339. EXPECT_EQ(msg.data, "hello");
  11340. EXPECT_EQ(msg.event, "message");
  11341. // Blank line ends event
  11342. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11343. }
  11344. // Test: Multi-line data
  11345. TEST_F(SSEParsingTest, MultiLineData) {
  11346. sse::SSEMessage msg;
  11347. int retry_ms = 3000;
  11348. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11349. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11350. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11351. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11352. }
  11353. // Test: Custom event types
  11354. TEST_F(SSEParsingTest, CustomEventType) {
  11355. sse::SSEMessage msg;
  11356. int retry_ms = 3000;
  11357. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11358. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11359. EXPECT_EQ(msg.event, "update");
  11360. EXPECT_EQ(msg.data, "payload");
  11361. }
  11362. // Test: Event ID handling
  11363. TEST_F(SSEParsingTest, EventIdHandling) {
  11364. sse::SSEMessage msg;
  11365. int retry_ms = 3000;
  11366. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11367. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11368. EXPECT_EQ(msg.id, "12345");
  11369. }
  11370. // Test: Empty event ID (clears last event ID)
  11371. TEST_F(SSEParsingTest, EmptyEventId) {
  11372. sse::SSEMessage msg;
  11373. msg.id = "previous";
  11374. int retry_ms = 3000;
  11375. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11376. EXPECT_EQ(msg.id, "");
  11377. }
  11378. // Test: Retry field parsing
  11379. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11380. sse::SSEMessage msg;
  11381. int retry_ms = 3000;
  11382. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11383. EXPECT_EQ(retry_ms, 5000);
  11384. }
  11385. // Test: Invalid retry value
  11386. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11387. sse::SSEMessage msg;
  11388. int retry_ms = 3000;
  11389. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11390. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11391. }
  11392. // Test: Comments (lines starting with :)
  11393. TEST_F(SSEParsingTest, CommentsIgnored) {
  11394. sse::SSEMessage msg;
  11395. int retry_ms = 3000;
  11396. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11397. EXPECT_EQ(msg.data, "");
  11398. EXPECT_EQ(msg.event, "message");
  11399. }
  11400. // Test: Colon in value
  11401. TEST_F(SSEParsingTest, ColonInValue) {
  11402. sse::SSEMessage msg;
  11403. int retry_ms = 3000;
  11404. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11405. EXPECT_EQ(msg.data, "hello:world:test");
  11406. }
  11407. // Test: Line with no colon (field name only)
  11408. TEST_F(SSEParsingTest, FieldNameOnly) {
  11409. sse::SSEMessage msg;
  11410. int retry_ms = 3000;
  11411. // According to SSE spec, this is treated as field name with empty value
  11412. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11413. // Since we don't recognize "data" without colon, data should be empty
  11414. EXPECT_EQ(msg.data, "");
  11415. }
  11416. // Test: Trailing \r handling
  11417. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11418. sse::SSEMessage msg;
  11419. int retry_ms = 3000;
  11420. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11421. EXPECT_EQ(msg.data, "hello");
  11422. }
  11423. // Test: Unknown fields ignored
  11424. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11425. sse::SSEMessage msg;
  11426. int retry_ms = 3000;
  11427. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11428. EXPECT_EQ(msg.data, "");
  11429. EXPECT_EQ(msg.event, "message");
  11430. }
  11431. // Test: Space after colon is optional
  11432. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11433. sse::SSEMessage msg1, msg2;
  11434. int retry_ms = 3000;
  11435. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11436. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11437. EXPECT_EQ(msg1.data, "hello");
  11438. EXPECT_EQ(msg2.data, "hello");
  11439. }
  11440. // Test: SSEMessage clear
  11441. TEST_F(SSEParsingTest, MessageClear) {
  11442. sse::SSEMessage msg;
  11443. msg.event = "custom";
  11444. msg.data = "some data";
  11445. msg.id = "123";
  11446. msg.clear();
  11447. EXPECT_EQ(msg.event, "message");
  11448. EXPECT_EQ(msg.data, "");
  11449. EXPECT_EQ(msg.id, "");
  11450. }
  11451. // Test: Complete event parsing
  11452. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11453. sse::SSEMessage msg;
  11454. int retry_ms = 3000;
  11455. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11456. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11457. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11458. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11459. // Blank line ends event
  11460. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11461. EXPECT_EQ(msg.event, "notification");
  11462. EXPECT_EQ(msg.id, "evt-42");
  11463. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11464. EXPECT_EQ(retry_ms, 1000);
  11465. }
  11466. //==============================================================================
  11467. // Integration Tests with Server
  11468. //==============================================================================
  11469. class SSEIntegrationTest : public ::testing::Test {
  11470. protected:
  11471. void SetUp() override {
  11472. stop_server_.store(false);
  11473. events_.clear();
  11474. server_ = httplib::detail::make_unique<Server>();
  11475. setup_server();
  11476. start_server();
  11477. }
  11478. void TearDown() override {
  11479. stop_server_.store(true);
  11480. event_cv_.notify_all();
  11481. server_->stop();
  11482. if (server_thread_.joinable()) { server_thread_.join(); }
  11483. }
  11484. void setup_server() {
  11485. // Simple SSE endpoint
  11486. server_->Get("/events", [this](const Request &req, Response &res) {
  11487. auto last_id = req.get_header_value("Last-Event-ID");
  11488. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11489. res.set_chunked_content_provider(
  11490. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11491. std::unique_lock<std::mutex> lock(event_mutex_);
  11492. if (event_cv_.wait_for(
  11493. lock, std::chrono::milliseconds(200), [this] {
  11494. return !events_.empty() || stop_server_.load();
  11495. })) {
  11496. if (stop_server_.load()) { return false; }
  11497. if (!events_.empty()) {
  11498. std::string event = events_.front();
  11499. events_.erase(events_.begin());
  11500. sink.write(event.data(), event.size());
  11501. return true;
  11502. }
  11503. }
  11504. return !stop_server_.load();
  11505. });
  11506. });
  11507. // Endpoint that returns error
  11508. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11509. res.status = 500;
  11510. res.set_content("Internal Server Error", "text/plain");
  11511. });
  11512. // Endpoint for custom event types
  11513. server_->Get("/custom-events", [](const Request &, Response &res) {
  11514. res.set_chunked_content_provider(
  11515. "text/event-stream", [](size_t offset, DataSink &sink) {
  11516. if (offset == 0) {
  11517. std::string event = "event: update\ndata: updated\n\n"
  11518. "event: delete\ndata: deleted\n\n";
  11519. sink.write(event.data(), event.size());
  11520. }
  11521. return false; // End stream after sending
  11522. });
  11523. });
  11524. }
  11525. void start_server() {
  11526. port_ = server_->bind_to_any_port(HOST);
  11527. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11528. // Wait for server to start
  11529. while (!server_->is_running()) {
  11530. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11531. }
  11532. }
  11533. int get_port() const { return port_; }
  11534. void send_event(const std::string &event) {
  11535. std::lock_guard<std::mutex> lock(event_mutex_);
  11536. events_.push_back(event);
  11537. event_cv_.notify_all();
  11538. }
  11539. std::unique_ptr<Server> server_;
  11540. std::thread server_thread_;
  11541. std::mutex event_mutex_;
  11542. std::condition_variable event_cv_;
  11543. std::vector<std::string> events_;
  11544. std::atomic<bool> stop_server_{false};
  11545. std::string last_received_event_id_;
  11546. int port_ = 0;
  11547. };
  11548. // Test: Successful connection and on_open callback
  11549. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11550. // Add a simple endpoint that sends one event and closes
  11551. server_->Get("/simple-event", [](const Request &, Response &res) {
  11552. res.set_chunked_content_provider(
  11553. "text/event-stream", [](size_t offset, DataSink &sink) {
  11554. if (offset == 0) {
  11555. std::string event = "data: hello\n\n";
  11556. sink.write(event.data(), event.size());
  11557. }
  11558. return false; // Close stream after sending
  11559. });
  11560. });
  11561. Client client("localhost", get_port());
  11562. sse::SSEClient sse(client, "/simple-event");
  11563. std::atomic<bool> open_called{false};
  11564. std::atomic<bool> message_received{false};
  11565. sse.on_open([&open_called]() { open_called.store(true); });
  11566. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11567. if (msg.data == "hello") { message_received.store(true); }
  11568. });
  11569. sse.set_reconnect_interval(100);
  11570. sse.set_max_reconnect_attempts(1);
  11571. // Start async
  11572. sse.start_async();
  11573. // Wait for message to be processed
  11574. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11575. sse.stop();
  11576. EXPECT_TRUE(open_called.load());
  11577. EXPECT_TRUE(message_received.load());
  11578. }
  11579. // Test: on_message callback
  11580. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11581. // Endpoint that sends multiple events then closes
  11582. server_->Get("/multi-event", [](const Request &, Response &res) {
  11583. res.set_chunked_content_provider(
  11584. "text/event-stream", [](size_t offset, DataSink &sink) {
  11585. if (offset == 0) {
  11586. std::string events = "data: message1\n\ndata: message2\n\n";
  11587. sink.write(events.data(), events.size());
  11588. }
  11589. return false;
  11590. });
  11591. });
  11592. Client client("localhost", get_port());
  11593. sse::SSEClient sse(client, "/multi-event");
  11594. std::vector<std::string> received_messages;
  11595. std::mutex messages_mutex;
  11596. sse.on_message([&](const sse::SSEMessage &msg) {
  11597. std::lock_guard<std::mutex> lock(messages_mutex);
  11598. received_messages.push_back(msg.data);
  11599. });
  11600. sse.set_reconnect_interval(100);
  11601. sse.set_max_reconnect_attempts(1);
  11602. sse.start_async();
  11603. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11604. sse.stop();
  11605. std::lock_guard<std::mutex> lock(messages_mutex);
  11606. EXPECT_GE(received_messages.size(), 2u);
  11607. if (received_messages.size() >= 2) {
  11608. EXPECT_EQ(received_messages[0], "message1");
  11609. EXPECT_EQ(received_messages[1], "message2");
  11610. }
  11611. }
  11612. // Test: on_event for specific types
  11613. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11614. Client client("localhost", get_port());
  11615. sse::SSEClient sse(client, "/custom-events");
  11616. std::atomic<bool> update_received{false};
  11617. std::atomic<bool> delete_received{false};
  11618. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11619. if (msg.data == "updated") { update_received.store(true); }
  11620. });
  11621. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11622. if (msg.data == "deleted") { delete_received.store(true); }
  11623. });
  11624. sse.set_max_reconnect_attempts(1);
  11625. sse.start_async();
  11626. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11627. sse.stop();
  11628. EXPECT_TRUE(update_received.load());
  11629. EXPECT_TRUE(delete_received.load());
  11630. }
  11631. // Test: on_error callback on connection failure
  11632. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11633. // Connect to a non-existent port
  11634. Client client("localhost", 59999);
  11635. sse::SSEClient sse(client, "/events");
  11636. std::atomic<bool> error_called{false};
  11637. Error received_error = Error::Success;
  11638. sse.on_error([&](Error err) {
  11639. error_called.store(true);
  11640. received_error = err;
  11641. });
  11642. sse.set_reconnect_interval(50);
  11643. sse.set_max_reconnect_attempts(1);
  11644. sse.start_async();
  11645. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11646. sse.stop();
  11647. EXPECT_TRUE(error_called.load());
  11648. EXPECT_NE(received_error, Error::Success);
  11649. }
  11650. // Test: Last-Event-ID header sent on reconnect
  11651. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11652. // Endpoint that sends event with ID
  11653. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11654. res.set_chunked_content_provider(
  11655. "text/event-stream", [](size_t offset, DataSink &sink) {
  11656. if (offset == 0) {
  11657. std::string event = "id: evt-123\ndata: test\n\n";
  11658. sink.write(event.data(), event.size());
  11659. }
  11660. return false;
  11661. });
  11662. });
  11663. Client client("localhost", get_port());
  11664. sse::SSEClient sse(client, "/event-with-id");
  11665. std::atomic<bool> id_received{false};
  11666. sse.on_message([&](const sse::SSEMessage &msg) {
  11667. if (!msg.id.empty()) { id_received.store(true); }
  11668. });
  11669. sse.set_reconnect_interval(100);
  11670. sse.set_max_reconnect_attempts(1);
  11671. sse.start_async();
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11673. sse.stop();
  11674. EXPECT_TRUE(id_received.load());
  11675. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11676. }
  11677. // Test: Manual stop
  11678. TEST_F(SSEIntegrationTest, ManualStop) {
  11679. // Endpoint that sends one event and stays open briefly
  11680. std::atomic<bool> handler_running{true};
  11681. server_->Get("/stay-open", [&handler_running](const Request &,
  11682. Response &res) {
  11683. res.set_chunked_content_provider(
  11684. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11685. if (offset == 0) {
  11686. std::string event = "data: connected\n\n";
  11687. sink.write(event.data(), event.size());
  11688. }
  11689. // Keep connection open while handler_running is true
  11690. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11691. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11692. }
  11693. return false;
  11694. });
  11695. });
  11696. Client client("localhost", get_port());
  11697. sse::SSEClient sse(client, "/stay-open");
  11698. std::atomic<bool> connected{false};
  11699. sse.on_open([&connected]() { connected.store(true); });
  11700. sse.set_reconnect_interval(100);
  11701. sse.set_max_reconnect_attempts(1);
  11702. sse.start_async();
  11703. // Wait for connection to establish
  11704. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11705. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11706. }
  11707. EXPECT_TRUE(connected.load());
  11708. EXPECT_TRUE(sse.is_connected());
  11709. // Signal handler to stop
  11710. handler_running.store(false);
  11711. // Stop SSE client
  11712. sse.stop();
  11713. EXPECT_FALSE(sse.is_connected());
  11714. }
  11715. // Test: SSEClient with custom headers
  11716. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11717. // Setup a server endpoint that checks for custom header
  11718. std::atomic<bool> header_received{false};
  11719. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11720. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11721. header_received.store(true);
  11722. }
  11723. res.set_chunked_content_provider("text/event-stream",
  11724. [](size_t, DataSink &) { return false; });
  11725. });
  11726. Client client("localhost", get_port());
  11727. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11728. sse::SSEClient sse(client, "/header-check", headers);
  11729. sse.set_max_reconnect_attempts(1);
  11730. sse.start_async();
  11731. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11732. sse.stop();
  11733. EXPECT_TRUE(header_received.load());
  11734. }
  11735. // Test: Reconnect interval configuration
  11736. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11737. Client client("localhost", get_port());
  11738. sse::SSEClient sse(client, "/events");
  11739. auto &result = sse.set_reconnect_interval(500);
  11740. // Builder pattern should return reference to self
  11741. EXPECT_EQ(&result, &sse);
  11742. }
  11743. // Test: Max reconnect attempts
  11744. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11745. // Connect to non-existent port to force reconnects
  11746. Client client("localhost", 59998);
  11747. sse::SSEClient sse(client, "/events");
  11748. std::atomic<int> error_count{0};
  11749. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11750. sse.set_reconnect_interval(50);
  11751. sse.set_max_reconnect_attempts(2);
  11752. auto start = std::chrono::steady_clock::now();
  11753. sse.start(); // Blocking call
  11754. auto end = std::chrono::steady_clock::now();
  11755. // Should have stopped after 2 failed attempts
  11756. EXPECT_GE(error_count.load(), 2);
  11757. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11758. auto duration =
  11759. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11760. #ifdef _WIN32
  11761. // Windows is much slower for socket connection failures
  11762. EXPECT_LT(duration.count(), 7000);
  11763. #else
  11764. EXPECT_LT(duration.count(), 1000);
  11765. #endif
  11766. }
  11767. // Test: Multi-line data in integration
  11768. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11769. // Endpoint with multi-line data
  11770. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11771. res.set_chunked_content_provider(
  11772. "text/event-stream", [](size_t offset, DataSink &sink) {
  11773. if (offset == 0) {
  11774. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11775. sink.write(event.data(), event.size());
  11776. }
  11777. return false;
  11778. });
  11779. });
  11780. Client client("localhost", get_port());
  11781. sse::SSEClient sse(client, "/multiline-data");
  11782. std::string received_data;
  11783. std::mutex data_mutex;
  11784. sse.on_message([&](const sse::SSEMessage &msg) {
  11785. std::lock_guard<std::mutex> lock(data_mutex);
  11786. received_data = msg.data;
  11787. });
  11788. sse.set_reconnect_interval(100);
  11789. sse.set_max_reconnect_attempts(1);
  11790. sse.start_async();
  11791. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11792. sse.stop();
  11793. std::lock_guard<std::mutex> lock(data_mutex);
  11794. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11795. }
  11796. // Test: Auto-reconnect after server disconnection
  11797. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11798. std::atomic<int> connection_count{0};
  11799. std::atomic<int> message_count{0};
  11800. // Endpoint that sends one event and closes, forcing reconnect
  11801. server_->Get("/reconnect-test",
  11802. [&connection_count](const Request &, Response &res) {
  11803. connection_count.fetch_add(1);
  11804. res.set_chunked_content_provider(
  11805. "text/event-stream", [](size_t offset, DataSink &sink) {
  11806. if (offset == 0) {
  11807. std::string event = "data: hello\n\n";
  11808. sink.write(event.data(), event.size());
  11809. }
  11810. return false; // Close connection after sending
  11811. });
  11812. });
  11813. Client client("localhost", get_port());
  11814. sse::SSEClient sse(client, "/reconnect-test");
  11815. sse.on_message([&message_count](const sse::SSEMessage &) {
  11816. message_count.fetch_add(1);
  11817. });
  11818. sse.set_reconnect_interval(100);
  11819. sse.set_max_reconnect_attempts(3);
  11820. sse.start_async();
  11821. // Wait long enough for multiple reconnects
  11822. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11823. sse.stop();
  11824. // Should have connected multiple times (initial + reconnects)
  11825. EXPECT_GE(connection_count.load(), 2);
  11826. // Should have received messages from multiple connections
  11827. EXPECT_GE(message_count.load(), 2);
  11828. }
  11829. // Test: Last-Event-ID sent on reconnect
  11830. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11831. std::atomic<int> connection_count{0};
  11832. std::vector<std::string> received_last_event_ids;
  11833. std::mutex id_mutex;
  11834. // Endpoint that checks Last-Event-ID header and sends event with ID
  11835. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11836. int conn = connection_count.fetch_add(1);
  11837. // Capture the Last-Event-ID header from each connection
  11838. {
  11839. std::lock_guard<std::mutex> lock(id_mutex);
  11840. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11841. }
  11842. res.set_chunked_content_provider(
  11843. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11844. if (offset == 0) {
  11845. std::string event =
  11846. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11847. sink.write(event.data(), event.size());
  11848. }
  11849. return false;
  11850. });
  11851. });
  11852. Client client("localhost", get_port());
  11853. sse::SSEClient sse(client, "/reconnect-with-id");
  11854. sse.set_reconnect_interval(100);
  11855. sse.set_max_reconnect_attempts(3);
  11856. sse.start_async();
  11857. // Wait for at least 2 connections
  11858. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11859. sse.stop();
  11860. // Verify behavior
  11861. std::lock_guard<std::mutex> lock(id_mutex);
  11862. EXPECT_GE(received_last_event_ids.size(), 2u);
  11863. // First connection should have no Last-Event-ID
  11864. if (!received_last_event_ids.empty()) {
  11865. EXPECT_EQ(received_last_event_ids[0], "");
  11866. }
  11867. // Second connection should have Last-Event-ID from first connection
  11868. if (received_last_event_ids.size() >= 2) {
  11869. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11870. }
  11871. }
  11872. TEST(Issue2318Test, EmptyHostString) {
  11873. {
  11874. httplib::Client cli_empty("", PORT);
  11875. auto res = cli_empty.Get("/");
  11876. ASSERT_FALSE(res);
  11877. EXPECT_EQ(httplib::Error::Connection, res.error());
  11878. }
  11879. {
  11880. httplib::Client cli(" ", PORT);
  11881. auto res = cli.Get("/");
  11882. ASSERT_FALSE(res);
  11883. EXPECT_EQ(httplib::Error::Connection, res.error());
  11884. }
  11885. }
  11886. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11887. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  11888. Server svr;
  11889. // Set a small payload limit (1KB)
  11890. svr.set_payload_max_length(1024);
  11891. svr.Post("/test", [&](const Request &req, Response &res) {
  11892. res.set_content("Body size: " + std::to_string(req.body.size()),
  11893. "text/plain");
  11894. });
  11895. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11896. auto se = detail::scope_exit([&] {
  11897. svr.stop();
  11898. listen_thread.join();
  11899. });
  11900. svr.wait_until_ready();
  11901. // Create data that compresses well but exceeds limit when decompressed
  11902. // 8KB of repeated null bytes compresses to a very small size
  11903. std::string original_data(8 * 1024, '\0');
  11904. // Compress the data using gzip
  11905. std::string compressed_data;
  11906. detail::gzip_compressor compressor;
  11907. compressor.compress(original_data.data(), original_data.size(), true,
  11908. [&](const char *data, size_t size) {
  11909. compressed_data.append(data, size);
  11910. return true;
  11911. });
  11912. // Verify compression worked (compressed should be much smaller)
  11913. ASSERT_LT(compressed_data.size(), original_data.size());
  11914. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  11915. // Send compressed data with Content-Encoding: gzip
  11916. Client cli(HOST, PORT);
  11917. Headers headers = {{"Content-Encoding", "gzip"}};
  11918. auto res =
  11919. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  11920. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  11921. ASSERT_TRUE(res);
  11922. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11923. }
  11924. #endif