test.cc 262 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718
  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 <curl/curl.h>
  6. #endif
  7. #include <gtest/gtest.h>
  8. #include <atomic>
  9. #include <chrono>
  10. #include <fstream>
  11. #include <future>
  12. #include <limits>
  13. #include <memory>
  14. #include <sstream>
  15. #include <stdexcept>
  16. #include <thread>
  17. #include <type_traits>
  18. #include <vector>
  19. #define SERVER_CERT_FILE "./cert.pem"
  20. #define SERVER_CERT2_FILE "./cert2.pem"
  21. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  22. #define CA_CERT_FILE "./ca-bundle.crt"
  23. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  24. #define CLIENT_CA_CERT_DIR "."
  25. #define CLIENT_CERT_FILE "./client.cert.pem"
  26. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  27. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  28. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  29. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  30. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  31. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  32. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  33. using namespace std;
  34. using namespace httplib;
  35. const char *HOST = "localhost";
  36. const int PORT = 1234;
  37. const string LONG_QUERY_VALUE = string(25000, '@');
  38. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  39. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  40. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  41. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  42. const char *key) {
  43. auto it = std::find_if(
  44. files.begin(), files.end(),
  45. [&](const MultipartFormData &file) { return file.name == key; });
  46. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  47. return *it;
  48. #else
  49. if (it != files.end()) { return *it; }
  50. throw std::runtime_error("invalid multipart form data name error");
  51. #endif
  52. }
  53. static void read_file(const std::string &path, std::string &out) {
  54. std::ifstream fs(path, std::ios_base::binary);
  55. if (!fs) throw std::runtime_error("File not found: " + path);
  56. fs.seekg(0, std::ios_base::end);
  57. auto size = fs.tellg();
  58. fs.seekg(0);
  59. out.resize(static_cast<size_t>(size));
  60. fs.read(&out[0], static_cast<std::streamsize>(size));
  61. }
  62. class UnixSocketTest : public ::testing::Test {
  63. protected:
  64. void TearDown() override { std::remove(pathname_.c_str()); }
  65. void client_GET(const std::string &addr) {
  66. httplib::Client cli{addr};
  67. cli.set_address_family(AF_UNIX);
  68. ASSERT_TRUE(cli.is_valid());
  69. const auto &result = cli.Get(pattern_);
  70. ASSERT_TRUE(result) << "error: " << result.error();
  71. const auto &resp = result.value();
  72. EXPECT_EQ(resp.status, StatusCode::OK_200);
  73. EXPECT_EQ(resp.body, content_);
  74. }
  75. const std::string pathname_{"./httplib-server.sock"};
  76. const std::string pattern_{"/hi"};
  77. const std::string content_{"Hello World!"};
  78. };
  79. TEST_F(UnixSocketTest, pathname) {
  80. httplib::Server svr;
  81. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  82. res.set_content(content_, "text/plain");
  83. });
  84. std::thread t{[&] {
  85. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  86. }};
  87. auto se = detail::scope_exit([&] {
  88. svr.stop();
  89. t.join();
  90. ASSERT_FALSE(svr.is_running());
  91. });
  92. svr.wait_until_ready();
  93. ASSERT_TRUE(svr.is_running());
  94. client_GET(pathname_);
  95. }
  96. #if defined(__linux__) || \
  97. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  98. TEST_F(UnixSocketTest, PeerPid) {
  99. httplib::Server svr;
  100. std::string remote_port_val;
  101. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  102. res.set_content(content_, "text/plain");
  103. remote_port_val = req.get_header_value("REMOTE_PORT");
  104. });
  105. std::thread t{[&] {
  106. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  107. }};
  108. auto se = detail::scope_exit([&] {
  109. svr.stop();
  110. t.join();
  111. ASSERT_FALSE(svr.is_running());
  112. });
  113. svr.wait_until_ready();
  114. ASSERT_TRUE(svr.is_running());
  115. client_GET(pathname_);
  116. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  117. }
  118. #endif
  119. #ifdef __linux__
  120. TEST_F(UnixSocketTest, abstract) {
  121. constexpr char svr_path[]{"\x00httplib-server.sock"};
  122. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  123. httplib::Server svr;
  124. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  125. res.set_content(content_, "text/plain");
  126. });
  127. std::thread t{[&] {
  128. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  129. }};
  130. auto se = detail::scope_exit([&] {
  131. svr.stop();
  132. t.join();
  133. ASSERT_FALSE(svr.is_running());
  134. });
  135. svr.wait_until_ready();
  136. ASSERT_TRUE(svr.is_running());
  137. client_GET(abstract_addr);
  138. }
  139. #endif
  140. #ifndef _WIN32
  141. TEST(SocketStream, wait_writable_UNIX) {
  142. int fds[2];
  143. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  144. const auto asSocketStream = [&](socket_t fd,
  145. std::function<bool(Stream &)> func) {
  146. return detail::process_client_socket(
  147. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  148. };
  149. asSocketStream(fds[0], [&](Stream &s0) {
  150. EXPECT_EQ(s0.socket(), fds[0]);
  151. EXPECT_TRUE(s0.wait_writable());
  152. EXPECT_EQ(0, close(fds[1]));
  153. EXPECT_FALSE(s0.wait_writable());
  154. return true;
  155. });
  156. EXPECT_EQ(0, close(fds[0]));
  157. }
  158. TEST(SocketStream, wait_writable_INET) {
  159. sockaddr_in addr;
  160. memset(&addr, 0, sizeof(addr));
  161. addr.sin_family = AF_INET;
  162. addr.sin_port = htons(PORT + 1);
  163. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  164. int disconnected_svr_sock = -1;
  165. std::thread svr{[&] {
  166. const int s = socket(AF_INET, SOCK_STREAM, 0);
  167. ASSERT_LE(0, s);
  168. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  169. ASSERT_EQ(0, listen(s, 1));
  170. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  171. ASSERT_EQ(0, close(s));
  172. }};
  173. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  174. std::thread cli{[&] {
  175. const int s = socket(AF_INET, SOCK_STREAM, 0);
  176. ASSERT_LE(0, s);
  177. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. cli.join();
  181. svr.join();
  182. ASSERT_NE(disconnected_svr_sock, -1);
  183. const auto asSocketStream = [&](socket_t fd,
  184. std::function<bool(Stream &)> func) {
  185. return detail::process_client_socket(
  186. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  187. };
  188. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  189. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  190. EXPECT_FALSE(ss.wait_writable());
  191. return true;
  192. });
  193. ASSERT_EQ(0, close(disconnected_svr_sock));
  194. }
  195. #endif // #ifndef _WIN32
  196. TEST(ClientTest, MoveConstructible) {
  197. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  198. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  199. }
  200. TEST(ClientTest, MoveAssignable) {
  201. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  202. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  203. }
  204. #ifdef _WIN32
  205. TEST(StartupTest, WSAStartup) {
  206. WSADATA wsaData;
  207. int ret = WSAStartup(0x0002, &wsaData);
  208. ASSERT_EQ(0, ret);
  209. }
  210. #endif
  211. TEST(DecodeURLTest, PercentCharacter) {
  212. EXPECT_EQ(
  213. detail::decode_url(
  214. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  215. false),
  216. u8"descrip=Gastos áéíóúñÑ 6");
  217. }
  218. TEST(DecodeURLTest, PercentCharacterNUL) {
  219. string expected;
  220. expected.push_back('x');
  221. expected.push_back('\0');
  222. expected.push_back('x');
  223. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  224. }
  225. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  226. string unescapedCharacters = "-_.!~*'()";
  227. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  228. }
  229. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  230. string reservedCharacters = ";,/?:@&=+$";
  231. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  232. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  233. }
  234. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  235. string chineseCharacters = u8"中国語";
  236. string russianCharacters = u8"дом";
  237. string brazilianCharacters = u8"óculos";
  238. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  239. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  240. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  241. "%D0%B4%D0%BE%D0%BC");
  242. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  243. }
  244. TEST(TrimTests, TrimStringTests) {
  245. EXPECT_EQ("abc", detail::trim_copy("abc"));
  246. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  247. EXPECT_TRUE(detail::trim_copy("").empty());
  248. }
  249. TEST(DivideTest, DivideStringTests) {
  250. auto divide = [](const std::string &str, char d) {
  251. std::string lhs;
  252. std::string rhs;
  253. detail::divide(str, d,
  254. [&](const char *lhs_data, std::size_t lhs_size,
  255. const char *rhs_data, std::size_t rhs_size) {
  256. lhs.assign(lhs_data, lhs_size);
  257. rhs.assign(rhs_data, rhs_size);
  258. });
  259. return std::make_pair(std::move(lhs), std::move(rhs));
  260. };
  261. {
  262. const auto res = divide("", '=');
  263. EXPECT_EQ(res.first, "");
  264. EXPECT_EQ(res.second, "");
  265. }
  266. {
  267. const auto res = divide("=", '=');
  268. EXPECT_EQ(res.first, "");
  269. EXPECT_EQ(res.second, "");
  270. }
  271. {
  272. const auto res = divide(" ", '=');
  273. EXPECT_EQ(res.first, " ");
  274. EXPECT_EQ(res.second, "");
  275. }
  276. {
  277. const auto res = divide("a", '=');
  278. EXPECT_EQ(res.first, "a");
  279. EXPECT_EQ(res.second, "");
  280. }
  281. {
  282. const auto res = divide("a=", '=');
  283. EXPECT_EQ(res.first, "a");
  284. EXPECT_EQ(res.second, "");
  285. }
  286. {
  287. const auto res = divide("=b", '=');
  288. EXPECT_EQ(res.first, "");
  289. EXPECT_EQ(res.second, "b");
  290. }
  291. {
  292. const auto res = divide("a=b", '=');
  293. EXPECT_EQ(res.first, "a");
  294. EXPECT_EQ(res.second, "b");
  295. }
  296. {
  297. const auto res = divide("a=b=", '=');
  298. EXPECT_EQ(res.first, "a");
  299. EXPECT_EQ(res.second, "b=");
  300. }
  301. {
  302. const auto res = divide("a=b=c", '=');
  303. EXPECT_EQ(res.first, "a");
  304. EXPECT_EQ(res.second, "b=c");
  305. }
  306. }
  307. TEST(SplitTest, ParseQueryString) {
  308. string s = "key1=val1&key2=val2&key3=val3";
  309. Params dic;
  310. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  311. [&](const char *b, const char *e) {
  312. string key, val;
  313. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  314. if (key.empty()) {
  315. key.assign(b2, e2);
  316. } else {
  317. val.assign(b2, e2);
  318. }
  319. });
  320. dic.emplace(key, val);
  321. });
  322. EXPECT_EQ("val1", dic.find("key1")->second);
  323. EXPECT_EQ("val2", dic.find("key2")->second);
  324. EXPECT_EQ("val3", dic.find("key3")->second);
  325. }
  326. TEST(SplitTest, ParseInvalidQueryTests) {
  327. {
  328. string s = " ";
  329. Params dict;
  330. detail::parse_query_text(s, dict);
  331. EXPECT_TRUE(dict.empty());
  332. }
  333. {
  334. string s = " = =";
  335. Params dict;
  336. detail::parse_query_text(s, dict);
  337. EXPECT_TRUE(dict.empty());
  338. }
  339. }
  340. TEST(ParseQueryTest, ParseQueryString) {
  341. {
  342. std::string s = "key1=val1&key2=val2&key3=val3";
  343. Params dic;
  344. detail::parse_query_text(s, dic);
  345. EXPECT_EQ("val1", dic.find("key1")->second);
  346. EXPECT_EQ("val2", dic.find("key2")->second);
  347. EXPECT_EQ("val3", dic.find("key3")->second);
  348. }
  349. {
  350. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  351. Params dic;
  352. detail::parse_query_text(s, dic);
  353. EXPECT_EQ("", dic.find("key1")->second);
  354. EXPECT_EQ("val1", dic.find("key2")->second);
  355. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  356. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  357. }
  358. }
  359. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  360. Params dic;
  361. EXPECT_EQ(detail::params_to_query_str(dic), "");
  362. dic.emplace("key1", "val1");
  363. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  364. dic.emplace("key2", "val2");
  365. dic.emplace("key3", "val3");
  366. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  367. }
  368. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  369. string content_type = "multipart/form-data; boundary=something";
  370. string boundary;
  371. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  372. EXPECT_TRUE(ret);
  373. EXPECT_EQ(boundary, "something");
  374. }
  375. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  376. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  377. string boundary;
  378. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  379. EXPECT_TRUE(ret);
  380. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  381. }
  382. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  383. string content_type =
  384. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  385. string boundary;
  386. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  387. EXPECT_TRUE(ret);
  388. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  389. }
  390. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  391. string content_type =
  392. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  393. string boundary;
  394. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  395. EXPECT_TRUE(ret);
  396. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  397. }
  398. TEST(GetHeaderValueTest, DefaultValue) {
  399. Headers headers = {{"Dummy", "Dummy"}};
  400. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  401. EXPECT_STREQ("text/plain", val);
  402. }
  403. TEST(GetHeaderValueTest, DefaultValueInt) {
  404. Headers headers = {{"Dummy", "Dummy"}};
  405. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  406. EXPECT_EQ(100ull, val);
  407. }
  408. TEST(GetHeaderValueTest, RegularValue) {
  409. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  410. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  411. EXPECT_STREQ("text/html", val);
  412. }
  413. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  414. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  415. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  416. EXPECT_STREQ("text/html", val);
  417. }
  418. TEST(GetHeaderValueTest, SetContent) {
  419. Response res;
  420. res.set_content("html", "text/html");
  421. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  422. res.set_content("text", "text/plain");
  423. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  424. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  425. }
  426. TEST(GetHeaderValueTest, RegularValueInt) {
  427. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  428. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  429. EXPECT_EQ(100ull, val);
  430. }
  431. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  432. Headers headers = {{"Content-Length", "x"}};
  433. auto is_invalid_value = false;
  434. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  435. is_invalid_value);
  436. EXPECT_EQ(0ull, val);
  437. EXPECT_TRUE(is_invalid_value);
  438. }
  439. TEST(GetHeaderValueTest, Range) {
  440. {
  441. Headers headers = {make_range_header({{1, -1}})};
  442. auto val = detail::get_header_value(headers, "Range", 0, 0);
  443. EXPECT_STREQ("bytes=1-", val);
  444. }
  445. {
  446. Headers headers = {make_range_header({{-1, 1}})};
  447. auto val = detail::get_header_value(headers, "Range", 0, 0);
  448. EXPECT_STREQ("bytes=-1", val);
  449. }
  450. {
  451. Headers headers = {make_range_header({{1, 10}})};
  452. auto val = detail::get_header_value(headers, "Range", 0, 0);
  453. EXPECT_STREQ("bytes=1-10", val);
  454. }
  455. {
  456. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  457. auto val = detail::get_header_value(headers, "Range", 0, 0);
  458. EXPECT_STREQ("bytes=1-10, 100-", val);
  459. }
  460. {
  461. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  462. auto val = detail::get_header_value(headers, "Range", 0, 0);
  463. EXPECT_STREQ("bytes=1-10, 100-200", val);
  464. }
  465. {
  466. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  467. auto val = detail::get_header_value(headers, "Range", 0, 0);
  468. EXPECT_STREQ("bytes=0-0, -1", val);
  469. }
  470. }
  471. TEST(ParseHeaderValueTest, Range) {
  472. {
  473. Ranges ranges;
  474. auto ret = detail::parse_range_header("bytes=1-", ranges);
  475. EXPECT_TRUE(ret);
  476. EXPECT_EQ(1u, ranges.size());
  477. EXPECT_EQ(1u, ranges[0].first);
  478. EXPECT_EQ(-1, ranges[0].second);
  479. }
  480. {
  481. Ranges ranges;
  482. auto ret = detail::parse_range_header("bytes=-1", ranges);
  483. EXPECT_TRUE(ret);
  484. EXPECT_EQ(1u, ranges.size());
  485. EXPECT_EQ(-1, ranges[0].first);
  486. EXPECT_EQ(1u, ranges[0].second);
  487. }
  488. {
  489. Ranges ranges;
  490. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  491. EXPECT_TRUE(ret);
  492. EXPECT_EQ(1u, ranges.size());
  493. EXPECT_EQ(1u, ranges[0].first);
  494. EXPECT_EQ(10u, ranges[0].second);
  495. }
  496. {
  497. Ranges ranges;
  498. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  499. EXPECT_FALSE(ret);
  500. }
  501. {
  502. Ranges ranges;
  503. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  504. EXPECT_TRUE(ret);
  505. EXPECT_EQ(2u, ranges.size());
  506. EXPECT_EQ(1u, ranges[0].first);
  507. EXPECT_EQ(10u, ranges[0].second);
  508. EXPECT_EQ(100u, ranges[1].first);
  509. EXPECT_EQ(-1, ranges[1].second);
  510. }
  511. {
  512. Ranges ranges;
  513. auto ret =
  514. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  515. EXPECT_TRUE(ret);
  516. EXPECT_EQ(3u, ranges.size());
  517. EXPECT_EQ(1u, ranges[0].first);
  518. EXPECT_EQ(10u, ranges[0].second);
  519. EXPECT_EQ(100u, ranges[1].first);
  520. EXPECT_EQ(200u, ranges[1].second);
  521. EXPECT_EQ(300u, ranges[2].first);
  522. EXPECT_EQ(400u, ranges[2].second);
  523. }
  524. {
  525. Ranges ranges;
  526. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  527. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  528. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  529. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  530. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  531. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  532. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  533. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  534. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  535. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  536. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  537. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  538. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  539. EXPECT_TRUE(ranges.empty());
  540. }
  541. }
  542. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  543. Request req;
  544. req.set_header("Accept-Encoding", "gzip");
  545. Response res;
  546. res.set_header("Content-Type", "text/plain");
  547. auto ret = detail::encoding_type(req, res);
  548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  549. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  550. #else
  551. EXPECT_TRUE(ret == detail::EncodingType::None);
  552. #endif
  553. }
  554. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  555. Request req;
  556. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  557. Response res;
  558. res.set_header("Content-Type", "text/plain");
  559. auto ret = detail::encoding_type(req, res);
  560. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  561. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  562. #elif CPPHTTPLIB_ZLIB_SUPPORT
  563. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  564. #elif CPPHTTPLIB_ZSTD_SUPPORT
  565. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  566. #else
  567. EXPECT_TRUE(ret == detail::EncodingType::None);
  568. #endif
  569. }
  570. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  571. Request req;
  572. req.set_header("Accept-Encoding",
  573. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  574. Response res;
  575. res.set_header("Content-Type", "text/plain");
  576. auto ret = detail::encoding_type(req, res);
  577. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  578. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  579. #elif CPPHTTPLIB_ZLIB_SUPPORT
  580. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  581. #elif CPPHTTPLIB_ZSTD_SUPPORT
  582. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  583. #else
  584. EXPECT_TRUE(ret == detail::EncodingType::None);
  585. #endif
  586. }
  587. TEST(BufferStreamTest, read) {
  588. detail::BufferStream strm1;
  589. Stream &strm = strm1;
  590. EXPECT_EQ(5, strm.write("hello"));
  591. char buf[512];
  592. EXPECT_EQ(2, strm.read(buf, 2));
  593. EXPECT_EQ('h', buf[0]);
  594. EXPECT_EQ('e', buf[1]);
  595. EXPECT_EQ(2, strm.read(buf, 2));
  596. EXPECT_EQ('l', buf[0]);
  597. EXPECT_EQ('l', buf[1]);
  598. EXPECT_EQ(1, strm.read(buf, 1));
  599. EXPECT_EQ('o', buf[0]);
  600. EXPECT_EQ(0, strm.read(buf, 1));
  601. }
  602. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  603. auto host = "www.httpwatch.com";
  604. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  605. auto port = 443;
  606. SSLClient cli(host, port);
  607. #else
  608. auto port = 80;
  609. Client cli(host, port);
  610. #endif
  611. cli.set_connection_timeout(2);
  612. auto res =
  613. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  614. ASSERT_TRUE(res);
  615. std::string out;
  616. read_file("./image.jpg", out);
  617. EXPECT_EQ(StatusCode::OK_200, res->status);
  618. EXPECT_EQ(out, res->body);
  619. }
  620. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  621. auto host = "www.httpwatch.com";
  622. auto ip = hosted_at(host);
  623. EXPECT_EQ("23.96.13.243", ip);
  624. std::vector<std::string> addrs;
  625. hosted_at(host, addrs);
  626. EXPECT_EQ(1u, addrs.size());
  627. }
  628. #if 0 // It depends on each test environment...
  629. TEST(HostnameToIPConversionTest, YouTube_Online) {
  630. auto host = "www.youtube.com";
  631. std::vector<std::string> addrs;
  632. hosted_at(host, addrs);
  633. EXPECT_EQ(20u, addrs.size());
  634. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  635. EXPECT_TRUE(it != addrs.end());
  636. }
  637. #endif
  638. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  639. auto host = "www.httpwatch.com";
  640. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  641. auto port = 443;
  642. SSLClient cli(host, port);
  643. #else
  644. auto port = 80;
  645. Client cli(host, port);
  646. #endif
  647. cli.set_connection_timeout(2);
  648. std::string body;
  649. auto res =
  650. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  651. [&](const char *data, size_t data_length) {
  652. body.append(data, data_length);
  653. return true;
  654. });
  655. ASSERT_TRUE(res);
  656. std::string out;
  657. read_file("./image.jpg", out);
  658. EXPECT_EQ(StatusCode::OK_200, res->status);
  659. EXPECT_EQ(out, body);
  660. }
  661. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  662. auto host = "www.httpwatch.com";
  663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  664. auto port = 443;
  665. SSLClient cli(host, port);
  666. #else
  667. auto port = 80;
  668. Client cli(host, port);
  669. #endif
  670. cli.set_connection_timeout(2);
  671. std::string body;
  672. auto res = cli.Get(
  673. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  674. [&](const Response &response) {
  675. EXPECT_EQ(StatusCode::OK_200, response.status);
  676. return true;
  677. },
  678. [&](const char *data, size_t data_length) {
  679. body.append(data, data_length);
  680. return true;
  681. });
  682. ASSERT_TRUE(res);
  683. std::string out;
  684. read_file("./image.jpg", out);
  685. EXPECT_EQ(StatusCode::OK_200, res->status);
  686. EXPECT_EQ(out, body);
  687. }
  688. TEST(RangeTest, FromHTTPBin_Online) {
  689. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  690. auto host = "httpbin.org";
  691. auto path = std::string{"/range/32"};
  692. #else
  693. auto host = "nghttp2.org";
  694. auto path = std::string{"/httpbin/range/32"};
  695. #endif
  696. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  697. auto port = 443;
  698. SSLClient cli(host, port);
  699. #else
  700. auto port = 80;
  701. Client cli(host, port);
  702. #endif
  703. cli.set_connection_timeout(5);
  704. {
  705. auto res = cli.Get(path);
  706. ASSERT_TRUE(res);
  707. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  708. EXPECT_EQ(StatusCode::OK_200, res->status);
  709. }
  710. {
  711. Headers headers = {make_range_header({{1, -1}})};
  712. auto res = cli.Get(path, headers);
  713. ASSERT_TRUE(res);
  714. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  716. }
  717. {
  718. Headers headers = {make_range_header({{1, 10}})};
  719. auto res = cli.Get(path, headers);
  720. ASSERT_TRUE(res);
  721. EXPECT_EQ("bcdefghijk", res->body);
  722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  723. }
  724. {
  725. Headers headers = {make_range_header({{0, 31}})};
  726. auto res = cli.Get(path, headers);
  727. ASSERT_TRUE(res);
  728. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  729. EXPECT_EQ(StatusCode::OK_200, res->status);
  730. }
  731. {
  732. Headers headers = {make_range_header({{0, -1}})};
  733. auto res = cli.Get(path, headers);
  734. ASSERT_TRUE(res);
  735. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  736. EXPECT_EQ(StatusCode::OK_200, res->status);
  737. }
  738. {
  739. Headers headers = {make_range_header({{0, 32}})};
  740. auto res = cli.Get(path, headers);
  741. ASSERT_TRUE(res);
  742. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  743. }
  744. }
  745. TEST(ConnectionErrorTest, InvalidHost) {
  746. auto host = "-abcde.com";
  747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  748. auto port = 443;
  749. SSLClient cli(host, port);
  750. #else
  751. auto port = 80;
  752. Client cli(host, port);
  753. #endif
  754. cli.set_connection_timeout(std::chrono::seconds(2));
  755. auto res = cli.Get("/");
  756. ASSERT_TRUE(!res);
  757. EXPECT_EQ(Error::Connection, res.error());
  758. }
  759. TEST(ConnectionErrorTest, InvalidHost2) {
  760. auto host = "httpbin.org/";
  761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  762. SSLClient cli(host);
  763. #else
  764. Client cli(host);
  765. #endif
  766. cli.set_connection_timeout(std::chrono::seconds(2));
  767. auto res = cli.Get("/");
  768. ASSERT_TRUE(!res);
  769. EXPECT_EQ(Error::Connection, res.error());
  770. }
  771. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  772. auto host = "httpbin.org/";
  773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  774. SSLClient cli(host);
  775. #else
  776. Client cli(host);
  777. #endif
  778. cli.set_connection_timeout(std::chrono::seconds(2));
  779. auto res = cli.Get("/");
  780. ASSERT_TRUE(!res);
  781. stringstream s;
  782. s << "error code: " << res.error();
  783. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  784. }
  785. TEST(ConnectionErrorTest, InvalidPort) {
  786. auto host = "localhost";
  787. auto port = 44380;
  788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  789. SSLClient cli(host, port);
  790. #else
  791. Client cli(host, port);
  792. #endif
  793. cli.set_connection_timeout(std::chrono::seconds(2));
  794. auto res = cli.Get("/");
  795. ASSERT_TRUE(!res);
  796. EXPECT_TRUE(Error::Connection == res.error() ||
  797. Error::ConnectionTimeout == res.error());
  798. }
  799. TEST(ConnectionErrorTest, Timeout_Online) {
  800. auto host = "google.com";
  801. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  802. auto port = 44380;
  803. SSLClient cli(host, port);
  804. #else
  805. auto port = 8080;
  806. Client cli(host, port);
  807. #endif
  808. cli.set_connection_timeout(std::chrono::seconds(2));
  809. // only probe one address type so that the error reason
  810. // correlates to the timed-out IPv4, not the unsupported
  811. // IPv6 connection attempt
  812. cli.set_address_family(AF_INET);
  813. auto res = cli.Get("/");
  814. ASSERT_TRUE(!res);
  815. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  816. }
  817. TEST(CancelTest, NoCancel_Online) {
  818. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  819. auto host = "httpbin.org";
  820. auto path = std::string{"/range/32"};
  821. #else
  822. auto host = "nghttp2.org";
  823. auto path = std::string{"/httpbin/range/32"};
  824. #endif
  825. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  826. auto port = 443;
  827. SSLClient cli(host, port);
  828. #else
  829. auto port = 80;
  830. Client cli(host, port);
  831. #endif
  832. cli.set_connection_timeout(std::chrono::seconds(5));
  833. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  834. ASSERT_TRUE(res);
  835. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  836. EXPECT_EQ(StatusCode::OK_200, res->status);
  837. }
  838. TEST(CancelTest, WithCancelSmallPayload_Online) {
  839. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  840. auto host = "httpbin.org";
  841. auto path = std::string{"/range/32"};
  842. #else
  843. auto host = "nghttp2.org";
  844. auto path = std::string{"/httpbin/range/32"};
  845. #endif
  846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  847. auto port = 443;
  848. SSLClient cli(host, port);
  849. #else
  850. auto port = 80;
  851. Client cli(host, port);
  852. #endif
  853. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  854. cli.set_connection_timeout(std::chrono::seconds(5));
  855. ASSERT_TRUE(!res);
  856. EXPECT_EQ(Error::Canceled, res.error());
  857. }
  858. TEST(CancelTest, WithCancelLargePayload_Online) {
  859. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  860. auto host = "httpbin.org";
  861. auto path = std::string{"/range/65536"};
  862. #else
  863. auto host = "nghttp2.org";
  864. auto path = std::string{"/httpbin/range/65536"};
  865. #endif
  866. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  867. auto port = 443;
  868. SSLClient cli(host, port);
  869. #else
  870. auto port = 80;
  871. Client cli(host, port);
  872. #endif
  873. cli.set_connection_timeout(std::chrono::seconds(5));
  874. uint32_t count = 0;
  875. auto res =
  876. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  877. ASSERT_TRUE(!res);
  878. EXPECT_EQ(Error::Canceled, res.error());
  879. }
  880. TEST(CancelTest, NoCancelPost) {
  881. Server svr;
  882. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  883. res.set_content("Hello World!", "text/plain");
  884. });
  885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  886. auto se = detail::scope_exit([&] {
  887. svr.stop();
  888. thread.join();
  889. ASSERT_FALSE(svr.is_running());
  890. });
  891. svr.wait_until_ready();
  892. Client cli(HOST, PORT);
  893. cli.set_connection_timeout(std::chrono::seconds(5));
  894. auto res =
  895. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  896. "application/json", [](uint64_t, uint64_t) { return true; });
  897. ASSERT_TRUE(res);
  898. EXPECT_EQ("Hello World!", res->body);
  899. EXPECT_EQ(StatusCode::OK_200, res->status);
  900. }
  901. TEST(CancelTest, WithCancelSmallPayloadPost) {
  902. Server svr;
  903. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  904. res.set_content("Hello World!", "text/plain");
  905. });
  906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  907. auto se = detail::scope_exit([&] {
  908. svr.stop();
  909. thread.join();
  910. ASSERT_FALSE(svr.is_running());
  911. });
  912. svr.wait_until_ready();
  913. Client cli(HOST, PORT);
  914. cli.set_connection_timeout(std::chrono::seconds(5));
  915. auto res =
  916. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  917. "application/json", [](uint64_t, uint64_t) { return false; });
  918. ASSERT_TRUE(!res);
  919. EXPECT_EQ(Error::Canceled, res.error());
  920. }
  921. TEST(CancelTest, WithCancelLargePayloadPost) {
  922. Server svr;
  923. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  924. res.set_content(LARGE_DATA, "text/plain");
  925. });
  926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  927. auto se = detail::scope_exit([&] {
  928. svr.stop();
  929. thread.join();
  930. ASSERT_FALSE(svr.is_running());
  931. });
  932. svr.wait_until_ready();
  933. Client cli(HOST, PORT);
  934. cli.set_connection_timeout(std::chrono::seconds(5));
  935. auto res =
  936. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  937. "application/json", [](uint64_t, uint64_t) { return false; });
  938. ASSERT_TRUE(!res);
  939. EXPECT_EQ(Error::Canceled, res.error());
  940. }
  941. TEST(CancelTest, NoCancelPut) {
  942. Server svr;
  943. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  944. res.set_content("Hello World!", "text/plain");
  945. });
  946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  947. auto se = detail::scope_exit([&] {
  948. svr.stop();
  949. thread.join();
  950. ASSERT_FALSE(svr.is_running());
  951. });
  952. svr.wait_until_ready();
  953. Client cli(HOST, PORT);
  954. cli.set_connection_timeout(std::chrono::seconds(5));
  955. auto res =
  956. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  957. "application/json", [](uint64_t, uint64_t) { return true; });
  958. ASSERT_TRUE(res);
  959. EXPECT_EQ("Hello World!", res->body);
  960. EXPECT_EQ(StatusCode::OK_200, res->status);
  961. }
  962. TEST(CancelTest, WithCancelSmallPayloadPut) {
  963. Server svr;
  964. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  965. res.set_content("Hello World!", "text/plain");
  966. });
  967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  968. auto se = detail::scope_exit([&] {
  969. svr.stop();
  970. thread.join();
  971. ASSERT_FALSE(svr.is_running());
  972. });
  973. svr.wait_until_ready();
  974. Client cli(HOST, PORT);
  975. cli.set_connection_timeout(std::chrono::seconds(5));
  976. auto res =
  977. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  978. "application/json", [](uint64_t, uint64_t) { return false; });
  979. ASSERT_TRUE(!res);
  980. EXPECT_EQ(Error::Canceled, res.error());
  981. }
  982. TEST(CancelTest, WithCancelLargePayloadPut) {
  983. Server svr;
  984. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  985. res.set_content(LARGE_DATA, "text/plain");
  986. });
  987. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. thread.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. Client cli(HOST, PORT);
  995. cli.set_connection_timeout(std::chrono::seconds(5));
  996. auto res =
  997. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  998. "application/json", [](uint64_t, uint64_t) { return false; });
  999. ASSERT_TRUE(!res);
  1000. EXPECT_EQ(Error::Canceled, res.error());
  1001. }
  1002. TEST(CancelTest, NoCancelPatch) {
  1003. Server svr;
  1004. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1005. res.set_content("Hello World!", "text/plain");
  1006. });
  1007. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1008. auto se = detail::scope_exit([&] {
  1009. svr.stop();
  1010. thread.join();
  1011. ASSERT_FALSE(svr.is_running());
  1012. });
  1013. svr.wait_until_ready();
  1014. Client cli(HOST, PORT);
  1015. cli.set_connection_timeout(std::chrono::seconds(5));
  1016. auto res =
  1017. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1018. "application/json", [](uint64_t, uint64_t) { return true; });
  1019. ASSERT_TRUE(res);
  1020. EXPECT_EQ("Hello World!", res->body);
  1021. EXPECT_EQ(StatusCode::OK_200, res->status);
  1022. }
  1023. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1024. Server svr;
  1025. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1026. res.set_content("Hello World!", "text/plain");
  1027. });
  1028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1029. auto se = detail::scope_exit([&] {
  1030. svr.stop();
  1031. thread.join();
  1032. ASSERT_FALSE(svr.is_running());
  1033. });
  1034. svr.wait_until_ready();
  1035. Client cli(HOST, PORT);
  1036. cli.set_connection_timeout(std::chrono::seconds(5));
  1037. auto res =
  1038. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1039. "application/json", [](uint64_t, uint64_t) { return false; });
  1040. ASSERT_TRUE(!res);
  1041. EXPECT_EQ(Error::Canceled, res.error());
  1042. }
  1043. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1044. Server svr;
  1045. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1046. res.set_content(LARGE_DATA, "text/plain");
  1047. });
  1048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1049. auto se = detail::scope_exit([&] {
  1050. svr.stop();
  1051. thread.join();
  1052. ASSERT_FALSE(svr.is_running());
  1053. });
  1054. svr.wait_until_ready();
  1055. Client cli(HOST, PORT);
  1056. cli.set_connection_timeout(std::chrono::seconds(5));
  1057. auto res =
  1058. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1059. "application/json", [](uint64_t, uint64_t) { return false; });
  1060. ASSERT_TRUE(!res);
  1061. EXPECT_EQ(Error::Canceled, res.error());
  1062. }
  1063. TEST(CancelTest, NoCancelDelete) {
  1064. Server svr;
  1065. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1066. res.set_content("Hello World!", "text/plain");
  1067. });
  1068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1069. auto se = detail::scope_exit([&] {
  1070. svr.stop();
  1071. thread.join();
  1072. ASSERT_FALSE(svr.is_running());
  1073. });
  1074. svr.wait_until_ready();
  1075. Client cli(HOST, PORT);
  1076. cli.set_connection_timeout(std::chrono::seconds(5));
  1077. auto res =
  1078. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1079. "application/json", [](uint64_t, uint64_t) { return true; });
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("Hello World!", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1085. Server svr;
  1086. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1087. res.set_content("Hello World!", "text/plain");
  1088. });
  1089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1090. auto se = detail::scope_exit([&] {
  1091. svr.stop();
  1092. thread.join();
  1093. ASSERT_FALSE(svr.is_running());
  1094. });
  1095. svr.wait_until_ready();
  1096. Client cli(HOST, PORT);
  1097. cli.set_connection_timeout(std::chrono::seconds(5));
  1098. auto res =
  1099. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1100. "application/json", [](uint64_t, uint64_t) { return false; });
  1101. ASSERT_TRUE(!res);
  1102. EXPECT_EQ(Error::Canceled, res.error());
  1103. }
  1104. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1105. Server svr;
  1106. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1107. res.set_content(LARGE_DATA, "text/plain");
  1108. });
  1109. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1110. auto se = detail::scope_exit([&] {
  1111. svr.stop();
  1112. thread.join();
  1113. ASSERT_FALSE(svr.is_running());
  1114. });
  1115. svr.wait_until_ready();
  1116. Client cli(HOST, PORT);
  1117. cli.set_connection_timeout(std::chrono::seconds(5));
  1118. auto res =
  1119. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1120. "application/json", [](uint64_t, uint64_t) { return false; });
  1121. ASSERT_TRUE(!res);
  1122. EXPECT_EQ(Error::Canceled, res.error());
  1123. }
  1124. static std::string remove_whitespace(const std::string &input) {
  1125. std::string output;
  1126. output.reserve(input.size());
  1127. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1128. [](unsigned char c) { return !std::isspace(c); });
  1129. return output;
  1130. }
  1131. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1132. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1133. auto host = "httpbin.org";
  1134. auto path = std::string{"/basic-auth/hello/world"};
  1135. #else
  1136. auto host = "nghttp2.org";
  1137. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1138. #endif
  1139. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1140. auto port = 443;
  1141. SSLClient cli(host, port);
  1142. #else
  1143. auto port = 80;
  1144. Client cli(host, port);
  1145. #endif
  1146. {
  1147. auto res = cli.Get(path);
  1148. ASSERT_TRUE(res);
  1149. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1150. }
  1151. {
  1152. auto res =
  1153. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1156. remove_whitespace(res->body));
  1157. EXPECT_EQ(StatusCode::OK_200, res->status);
  1158. }
  1159. {
  1160. cli.set_basic_auth("hello", "world");
  1161. auto res = cli.Get(path);
  1162. ASSERT_TRUE(res);
  1163. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1164. remove_whitespace(res->body));
  1165. EXPECT_EQ(StatusCode::OK_200, res->status);
  1166. }
  1167. {
  1168. cli.set_basic_auth("hello", "bad");
  1169. auto res = cli.Get(path);
  1170. ASSERT_TRUE(res);
  1171. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1172. }
  1173. {
  1174. cli.set_basic_auth("bad", "world");
  1175. auto res = cli.Get(path);
  1176. ASSERT_TRUE(res);
  1177. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1178. }
  1179. }
  1180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1181. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1182. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1183. auto host = "httpbin.org";
  1184. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1185. auto paths = std::vector<std::string>{
  1186. "/digest-auth/auth/hello/world/MD5",
  1187. "/digest-auth/auth/hello/world/SHA-256",
  1188. "/digest-auth/auth/hello/world/SHA-512",
  1189. "/digest-auth/auth-int/hello/world/MD5",
  1190. };
  1191. #else
  1192. auto host = "nghttp2.org";
  1193. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1194. auto paths = std::vector<std::string>{
  1195. "/httpbin/digest-auth/auth/hello/world/MD5",
  1196. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1197. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1198. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1199. };
  1200. #endif
  1201. auto port = 443;
  1202. SSLClient cli(host, port);
  1203. {
  1204. auto res = cli.Get(unauth_path);
  1205. ASSERT_TRUE(res);
  1206. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1207. }
  1208. {
  1209. cli.set_digest_auth("hello", "world");
  1210. for (const auto &path : paths) {
  1211. auto res = cli.Get(path.c_str());
  1212. ASSERT_TRUE(res);
  1213. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1214. remove_whitespace(res->body));
  1215. EXPECT_EQ(StatusCode::OK_200, res->status);
  1216. }
  1217. cli.set_digest_auth("hello", "bad");
  1218. for (const auto &path : paths) {
  1219. auto res = cli.Get(path.c_str());
  1220. ASSERT_TRUE(res);
  1221. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1222. }
  1223. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1224. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1225. // cli.set_digest_auth("bad", "world");
  1226. // for (const auto& path : paths) {
  1227. // auto res = cli.Get(path.c_str());
  1228. // ASSERT_TRUE(res);
  1229. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1230. // }
  1231. }
  1232. }
  1233. #endif
  1234. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1235. auto host = "google.com";
  1236. auto another_host = "example.com";
  1237. auto wrong_ip = "0.0.0.0";
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(res);
  1246. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1247. }
  1248. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1249. auto host = "google.com";
  1250. auto wrong_ip = "0.0.0.0";
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. SSLClient cli(host);
  1253. #else
  1254. Client cli(host);
  1255. #endif
  1256. cli.set_hostname_addr_map({{host, wrong_ip}});
  1257. auto res = cli.Get("/");
  1258. ASSERT_TRUE(!res);
  1259. EXPECT_EQ(Error::Connection, res.error());
  1260. }
  1261. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1262. auto host = "nghttp2.org";
  1263. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1264. SSLClient cli(host);
  1265. #else
  1266. Client cli(host);
  1267. #endif
  1268. cli.set_follow_location(true);
  1269. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1270. ASSERT_TRUE(res);
  1271. EXPECT_EQ(StatusCode::OK_200, res->status);
  1272. }
  1273. TEST(RedirectTest, Redirect_Online) {
  1274. auto host = "nghttp2.org";
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_follow_location(true);
  1281. auto res = cli.Get("/httpbin/redirect/3");
  1282. ASSERT_TRUE(res);
  1283. EXPECT_EQ(StatusCode::OK_200, res->status);
  1284. }
  1285. TEST(RelativeRedirectTest, Redirect_Online) {
  1286. auto host = "nghttp2.org";
  1287. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1288. SSLClient cli(host);
  1289. #else
  1290. Client cli(host);
  1291. #endif
  1292. cli.set_follow_location(true);
  1293. auto res = cli.Get("/httpbin/relative-redirect/3");
  1294. ASSERT_TRUE(res);
  1295. EXPECT_EQ(StatusCode::OK_200, res->status);
  1296. }
  1297. TEST(TooManyRedirectTest, Redirect_Online) {
  1298. auto host = "nghttp2.org";
  1299. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1300. SSLClient cli(host);
  1301. #else
  1302. Client cli(host);
  1303. #endif
  1304. cli.set_follow_location(true);
  1305. auto res = cli.Get("/httpbin/redirect/21");
  1306. ASSERT_TRUE(!res);
  1307. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1308. }
  1309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1310. TEST(YahooRedirectTest, Redirect_Online) {
  1311. Client cli("yahoo.com");
  1312. auto res = cli.Get("/");
  1313. ASSERT_TRUE(res);
  1314. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1315. cli.set_follow_location(true);
  1316. res = cli.Get("/");
  1317. ASSERT_TRUE(res);
  1318. EXPECT_EQ(StatusCode::OK_200, res->status);
  1319. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1320. }
  1321. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1322. #define REDIR_HOST "httpbingo.org"
  1323. #define REDIR_PATH "/redirect-to"
  1324. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1325. SSLClient cli(REDIR_HOST);
  1326. cli.set_follow_location(true);
  1327. auto res =
  1328. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1329. ASSERT_TRUE(res);
  1330. EXPECT_EQ(StatusCode::OK_200, res->status);
  1331. }
  1332. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1333. SSLClient cli(REDIR_HOST);
  1334. cli.set_follow_location(true);
  1335. Params params;
  1336. params.emplace("url", "http://example.com");
  1337. params.emplace("status_code", "302");
  1338. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1339. ASSERT_TRUE(res);
  1340. EXPECT_EQ(StatusCode::OK_200, res->status);
  1341. }
  1342. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1343. SSLClient cli(REDIR_HOST);
  1344. cli.set_follow_location(true);
  1345. Params params;
  1346. params.emplace("url", "http://example.com");
  1347. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(UrlWithSpace, Redirect_Online) {
  1352. SSLClient cli("edge.forgecdn.net");
  1353. cli.set_follow_location(true);
  1354. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1355. ASSERT_TRUE(res);
  1356. EXPECT_EQ(StatusCode::OK_200, res->status);
  1357. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1358. }
  1359. #endif
  1360. #if !defined(_WIN32) && !defined(_WIN64)
  1361. TEST(ReceiveSignals, Signal) {
  1362. auto setupSignalHandlers = []() {
  1363. struct sigaction act;
  1364. sigemptyset(&act.sa_mask);
  1365. act.sa_flags = SA_SIGINFO;
  1366. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1367. switch (sig) {
  1368. case SIGINT:
  1369. default: break;
  1370. }
  1371. };
  1372. ::sigaction(SIGINT, &act, nullptr);
  1373. };
  1374. Server svr;
  1375. int port = 0;
  1376. auto thread = std::thread([&]() {
  1377. setupSignalHandlers();
  1378. port = svr.bind_to_any_port("localhost");
  1379. svr.listen_after_bind();
  1380. });
  1381. auto se = detail::scope_exit([&] {
  1382. svr.stop();
  1383. thread.join();
  1384. ASSERT_FALSE(svr.is_running());
  1385. });
  1386. svr.wait_until_ready();
  1387. ASSERT_TRUE(svr.is_running());
  1388. pthread_kill(thread.native_handle(), SIGINT);
  1389. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1390. ASSERT_TRUE(svr.is_running());
  1391. }
  1392. #endif
  1393. TEST(RedirectToDifferentPort, Redirect) {
  1394. Server svr1;
  1395. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1396. res.set_content("Hello World!", "text/plain");
  1397. });
  1398. int svr1_port = 0;
  1399. auto thread1 = std::thread([&]() {
  1400. svr1_port = svr1.bind_to_any_port("localhost");
  1401. svr1.listen_after_bind();
  1402. });
  1403. Server svr2;
  1404. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1405. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1406. });
  1407. int svr2_port = 0;
  1408. auto thread2 = std::thread([&]() {
  1409. svr2_port = svr2.bind_to_any_port("localhost");
  1410. svr2.listen_after_bind();
  1411. });
  1412. auto se = detail::scope_exit([&] {
  1413. svr2.stop();
  1414. thread2.join();
  1415. svr1.stop();
  1416. thread1.join();
  1417. ASSERT_FALSE(svr2.is_running());
  1418. ASSERT_FALSE(svr1.is_running());
  1419. });
  1420. svr1.wait_until_ready();
  1421. svr2.wait_until_ready();
  1422. Client cli("localhost", svr2_port);
  1423. cli.set_follow_location(true);
  1424. auto res = cli.Get("/2");
  1425. ASSERT_TRUE(res);
  1426. EXPECT_EQ(StatusCode::OK_200, res->status);
  1427. EXPECT_EQ("Hello World!", res->body);
  1428. }
  1429. TEST(RedirectFromPageWithContent, Redirect) {
  1430. Server svr;
  1431. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("___", "text/plain");
  1433. res.set_redirect("/2");
  1434. });
  1435. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1436. res.set_content("Hello World!", "text/plain");
  1437. });
  1438. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. th.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. {
  1446. Client cli("localhost", PORT);
  1447. cli.set_follow_location(true);
  1448. std::string body;
  1449. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1450. body.append(data, data_length);
  1451. return true;
  1452. });
  1453. ASSERT_TRUE(res);
  1454. EXPECT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_EQ("Hello World!", body);
  1456. }
  1457. {
  1458. Client cli("localhost", PORT);
  1459. std::string body;
  1460. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1461. body.append(data, data_length);
  1462. return true;
  1463. });
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ(StatusCode::Found_302, res->status);
  1466. EXPECT_EQ("___", body);
  1467. }
  1468. }
  1469. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1470. Server svr;
  1471. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1472. res.set_content("___", "text/plain");
  1473. // res.set_redirect("/2");
  1474. res.set_redirect("http://[::1]:1234/2");
  1475. });
  1476. svr.Get("/2", [&](const Request &req, Response &res) {
  1477. auto host_header = req.headers.find("Host");
  1478. ASSERT_TRUE(host_header != req.headers.end());
  1479. EXPECT_EQ("[::1]:1234", host_header->second);
  1480. res.set_content("Hello World!", "text/plain");
  1481. });
  1482. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. th.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1489. // actually starts anything, so the condition !svr.is_running() will
  1490. // always remain true, and the loop never stops.
  1491. // This basically counts how many milliseconds have passed since the
  1492. // call to svr.listen(), and if after 5 seconds nothing started yet
  1493. // aborts the test.
  1494. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1495. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1496. ASSERT_LT(milliseconds, 5000U);
  1497. }
  1498. {
  1499. Client cli("http://[::1]:1234");
  1500. cli.set_follow_location(true);
  1501. std::string body;
  1502. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1503. body.append(data, data_length);
  1504. return true;
  1505. });
  1506. ASSERT_TRUE(res);
  1507. EXPECT_EQ(StatusCode::OK_200, res->status);
  1508. EXPECT_EQ("Hello World!", body);
  1509. }
  1510. {
  1511. Client cli("http://[::1]:1234");
  1512. std::string body;
  1513. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1514. body.append(data, data_length);
  1515. return true;
  1516. });
  1517. ASSERT_TRUE(res);
  1518. EXPECT_EQ(StatusCode::Found_302, res->status);
  1519. EXPECT_EQ("___", body);
  1520. }
  1521. }
  1522. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1523. Server svr;
  1524. svr.Get("/foo", [](const Request &req, Response &res) {
  1525. auto a = req.params.find("a");
  1526. if (a != req.params.end()) {
  1527. res.set_content((*a).second, "text/plain");
  1528. res.status = StatusCode::OK_200;
  1529. } else {
  1530. res.status = StatusCode::BadRequest_400;
  1531. }
  1532. });
  1533. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1534. auto se = detail::scope_exit([&] {
  1535. svr.stop();
  1536. thread.join();
  1537. ASSERT_FALSE(svr.is_running());
  1538. });
  1539. svr.wait_until_ready();
  1540. {
  1541. Client cli(HOST, PORT);
  1542. cli.set_url_encode(false);
  1543. auto res = cli.Get("/foo?a=explicitly+encoded");
  1544. ASSERT_TRUE(res);
  1545. EXPECT_EQ(StatusCode::OK_200, res->status);
  1546. // This expects it back with a space, as the `+` won't have been
  1547. // url-encoded, and server-side the params get decoded turning `+`
  1548. // into spaces.
  1549. EXPECT_EQ("explicitly encoded", res->body);
  1550. }
  1551. }
  1552. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1553. Server svr;
  1554. svr.Get("/", [](const Request &req, Response &) {
  1555. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1556. });
  1557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1558. auto se = detail::scope_exit([&] {
  1559. svr.stop();
  1560. thread.join();
  1561. ASSERT_FALSE(svr.is_running());
  1562. });
  1563. svr.wait_until_ready();
  1564. {
  1565. Client cli(HOST, PORT);
  1566. cli.set_url_encode(false);
  1567. auto res = cli.Get("/?something=%0A");
  1568. ASSERT_TRUE(res);
  1569. EXPECT_EQ(StatusCode::OK_200, res->status);
  1570. }
  1571. }
  1572. TEST(BindServerTest, DISABLED_BindDualStack) {
  1573. Server svr;
  1574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1575. res.set_content("Hello World!", "text/plain");
  1576. });
  1577. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1578. auto se = detail::scope_exit([&] {
  1579. svr.stop();
  1580. thread.join();
  1581. ASSERT_FALSE(svr.is_running());
  1582. });
  1583. svr.wait_until_ready();
  1584. {
  1585. Client cli("127.0.0.1", PORT);
  1586. auto res = cli.Get("/1");
  1587. ASSERT_TRUE(res);
  1588. EXPECT_EQ(StatusCode::OK_200, res->status);
  1589. EXPECT_EQ("Hello World!", res->body);
  1590. }
  1591. {
  1592. Client cli("::1", PORT);
  1593. auto res = cli.Get("/1");
  1594. ASSERT_TRUE(res);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. EXPECT_EQ("Hello World!", res->body);
  1597. }
  1598. }
  1599. TEST(BindServerTest, BindAndListenSeparately) {
  1600. Server svr;
  1601. int port = svr.bind_to_any_port("0.0.0.0");
  1602. ASSERT_TRUE(svr.is_valid());
  1603. ASSERT_TRUE(port > 0);
  1604. svr.stop();
  1605. }
  1606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1607. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1608. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1609. CLIENT_CA_CERT_DIR);
  1610. int port = svr.bind_to_any_port("0.0.0.0");
  1611. ASSERT_TRUE(svr.is_valid());
  1612. ASSERT_TRUE(port > 0);
  1613. svr.stop();
  1614. }
  1615. #endif
  1616. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1617. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1618. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1619. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1620. int port = svr.bind_to_any_port("0.0.0.0");
  1621. ASSERT_TRUE(svr.is_valid());
  1622. ASSERT_TRUE(port > 0);
  1623. svr.stop();
  1624. }
  1625. #endif
  1626. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1627. X509 *readCertificate(const std::string &strFileName) {
  1628. std::ifstream inStream(strFileName);
  1629. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1630. std::istreambuf_iterator<char>());
  1631. if (strCertPEM.empty()) return (nullptr);
  1632. BIO *pbCert = BIO_new(BIO_s_mem());
  1633. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1634. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1635. BIO_free(pbCert);
  1636. return (pCert);
  1637. }
  1638. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1639. std::ifstream inStream(strFileName);
  1640. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1641. std::istreambuf_iterator<char>());
  1642. if (strPrivateKeyPEM.empty()) return (nullptr);
  1643. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1644. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1645. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1646. BIO_free(pbPrivKey);
  1647. return (pPrivateKey);
  1648. }
  1649. TEST(BindServerTest, UpdateCerts) {
  1650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1651. int port = svr.bind_to_any_port("0.0.0.0");
  1652. ASSERT_TRUE(svr.is_valid());
  1653. ASSERT_TRUE(port > 0);
  1654. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1655. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1656. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1657. ASSERT_TRUE(cert != nullptr);
  1658. ASSERT_TRUE(ca_cert != nullptr);
  1659. ASSERT_TRUE(key != nullptr);
  1660. X509_STORE *cert_store = X509_STORE_new();
  1661. X509_STORE_add_cert(cert_store, ca_cert);
  1662. svr.update_certs(cert, key, cert_store);
  1663. ASSERT_TRUE(svr.is_valid());
  1664. svr.stop();
  1665. X509_free(cert);
  1666. X509_free(ca_cert);
  1667. EVP_PKEY_free(key);
  1668. }
  1669. #endif
  1670. TEST(ErrorHandlerTest, ContentLength) {
  1671. Server svr;
  1672. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1673. res.status = StatusCode::OK_200;
  1674. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1675. "text/html"); // <= Content-Length still 13
  1676. });
  1677. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1678. res.set_content("Hello World!\n", "text/plain");
  1679. res.status = 524;
  1680. });
  1681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1682. auto se = detail::scope_exit([&] {
  1683. svr.stop();
  1684. thread.join();
  1685. ASSERT_FALSE(svr.is_running());
  1686. });
  1687. svr.wait_until_ready();
  1688. {
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1691. ASSERT_TRUE(res);
  1692. EXPECT_EQ(StatusCode::OK_200, res->status);
  1693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1694. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1695. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1696. }
  1697. }
  1698. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1699. TEST(ExceptionTest, WithoutExceptionHandler) {
  1700. Server svr;
  1701. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1702. throw std::runtime_error("exception...");
  1703. });
  1704. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1705. throw std::runtime_error("exception\r\n...");
  1706. });
  1707. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. listen_thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli("localhost", PORT);
  1715. {
  1716. auto res = cli.Get("/exception");
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1719. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1720. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1721. }
  1722. {
  1723. auto res = cli.Get("/unknown");
  1724. ASSERT_TRUE(res);
  1725. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1726. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1727. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1728. }
  1729. }
  1730. TEST(ExceptionTest, WithExceptionHandler) {
  1731. Server svr;
  1732. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1733. std::exception_ptr ep) {
  1734. EXPECT_FALSE(ep == nullptr);
  1735. try {
  1736. std::rethrow_exception(ep);
  1737. } catch (std::exception &e) {
  1738. EXPECT_EQ("abc", std::string(e.what()));
  1739. } catch (...) {}
  1740. res.status = StatusCode::InternalServerError_500;
  1741. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1742. "text/html"); // <= Content-Length still 13 at this point
  1743. });
  1744. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!\n", "text/plain");
  1746. throw std::runtime_error("abc");
  1747. });
  1748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1749. auto se = detail::scope_exit([&] {
  1750. svr.stop();
  1751. thread.join();
  1752. ASSERT_FALSE(svr.is_running());
  1753. });
  1754. svr.wait_until_ready();
  1755. for (size_t i = 0; i < 10; i++) {
  1756. Client cli(HOST, PORT);
  1757. for (size_t j = 0; j < 100; j++) {
  1758. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1761. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1762. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1763. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1764. }
  1765. cli.set_keep_alive(true);
  1766. for (size_t j = 0; j < 100; j++) {
  1767. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1770. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1771. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1772. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1773. }
  1774. }
  1775. }
  1776. TEST(ExceptionTest, AndErrorHandler) {
  1777. Server svr;
  1778. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1779. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1780. });
  1781. svr.set_exception_handler(
  1782. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1783. EXPECT_FALSE(ep == nullptr);
  1784. try {
  1785. std::rethrow_exception(ep);
  1786. } catch (std::exception &e) {
  1787. res.set_content(e.what(), "text/html");
  1788. } catch (...) {}
  1789. res.status = StatusCode::InternalServerError_500;
  1790. });
  1791. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1792. throw std::runtime_error("EXCEPTION");
  1793. });
  1794. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1795. res.set_content("ERROR", "text/html");
  1796. res.status = StatusCode::InternalServerError_500;
  1797. });
  1798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1799. auto se = detail::scope_exit([&] {
  1800. svr.stop();
  1801. thread.join();
  1802. ASSERT_FALSE(svr.is_running());
  1803. });
  1804. svr.wait_until_ready();
  1805. Client cli(HOST, PORT);
  1806. {
  1807. auto res = cli.Get("/exception");
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1810. EXPECT_EQ("EXCEPTION", res->body);
  1811. }
  1812. {
  1813. auto res = cli.Get("/error");
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1816. EXPECT_EQ("ERROR", res->body);
  1817. }
  1818. {
  1819. auto res = cli.Get("/invalid");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1822. EXPECT_EQ("NOT_FOUND", res->body);
  1823. }
  1824. }
  1825. #endif
  1826. TEST(NoContentTest, ContentLength) {
  1827. Server svr;
  1828. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1829. res.status = StatusCode::NoContent_204;
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. {
  1839. Client cli(HOST, PORT);
  1840. auto res = cli.Get("/hi");
  1841. ASSERT_TRUE(res);
  1842. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  1843. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1844. }
  1845. }
  1846. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1849. ASSERT_TRUE(svr.is_valid());
  1850. #else
  1851. Server svr;
  1852. #endif
  1853. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1854. if (req.path == "/routing_handler") {
  1855. res.set_header("PRE_ROUTING", "on");
  1856. res.set_content("Routing Handler", "text/plain");
  1857. return httplib::Server::HandlerResponse::Handled;
  1858. }
  1859. return httplib::Server::HandlerResponse::Unhandled;
  1860. });
  1861. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1862. res.set_content("Error", "text/html");
  1863. });
  1864. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1865. if (req.path == "/routing_handler") {
  1866. res.set_header("POST_ROUTING", "on");
  1867. }
  1868. });
  1869. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1870. res.set_content("Hello World!\n", "text/plain");
  1871. });
  1872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1873. auto se = detail::scope_exit([&] {
  1874. svr.stop();
  1875. thread.join();
  1876. ASSERT_FALSE(svr.is_running());
  1877. });
  1878. svr.wait_until_ready();
  1879. {
  1880. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1881. SSLClient cli(HOST, PORT);
  1882. cli.enable_server_certificate_verification(false);
  1883. #else
  1884. Client cli(HOST, PORT);
  1885. #endif
  1886. auto res = cli.Get("/routing_handler");
  1887. ASSERT_TRUE(res);
  1888. EXPECT_EQ(StatusCode::OK_200, res->status);
  1889. EXPECT_EQ("Routing Handler", res->body);
  1890. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1891. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1892. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1893. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1894. }
  1895. {
  1896. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1897. SSLClient cli(HOST, PORT);
  1898. cli.enable_server_certificate_verification(false);
  1899. #else
  1900. Client cli(HOST, PORT);
  1901. #endif
  1902. auto res = cli.Get("/hi");
  1903. ASSERT_TRUE(res);
  1904. EXPECT_EQ(StatusCode::OK_200, res->status);
  1905. EXPECT_EQ("Hello World!\n", res->body);
  1906. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1907. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1908. }
  1909. {
  1910. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1911. SSLClient cli(HOST, PORT);
  1912. cli.enable_server_certificate_verification(false);
  1913. #else
  1914. Client cli(HOST, PORT);
  1915. #endif
  1916. auto res = cli.Get("/aaa");
  1917. ASSERT_TRUE(res);
  1918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1919. EXPECT_EQ("Error", res->body);
  1920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1922. }
  1923. }
  1924. TEST(InvalidFormatTest, StatusCode) {
  1925. Server svr;
  1926. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1927. res.set_content("Hello World!\n", "text/plain");
  1928. res.status = 9999; // Status should be a three-digit code...
  1929. });
  1930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1931. auto se = detail::scope_exit([&] {
  1932. svr.stop();
  1933. thread.join();
  1934. ASSERT_FALSE(svr.is_running());
  1935. });
  1936. svr.wait_until_ready();
  1937. {
  1938. Client cli(HOST, PORT);
  1939. auto res = cli.Get("/hi");
  1940. ASSERT_FALSE(res);
  1941. }
  1942. }
  1943. TEST(URLFragmentTest, WithFragment) {
  1944. Server svr;
  1945. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1946. EXPECT_TRUE(req.target == "/hi");
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1958. EXPECT_TRUE(res);
  1959. EXPECT_EQ(StatusCode::OK_200, res->status);
  1960. res = cli.Get("/hi%23key1=val1=key2=val2");
  1961. EXPECT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1963. }
  1964. }
  1965. TEST(HeaderWriter, SetHeaderWriter) {
  1966. Server svr;
  1967. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1968. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1969. return detail::write_headers(strm, hdrs);
  1970. });
  1971. svr.Get("/hi", [](const Request &req, Response &res) {
  1972. auto it = req.headers.find("CustomClientHeader");
  1973. EXPECT_TRUE(it != req.headers.end());
  1974. EXPECT_EQ(it->second, "CustomClientValue");
  1975. res.set_content("Hello World!\n", "text/plain");
  1976. });
  1977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1978. auto se = detail::scope_exit([&] {
  1979. svr.stop();
  1980. thread.join();
  1981. ASSERT_FALSE(svr.is_running());
  1982. });
  1983. svr.wait_until_ready();
  1984. {
  1985. Client cli(HOST, PORT);
  1986. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1987. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1988. return detail::write_headers(strm, hdrs);
  1989. });
  1990. auto res = cli.Get("/hi");
  1991. EXPECT_TRUE(res);
  1992. EXPECT_EQ(StatusCode::OK_200, res->status);
  1993. auto it = res->headers.find("CustomServerHeader");
  1994. EXPECT_TRUE(it != res->headers.end());
  1995. EXPECT_EQ(it->second, "CustomServerValue");
  1996. }
  1997. }
  1998. class ServerTest : public ::testing::Test {
  1999. protected:
  2000. ServerTest()
  2001. : cli_(HOST, PORT)
  2002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2003. ,
  2004. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2005. #endif
  2006. {
  2007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2008. cli_.enable_server_certificate_verification(false);
  2009. #endif
  2010. }
  2011. virtual void SetUp() {
  2012. svr_.set_mount_point("/", "./www");
  2013. svr_.set_mount_point("/mount", "./www2");
  2014. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2015. svr_.Get("/hi",
  2016. [&](const Request & /*req*/, Response &res) {
  2017. res.set_content("Hello World!", "text/plain");
  2018. })
  2019. .Get("/file_content",
  2020. [&](const Request & /*req*/, Response &res) {
  2021. res.set_file_content("./www/dir/test.html");
  2022. })
  2023. .Get("/file_content_with_content_type",
  2024. [&](const Request & /*req*/, Response &res) {
  2025. res.set_file_content("./www/file", "text/plain");
  2026. })
  2027. .Get("/invalid_file_content",
  2028. [&](const Request & /*req*/, Response &res) {
  2029. res.set_file_content("./www/dir/invalid_file_path");
  2030. })
  2031. .Get("/http_response_splitting",
  2032. [&](const Request & /*req*/, Response &res) {
  2033. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2034. EXPECT_EQ(0U, res.headers.size());
  2035. EXPECT_FALSE(res.has_header("a"));
  2036. res.set_header("a", "1\nSet-Cookie: a=1");
  2037. EXPECT_EQ(0U, res.headers.size());
  2038. EXPECT_FALSE(res.has_header("a"));
  2039. res.set_header("a", "1\rSet-Cookie: a=1");
  2040. EXPECT_EQ(0U, res.headers.size());
  2041. EXPECT_FALSE(res.has_header("a"));
  2042. res.set_header("a\r\nb", "0");
  2043. EXPECT_EQ(0U, res.headers.size());
  2044. EXPECT_FALSE(res.has_header("a"));
  2045. res.set_header("a\rb", "0");
  2046. EXPECT_EQ(0U, res.headers.size());
  2047. EXPECT_FALSE(res.has_header("a"));
  2048. res.set_header("a\nb", "0");
  2049. EXPECT_EQ(0U, res.headers.size());
  2050. EXPECT_FALSE(res.has_header("a"));
  2051. res.set_redirect("1\r\nSet-Cookie: a=1");
  2052. EXPECT_EQ(0U, res.headers.size());
  2053. EXPECT_FALSE(res.has_header("Location"));
  2054. })
  2055. .Get("/slow",
  2056. [&](const Request & /*req*/, Response &res) {
  2057. std::this_thread::sleep_for(std::chrono::seconds(2));
  2058. res.set_content("slow", "text/plain");
  2059. })
  2060. #if 0
  2061. .Post("/slowpost",
  2062. [&](const Request & /*req*/, Response &res) {
  2063. std::this_thread::sleep_for(std::chrono::seconds(2));
  2064. res.set_content("slow", "text/plain");
  2065. })
  2066. #endif
  2067. .Get("/remote_addr",
  2068. [&](const Request &req, Response &res) {
  2069. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2070. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2071. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2072. EXPECT_EQ(req.remote_port,
  2073. std::stoi(req.get_header_value("REMOTE_PORT")));
  2074. res.set_content(remote_addr.c_str(), "text/plain");
  2075. })
  2076. .Get("/local_addr",
  2077. [&](const Request &req, Response &res) {
  2078. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2079. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2080. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2081. auto local_port = req.get_header_value("LOCAL_PORT");
  2082. EXPECT_EQ(req.local_addr, local_addr);
  2083. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2084. res.set_content(local_addr.append(":").append(local_port),
  2085. "text/plain");
  2086. })
  2087. .Get("/endwith%",
  2088. [&](const Request & /*req*/, Response &res) {
  2089. res.set_content("Hello World!", "text/plain");
  2090. })
  2091. .Get("/a\\+\\+b",
  2092. [&](const Request &req, Response &res) {
  2093. ASSERT_TRUE(req.has_param("a +b"));
  2094. auto val = req.get_param_value("a +b");
  2095. res.set_content(val, "text/plain");
  2096. })
  2097. .Get("/", [&](const Request & /*req*/,
  2098. Response &res) { res.set_redirect("/hi"); })
  2099. .Post("/1",
  2100. [](const Request & /*req*/, Response &res) {
  2101. res.set_redirect("/2", StatusCode::SeeOther_303);
  2102. })
  2103. .Get("/2",
  2104. [](const Request & /*req*/, Response &res) {
  2105. res.set_content("redirected.", "text/plain");
  2106. res.status = StatusCode::OK_200;
  2107. })
  2108. .Post("/person",
  2109. [&](const Request &req, Response &res) {
  2110. if (req.has_param("name") && req.has_param("note")) {
  2111. persons_[req.get_param_value("name")] =
  2112. req.get_param_value("note");
  2113. } else {
  2114. res.status = StatusCode::BadRequest_400;
  2115. }
  2116. })
  2117. .Put("/person",
  2118. [&](const Request &req, Response &res) {
  2119. if (req.has_param("name") && req.has_param("note")) {
  2120. persons_[req.get_param_value("name")] =
  2121. req.get_param_value("note");
  2122. } else {
  2123. res.status = StatusCode::BadRequest_400;
  2124. }
  2125. })
  2126. .Get("/person/(.*)",
  2127. [&](const Request &req, Response &res) {
  2128. string name = req.matches[1];
  2129. if (persons_.find(name) != persons_.end()) {
  2130. auto note = persons_[name];
  2131. res.set_content(note, "text/plain");
  2132. } else {
  2133. res.status = StatusCode::NotFound_404;
  2134. }
  2135. })
  2136. .Post("/x-www-form-urlencoded-json",
  2137. [&](const Request &req, Response &res) {
  2138. auto json = req.get_param_value("json");
  2139. ASSERT_EQ(JSON_DATA, json);
  2140. res.set_content(json, "appliation/json");
  2141. res.status = StatusCode::OK_200;
  2142. })
  2143. .Get("/streamed-chunked",
  2144. [&](const Request & /*req*/, Response &res) {
  2145. res.set_chunked_content_provider(
  2146. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2147. sink.os << "123";
  2148. sink.os << "456";
  2149. sink.os << "789";
  2150. sink.done();
  2151. return true;
  2152. });
  2153. })
  2154. .Get("/streamed-chunked2",
  2155. [&](const Request & /*req*/, Response &res) {
  2156. auto i = new int(0);
  2157. res.set_chunked_content_provider(
  2158. "text/plain",
  2159. [i](size_t /*offset*/, DataSink &sink) {
  2160. switch (*i) {
  2161. case 0: sink.os << "123"; break;
  2162. case 1: sink.os << "456"; break;
  2163. case 2: sink.os << "789"; break;
  2164. case 3: sink.done(); break;
  2165. }
  2166. (*i)++;
  2167. return true;
  2168. },
  2169. [i](bool success) {
  2170. EXPECT_TRUE(success);
  2171. delete i;
  2172. });
  2173. })
  2174. .Get("/streamed-chunked-with-trailer",
  2175. [&](const Request & /*req*/, Response &res) {
  2176. auto i = new int(0);
  2177. res.set_header("Trailer", "Dummy1, Dummy2");
  2178. res.set_chunked_content_provider(
  2179. "text/plain",
  2180. [i](size_t /*offset*/, DataSink &sink) {
  2181. switch (*i) {
  2182. case 0: sink.os << "123"; break;
  2183. case 1: sink.os << "456"; break;
  2184. case 2: sink.os << "789"; break;
  2185. case 3: {
  2186. sink.done_with_trailer(
  2187. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2188. } break;
  2189. }
  2190. (*i)++;
  2191. return true;
  2192. },
  2193. [i](bool success) {
  2194. EXPECT_TRUE(success);
  2195. delete i;
  2196. });
  2197. })
  2198. .Get("/streamed",
  2199. [&](const Request & /*req*/, Response &res) {
  2200. res.set_content_provider(
  2201. 6, "text/plain",
  2202. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2203. sink.os << (offset < 3 ? "a" : "b");
  2204. return true;
  2205. });
  2206. })
  2207. .Get("/streamed-with-range",
  2208. [&](const Request &req, Response &res) {
  2209. auto data = new std::string("abcdefg");
  2210. res.set_content_provider(
  2211. data->size(), "text/plain",
  2212. [data](size_t offset, size_t length, DataSink &sink) {
  2213. size_t DATA_CHUNK_SIZE = 4;
  2214. const auto &d = *data;
  2215. auto out_len =
  2216. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2217. auto ret =
  2218. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2219. EXPECT_TRUE(ret);
  2220. return true;
  2221. },
  2222. [data, &req](bool success) {
  2223. EXPECT_EQ(success, !req.has_param("error"));
  2224. delete data;
  2225. });
  2226. })
  2227. .Get("/streamed-cancel",
  2228. [&](const Request & /*req*/, Response &res) {
  2229. res.set_content_provider(
  2230. size_t(-1), "text/plain",
  2231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2232. sink.os << "data_chunk";
  2233. return true;
  2234. });
  2235. })
  2236. .Get("/regex-with-delimiter",
  2237. [&](const Request &req, Response & /*res*/) {
  2238. ASSERT_TRUE(req.has_param("key"));
  2239. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2240. })
  2241. .Get("/with-range",
  2242. [&](const Request & /*req*/, Response &res) {
  2243. res.set_content("abcdefg", "text/plain");
  2244. })
  2245. .Get("/with-range-customized-response",
  2246. [&](const Request & /*req*/, Response &res) {
  2247. res.status = StatusCode::BadRequest_400;
  2248. res.set_content(JSON_DATA, "application/json");
  2249. })
  2250. .Post("/chunked",
  2251. [&](const Request &req, Response & /*res*/) {
  2252. EXPECT_EQ(req.body, "dechunked post body");
  2253. })
  2254. .Post("/large-chunked",
  2255. [&](const Request &req, Response & /*res*/) {
  2256. std::string expected(6 * 30 * 1024u, 'a');
  2257. EXPECT_EQ(req.body, expected);
  2258. })
  2259. .Post("/multipart",
  2260. [&](const Request &req, Response & /*res*/) {
  2261. EXPECT_EQ(6u, req.files.size());
  2262. ASSERT_TRUE(!req.has_file("???"));
  2263. ASSERT_TRUE(req.body.empty());
  2264. {
  2265. const auto &file = req.get_file_value("text1");
  2266. EXPECT_TRUE(file.filename.empty());
  2267. EXPECT_EQ("text default", file.content);
  2268. }
  2269. {
  2270. const auto &file = req.get_file_value("text2");
  2271. EXPECT_TRUE(file.filename.empty());
  2272. EXPECT_EQ("aωb", file.content);
  2273. }
  2274. {
  2275. const auto &file = req.get_file_value("file1");
  2276. EXPECT_EQ("hello.txt", file.filename);
  2277. EXPECT_EQ("text/plain", file.content_type);
  2278. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2279. }
  2280. {
  2281. const auto &file = req.get_file_value("file3");
  2282. EXPECT_TRUE(file.filename.empty());
  2283. EXPECT_EQ("application/octet-stream", file.content_type);
  2284. EXPECT_EQ(0u, file.content.size());
  2285. }
  2286. {
  2287. const auto &file = req.get_file_value("file4");
  2288. EXPECT_TRUE(file.filename.empty());
  2289. EXPECT_EQ(0u, file.content.size());
  2290. EXPECT_EQ("application/json tmp-string", file.content_type);
  2291. }
  2292. })
  2293. .Post("/multipart/multi_file_values",
  2294. [&](const Request &req, Response & /*res*/) {
  2295. EXPECT_EQ(5u, req.files.size());
  2296. ASSERT_TRUE(!req.has_file("???"));
  2297. ASSERT_TRUE(req.body.empty());
  2298. {
  2299. const auto &text_value = req.get_file_values("text");
  2300. EXPECT_EQ(1u, text_value.size());
  2301. auto &text = text_value[0];
  2302. EXPECT_TRUE(text.filename.empty());
  2303. EXPECT_EQ("default text", text.content);
  2304. }
  2305. {
  2306. const auto &text1_values = req.get_file_values("multi_text1");
  2307. EXPECT_EQ(2u, text1_values.size());
  2308. EXPECT_EQ("aaaaa", text1_values[0].content);
  2309. EXPECT_EQ("bbbbb", text1_values[1].content);
  2310. }
  2311. {
  2312. const auto &file1_values = req.get_file_values("multi_file1");
  2313. EXPECT_EQ(2u, file1_values.size());
  2314. auto file1 = file1_values[0];
  2315. EXPECT_EQ(file1.filename, "hello.txt");
  2316. EXPECT_EQ(file1.content_type, "text/plain");
  2317. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2318. auto file2 = file1_values[1];
  2319. EXPECT_EQ(file2.filename, "world.json");
  2320. EXPECT_EQ(file2.content_type, "application/json");
  2321. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2322. }
  2323. })
  2324. .Post("/empty",
  2325. [&](const Request &req, Response &res) {
  2326. EXPECT_EQ(req.body, "");
  2327. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2328. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2329. res.set_content("empty", "text/plain");
  2330. })
  2331. .Post("/empty-no-content-type",
  2332. [&](const Request &req, Response &res) {
  2333. EXPECT_EQ(req.body, "");
  2334. EXPECT_FALSE(req.has_header("Content-Type"));
  2335. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2336. res.set_content("empty-no-content-type", "text/plain");
  2337. })
  2338. .Post("/path-only",
  2339. [&](const Request &req, Response &res) {
  2340. EXPECT_EQ(req.body, "");
  2341. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2343. res.set_content("path-only", "text/plain");
  2344. })
  2345. .Post("/path-headers-only",
  2346. [&](const Request &req, Response &res) {
  2347. EXPECT_EQ(req.body, "");
  2348. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2349. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2350. EXPECT_EQ("world", req.get_header_value("hello"));
  2351. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2352. res.set_content("path-headers-only", "text/plain");
  2353. })
  2354. .Post("/post-large",
  2355. [&](const Request &req, Response &res) {
  2356. EXPECT_EQ(req.body, LARGE_DATA);
  2357. res.set_content(req.body, "text/plain");
  2358. })
  2359. .Put("/empty-no-content-type",
  2360. [&](const Request &req, Response &res) {
  2361. EXPECT_EQ(req.body, "");
  2362. EXPECT_FALSE(req.has_header("Content-Type"));
  2363. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2364. res.set_content("empty-no-content-type", "text/plain");
  2365. })
  2366. .Put("/put",
  2367. [&](const Request &req, Response &res) {
  2368. EXPECT_EQ(req.body, "PUT");
  2369. res.set_content(req.body, "text/plain");
  2370. })
  2371. .Put("/put-large",
  2372. [&](const Request &req, Response &res) {
  2373. EXPECT_EQ(req.body, LARGE_DATA);
  2374. res.set_content(req.body, "text/plain");
  2375. })
  2376. .Patch("/patch",
  2377. [&](const Request &req, Response &res) {
  2378. EXPECT_EQ(req.body, "PATCH");
  2379. res.set_content(req.body, "text/plain");
  2380. })
  2381. .Delete("/delete",
  2382. [&](const Request & /*req*/, Response &res) {
  2383. res.set_content("DELETE", "text/plain");
  2384. })
  2385. .Delete("/delete-body",
  2386. [&](const Request &req, Response &res) {
  2387. EXPECT_EQ(req.body, "content");
  2388. res.set_content(req.body, "text/plain");
  2389. })
  2390. .Options(R"(\*)",
  2391. [&](const Request & /*req*/, Response &res) {
  2392. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2393. })
  2394. .Get("/request-target",
  2395. [&](const Request &req, Response & /*res*/) {
  2396. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2397. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2398. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2399. })
  2400. .Get("/long-query-value",
  2401. [&](const Request &req, Response & /*res*/) {
  2402. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2403. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2404. })
  2405. .Get("/array-param",
  2406. [&](const Request &req, Response & /*res*/) {
  2407. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2408. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2409. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2410. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2411. })
  2412. .Post("/validate-no-multiple-headers",
  2413. [&](const Request &req, Response & /*res*/) {
  2414. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2415. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2416. })
  2417. .Post("/content_receiver",
  2418. [&](const Request &req, Response &res,
  2419. const ContentReader &content_reader) {
  2420. if (req.is_multipart_form_data()) {
  2421. MultipartFormDataItems files;
  2422. content_reader(
  2423. [&](const MultipartFormData &file) {
  2424. files.push_back(file);
  2425. return true;
  2426. },
  2427. [&](const char *data, size_t data_length) {
  2428. files.back().content.append(data, data_length);
  2429. return true;
  2430. });
  2431. EXPECT_EQ(5u, files.size());
  2432. {
  2433. const auto &file = get_file_value(files, "text1");
  2434. EXPECT_TRUE(file.filename.empty());
  2435. EXPECT_EQ("text default", file.content);
  2436. }
  2437. {
  2438. const auto &file = get_file_value(files, "text2");
  2439. EXPECT_TRUE(file.filename.empty());
  2440. EXPECT_EQ("aωb", file.content);
  2441. }
  2442. {
  2443. const auto &file = get_file_value(files, "file1");
  2444. EXPECT_EQ("hello.txt", file.filename);
  2445. EXPECT_EQ("text/plain", file.content_type);
  2446. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2447. }
  2448. {
  2449. const auto &file = get_file_value(files, "file3");
  2450. EXPECT_TRUE(file.filename.empty());
  2451. EXPECT_EQ("application/octet-stream", file.content_type);
  2452. EXPECT_EQ(0u, file.content.size());
  2453. }
  2454. } else {
  2455. std::string body;
  2456. content_reader([&](const char *data, size_t data_length) {
  2457. EXPECT_EQ(7U, data_length);
  2458. body.append(data, data_length);
  2459. return true;
  2460. });
  2461. EXPECT_EQ(body, "content");
  2462. res.set_content(body, "text/plain");
  2463. }
  2464. })
  2465. .Put("/content_receiver",
  2466. [&](const Request & /*req*/, Response &res,
  2467. const ContentReader &content_reader) {
  2468. std::string body;
  2469. content_reader([&](const char *data, size_t data_length) {
  2470. body.append(data, data_length);
  2471. return true;
  2472. });
  2473. EXPECT_EQ(body, "content");
  2474. res.set_content(body, "text/plain");
  2475. })
  2476. .Patch("/content_receiver",
  2477. [&](const Request & /*req*/, Response &res,
  2478. const ContentReader &content_reader) {
  2479. std::string body;
  2480. content_reader([&](const char *data, size_t data_length) {
  2481. body.append(data, data_length);
  2482. return true;
  2483. });
  2484. EXPECT_EQ(body, "content");
  2485. res.set_content(body, "text/plain");
  2486. })
  2487. .Post("/query-string-and-body",
  2488. [&](const Request &req, Response & /*res*/) {
  2489. ASSERT_TRUE(req.has_param("key"));
  2490. EXPECT_EQ(req.get_param_value("key"), "value");
  2491. EXPECT_EQ(req.body, "content");
  2492. })
  2493. .Get("/last-request",
  2494. [&](const Request &req, Response & /*res*/) {
  2495. EXPECT_EQ("close", req.get_header_value("Connection"));
  2496. })
  2497. .Get(R"(/redirect/(\d+))",
  2498. [&](const Request &req, Response &res) {
  2499. auto num = std::stoi(req.matches[1]) + 1;
  2500. std::string url = "/redirect/" + std::to_string(num);
  2501. res.set_redirect(url);
  2502. })
  2503. .Post("/binary",
  2504. [&](const Request &req, Response &res) {
  2505. EXPECT_EQ(4U, req.body.size());
  2506. EXPECT_EQ("application/octet-stream",
  2507. req.get_header_value("Content-Type"));
  2508. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2509. res.set_content(req.body, "application/octet-stream");
  2510. })
  2511. .Put("/binary",
  2512. [&](const Request &req, Response &res) {
  2513. EXPECT_EQ(4U, req.body.size());
  2514. EXPECT_EQ("application/octet-stream",
  2515. req.get_header_value("Content-Type"));
  2516. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2517. res.set_content(req.body, "application/octet-stream");
  2518. })
  2519. .Patch("/binary",
  2520. [&](const Request &req, Response &res) {
  2521. EXPECT_EQ(4U, req.body.size());
  2522. EXPECT_EQ("application/octet-stream",
  2523. req.get_header_value("Content-Type"));
  2524. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2525. res.set_content(req.body, "application/octet-stream");
  2526. })
  2527. .Delete("/binary",
  2528. [&](const Request &req, Response &res) {
  2529. EXPECT_EQ(4U, req.body.size());
  2530. EXPECT_EQ("application/octet-stream",
  2531. req.get_header_value("Content-Type"));
  2532. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2533. res.set_content(req.body, "application/octet-stream");
  2534. })
  2535. .Get("/issue1772",
  2536. [&](const Request & /*req*/, Response &res) {
  2537. res.status = 401;
  2538. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2539. })
  2540. .Delete("/issue609",
  2541. [](const httplib::Request &, httplib::Response &res,
  2542. const httplib::ContentReader &) {
  2543. res.set_content("ok", "text/plain");
  2544. })
  2545. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2546. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2547. .Get("/compress",
  2548. [&](const Request & /*req*/, Response &res) {
  2549. res.set_content(
  2550. "12345678901234567890123456789012345678901234567890123456789"
  2551. "01234567890123456789012345678901234567890",
  2552. "text/plain");
  2553. })
  2554. .Get("/nocompress",
  2555. [&](const Request & /*req*/, Response &res) {
  2556. res.set_content(
  2557. "12345678901234567890123456789012345678901234567890123456789"
  2558. "01234567890123456789012345678901234567890",
  2559. "application/octet-stream");
  2560. })
  2561. .Post("/compress-multipart",
  2562. [&](const Request &req, Response & /*res*/) {
  2563. EXPECT_EQ(2u, req.files.size());
  2564. ASSERT_TRUE(!req.has_file("???"));
  2565. {
  2566. const auto &file = req.get_file_value("key1");
  2567. EXPECT_TRUE(file.filename.empty());
  2568. EXPECT_EQ("test", file.content);
  2569. }
  2570. {
  2571. const auto &file = req.get_file_value("key2");
  2572. EXPECT_TRUE(file.filename.empty());
  2573. EXPECT_EQ("--abcdefg123", file.content);
  2574. }
  2575. })
  2576. #endif
  2577. ;
  2578. persons_["john"] = "programmer";
  2579. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2580. svr_.wait_until_ready();
  2581. }
  2582. virtual void TearDown() {
  2583. svr_.stop();
  2584. if (!request_threads_.empty()) {
  2585. std::this_thread::sleep_for(std::chrono::seconds(1));
  2586. for (auto &t : request_threads_) {
  2587. t.join();
  2588. }
  2589. }
  2590. t_.join();
  2591. }
  2592. map<string, string> persons_;
  2593. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2594. SSLClient cli_;
  2595. SSLServer svr_;
  2596. #else
  2597. Client cli_;
  2598. Server svr_;
  2599. #endif
  2600. thread t_;
  2601. std::vector<thread> request_threads_;
  2602. };
  2603. TEST_F(ServerTest, GetMethod200) {
  2604. auto res = cli_.Get("/hi");
  2605. ASSERT_TRUE(res);
  2606. EXPECT_EQ("HTTP/1.1", res->version);
  2607. EXPECT_EQ(StatusCode::OK_200, res->status);
  2608. EXPECT_EQ("OK", res->reason);
  2609. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2610. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2611. EXPECT_EQ("Hello World!", res->body);
  2612. }
  2613. TEST_F(ServerTest, GetEmptyFile) {
  2614. auto res = cli_.Get("/empty_file");
  2615. ASSERT_TRUE(res);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2618. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2619. EXPECT_EQ("", res->body);
  2620. }
  2621. TEST_F(ServerTest, GetFileContent) {
  2622. auto res = cli_.Get("/file_content");
  2623. ASSERT_TRUE(res);
  2624. EXPECT_EQ(StatusCode::OK_200, res->status);
  2625. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2626. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2627. EXPECT_EQ("test.html", res->body);
  2628. }
  2629. TEST_F(ServerTest, GetFileContentWithRange) {
  2630. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2631. ASSERT_TRUE(res);
  2632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2634. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2635. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2636. EXPECT_EQ("est", res->body);
  2637. }
  2638. TEST_F(ServerTest, GetFileContentWithContentType) {
  2639. auto res = cli_.Get("/file_content_with_content_type");
  2640. ASSERT_TRUE(res);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2643. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2644. EXPECT_EQ("file\n", res->body);
  2645. }
  2646. TEST_F(ServerTest, GetInvalidFileContent) {
  2647. auto res = cli_.Get("/invalid_file_content");
  2648. ASSERT_TRUE(res);
  2649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2650. }
  2651. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2652. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2653. ASSERT_TRUE(res);
  2654. EXPECT_EQ("HTTP/1.1", res->version);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2657. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2658. EXPECT_EQ("Hello World!", res->body);
  2659. }
  2660. TEST_F(ServerTest, GetMethod302) {
  2661. auto res = cli_.Get("/");
  2662. ASSERT_TRUE(res);
  2663. EXPECT_EQ(StatusCode::Found_302, res->status);
  2664. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2665. }
  2666. TEST_F(ServerTest, GetMethod302Redirect) {
  2667. cli_.set_follow_location(true);
  2668. auto res = cli_.Get("/");
  2669. ASSERT_TRUE(res);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ("/hi", res->location);
  2673. }
  2674. TEST_F(ServerTest, GetMethod404) {
  2675. auto res = cli_.Get("/invalid");
  2676. ASSERT_TRUE(res);
  2677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2678. }
  2679. TEST_F(ServerTest, HeadMethod200) {
  2680. auto res = cli_.Head("/hi");
  2681. ASSERT_TRUE(res);
  2682. EXPECT_EQ(StatusCode::OK_200, res->status);
  2683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2684. EXPECT_TRUE(res->body.empty());
  2685. }
  2686. TEST_F(ServerTest, HeadMethod200Static) {
  2687. auto res = cli_.Head("/mount/dir/index.html");
  2688. ASSERT_TRUE(res);
  2689. EXPECT_EQ(StatusCode::OK_200, res->status);
  2690. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2691. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2692. EXPECT_TRUE(res->body.empty());
  2693. }
  2694. TEST_F(ServerTest, HeadMethod404) {
  2695. auto res = cli_.Head("/invalid");
  2696. ASSERT_TRUE(res);
  2697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2698. EXPECT_TRUE(res->body.empty());
  2699. }
  2700. TEST_F(ServerTest, GetMethodPersonJohn) {
  2701. auto res = cli_.Get("/person/john");
  2702. ASSERT_TRUE(res);
  2703. EXPECT_EQ(StatusCode::OK_200, res->status);
  2704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2705. EXPECT_EQ("programmer", res->body);
  2706. }
  2707. TEST_F(ServerTest, PostMethod1) {
  2708. auto res = cli_.Get("/person/john1");
  2709. ASSERT_TRUE(res);
  2710. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2711. res = cli_.Post("/person", "name=john1&note=coder",
  2712. "application/x-www-form-urlencoded");
  2713. ASSERT_TRUE(res);
  2714. ASSERT_EQ(StatusCode::OK_200, res->status);
  2715. res = cli_.Get("/person/john1");
  2716. ASSERT_TRUE(res);
  2717. ASSERT_EQ(StatusCode::OK_200, res->status);
  2718. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2719. ASSERT_EQ("coder", res->body);
  2720. }
  2721. TEST_F(ServerTest, PostMethod2) {
  2722. auto res = cli_.Get("/person/john2");
  2723. ASSERT_TRUE(res);
  2724. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2725. Params params;
  2726. params.emplace("name", "john2");
  2727. params.emplace("note", "coder");
  2728. res = cli_.Post("/person", params);
  2729. ASSERT_TRUE(res);
  2730. ASSERT_EQ(StatusCode::OK_200, res->status);
  2731. res = cli_.Get("/person/john2");
  2732. ASSERT_TRUE(res);
  2733. ASSERT_EQ(StatusCode::OK_200, res->status);
  2734. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2735. ASSERT_EQ("coder", res->body);
  2736. }
  2737. TEST_F(ServerTest, PutMethod3) {
  2738. auto res = cli_.Get("/person/john3");
  2739. ASSERT_TRUE(res);
  2740. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2741. Params params;
  2742. params.emplace("name", "john3");
  2743. params.emplace("note", "coder");
  2744. res = cli_.Put("/person", params);
  2745. ASSERT_TRUE(res);
  2746. ASSERT_EQ(StatusCode::OK_200, res->status);
  2747. res = cli_.Get("/person/john3");
  2748. ASSERT_TRUE(res);
  2749. ASSERT_EQ(StatusCode::OK_200, res->status);
  2750. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2751. ASSERT_EQ("coder", res->body);
  2752. }
  2753. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2754. Params params;
  2755. params.emplace("json", JSON_DATA);
  2756. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2757. ASSERT_TRUE(res);
  2758. ASSERT_EQ(StatusCode::OK_200, res->status);
  2759. ASSERT_EQ(JSON_DATA, res->body);
  2760. }
  2761. TEST_F(ServerTest, PostEmptyContent) {
  2762. auto res = cli_.Post("/empty", "", "text/plain");
  2763. ASSERT_TRUE(res);
  2764. ASSERT_EQ(StatusCode::OK_200, res->status);
  2765. ASSERT_EQ("empty", res->body);
  2766. }
  2767. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2768. auto res = cli_.Post("/empty-no-content-type");
  2769. ASSERT_TRUE(res);
  2770. ASSERT_EQ(StatusCode::OK_200, res->status);
  2771. ASSERT_EQ("empty-no-content-type", res->body);
  2772. }
  2773. TEST_F(ServerTest, PostPathOnly) {
  2774. auto res = cli_.Post("/path-only");
  2775. ASSERT_TRUE(res);
  2776. ASSERT_EQ(StatusCode::OK_200, res->status);
  2777. ASSERT_EQ("path-only", res->body);
  2778. }
  2779. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2780. auto res = cli_.Post("/path-headers-only",
  2781. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2782. ASSERT_TRUE(res);
  2783. ASSERT_EQ(StatusCode::OK_200, res->status);
  2784. ASSERT_EQ("path-headers-only", res->body);
  2785. }
  2786. TEST_F(ServerTest, PostLarge) {
  2787. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2788. ASSERT_TRUE(res);
  2789. ASSERT_EQ(StatusCode::OK_200, res->status);
  2790. EXPECT_EQ(LARGE_DATA, res->body);
  2791. }
  2792. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2793. auto res = cli_.Put("/empty-no-content-type");
  2794. ASSERT_TRUE(res);
  2795. ASSERT_EQ(StatusCode::OK_200, res->status);
  2796. ASSERT_EQ("empty-no-content-type", res->body);
  2797. }
  2798. TEST_F(ServerTest, GetMethodDir) {
  2799. auto res = cli_.Get("/dir/");
  2800. ASSERT_TRUE(res);
  2801. EXPECT_EQ(StatusCode::OK_200, res->status);
  2802. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2803. auto body = R"(<html>
  2804. <head>
  2805. </head>
  2806. <body>
  2807. <a href="/dir/test.html">Test</a>
  2808. <a href="/hi">hi</a>
  2809. </body>
  2810. </html>
  2811. )";
  2812. EXPECT_EQ(body, res->body);
  2813. }
  2814. TEST_F(ServerTest, GetMethodDirTest) {
  2815. auto res = cli_.Get("/dir/test.html");
  2816. ASSERT_TRUE(res);
  2817. EXPECT_EQ(StatusCode::OK_200, res->status);
  2818. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2819. EXPECT_EQ("test.html", res->body);
  2820. }
  2821. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2822. auto res = cli_.Get("/dir/../dir/test.html");
  2823. ASSERT_TRUE(res);
  2824. EXPECT_EQ(StatusCode::OK_200, res->status);
  2825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2826. EXPECT_EQ("test.html", res->body);
  2827. }
  2828. TEST_F(ServerTest, GetMethodInvalidPath) {
  2829. auto res = cli_.Get("/dir/../test.html");
  2830. ASSERT_TRUE(res);
  2831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2832. }
  2833. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2834. auto res = cli_.Get("/../www/dir/test.html");
  2835. ASSERT_TRUE(res);
  2836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2837. }
  2838. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2839. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2840. ASSERT_TRUE(res);
  2841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2842. }
  2843. TEST_F(ServerTest, GetMethodDirMountTest) {
  2844. auto res = cli_.Get("/mount/dir/test.html");
  2845. ASSERT_TRUE(res);
  2846. EXPECT_EQ(StatusCode::OK_200, res->status);
  2847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2848. EXPECT_EQ("test.html", res->body);
  2849. }
  2850. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2851. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2852. ASSERT_TRUE(res);
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2855. EXPECT_EQ("test.html", res->body);
  2856. }
  2857. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2858. auto res = cli_.Get("/mount/dir/../test.html");
  2859. ASSERT_TRUE(res);
  2860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2861. }
  2862. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2863. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2864. ASSERT_TRUE(res);
  2865. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2866. }
  2867. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2868. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2869. ASSERT_TRUE(res);
  2870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2871. }
  2872. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2873. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2874. ASSERT_TRUE(res);
  2875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2876. }
  2877. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2878. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2879. ASSERT_TRUE(res);
  2880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2881. }
  2882. TEST_F(ServerTest, PostMethod303) {
  2883. auto res = cli_.Post("/1", "body", "text/plain");
  2884. ASSERT_TRUE(res);
  2885. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2886. EXPECT_EQ("/2", res->get_header_value("Location"));
  2887. }
  2888. TEST_F(ServerTest, PostMethod303Redirect) {
  2889. cli_.set_follow_location(true);
  2890. auto res = cli_.Post("/1", "body", "text/plain");
  2891. ASSERT_TRUE(res);
  2892. EXPECT_EQ(StatusCode::OK_200, res->status);
  2893. EXPECT_EQ("redirected.", res->body);
  2894. EXPECT_EQ("/2", res->location);
  2895. }
  2896. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2897. auto res = cli_.Get("/dir/test.abcde");
  2898. ASSERT_TRUE(res);
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2901. EXPECT_EQ("abcde", res->body);
  2902. }
  2903. TEST_F(ServerTest, StaticFileRange) {
  2904. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2905. ASSERT_TRUE(res);
  2906. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2907. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2908. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2909. EXPECT_EQ(true, res->has_header("Content-Range"));
  2910. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2911. EXPECT_EQ(std::string("cd"), res->body);
  2912. }
  2913. TEST_F(ServerTest, StaticFileRanges) {
  2914. auto res =
  2915. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2916. ASSERT_TRUE(res);
  2917. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2918. EXPECT_TRUE(
  2919. res->get_header_value("Content-Type")
  2920. .find(
  2921. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2922. 0);
  2923. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2924. }
  2925. TEST_F(ServerTest, StaticFileRangeHead) {
  2926. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2927. ASSERT_TRUE(res);
  2928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2929. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2930. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2931. EXPECT_EQ(true, res->has_header("Content-Range"));
  2932. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2933. }
  2934. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2935. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2936. ASSERT_TRUE(res);
  2937. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2938. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2939. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2940. EXPECT_EQ(true, res->has_header("Content-Range"));
  2941. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2942. res->get_header_value("Content-Range"));
  2943. EXPECT_EQ("LAST\n", res->body);
  2944. }
  2945. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2946. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2947. ASSERT_TRUE(res);
  2948. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2950. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2951. EXPECT_EQ(true, res->has_header("Content-Range"));
  2952. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2953. }
  2954. TEST_F(ServerTest, StaticFileBigFile) {
  2955. auto res = cli_.Get("/dir/1MB.txt");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2959. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2960. }
  2961. TEST_F(ServerTest, InvalidBaseDirMount) {
  2962. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2963. }
  2964. TEST_F(ServerTest, Binary) {
  2965. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2966. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2967. "application/octet-stream");
  2968. ASSERT_TRUE(res);
  2969. ASSERT_EQ(StatusCode::OK_200, res->status);
  2970. ASSERT_EQ(4U, res->body.size());
  2971. res = cli_.Put("/binary", binary.data(), binary.size(),
  2972. "application/octet-stream");
  2973. ASSERT_TRUE(res);
  2974. ASSERT_EQ(StatusCode::OK_200, res->status);
  2975. ASSERT_EQ(4U, res->body.size());
  2976. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2977. "application/octet-stream");
  2978. ASSERT_TRUE(res);
  2979. ASSERT_EQ(StatusCode::OK_200, res->status);
  2980. ASSERT_EQ(4U, res->body.size());
  2981. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2982. "application/octet-stream");
  2983. ASSERT_TRUE(res);
  2984. ASSERT_EQ(StatusCode::OK_200, res->status);
  2985. ASSERT_EQ(4U, res->body.size());
  2986. }
  2987. TEST_F(ServerTest, BinaryString) {
  2988. auto binary = std::string("\x00\x01\x02\x03", 4);
  2989. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2990. ASSERT_TRUE(res);
  2991. ASSERT_EQ(StatusCode::OK_200, res->status);
  2992. ASSERT_EQ(4U, res->body.size());
  2993. res = cli_.Put("/binary", binary, "application/octet-stream");
  2994. ASSERT_TRUE(res);
  2995. ASSERT_EQ(StatusCode::OK_200, res->status);
  2996. ASSERT_EQ(4U, res->body.size());
  2997. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2998. ASSERT_TRUE(res);
  2999. ASSERT_EQ(StatusCode::OK_200, res->status);
  3000. ASSERT_EQ(4U, res->body.size());
  3001. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3002. ASSERT_TRUE(res);
  3003. ASSERT_EQ(StatusCode::OK_200, res->status);
  3004. ASSERT_EQ(4U, res->body.size());
  3005. }
  3006. TEST_F(ServerTest, EmptyRequest) {
  3007. auto res = cli_.Get("");
  3008. ASSERT_TRUE(!res);
  3009. EXPECT_EQ(Error::Connection, res.error());
  3010. }
  3011. TEST_F(ServerTest, LongRequest) {
  3012. std::string request;
  3013. for (size_t i = 0; i < 545; i++) {
  3014. request += "/TooLongRequest";
  3015. }
  3016. request += "OK";
  3017. auto res = cli_.Get(request.c_str());
  3018. ASSERT_TRUE(res);
  3019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3020. }
  3021. TEST_F(ServerTest, TooLongRequest) {
  3022. std::string request;
  3023. for (size_t i = 0; i < 546; i++) {
  3024. request += "/TooLongRequest";
  3025. }
  3026. request += "_NG";
  3027. auto res = cli_.Get(request.c_str());
  3028. ASSERT_TRUE(res);
  3029. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3030. }
  3031. TEST_F(ServerTest, AlmostTooLongRequest) {
  3032. // test for #2046 - URI length check shouldn't include other content on req
  3033. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3034. // leading /, space, HTTP/1.1)
  3035. std::string request =
  3036. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3037. auto res = cli_.Get(request.c_str());
  3038. ASSERT_TRUE(res);
  3039. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3040. }
  3041. TEST_F(ServerTest, LongHeader) {
  3042. Request req;
  3043. req.method = "GET";
  3044. req.path = "/hi";
  3045. std::string host_and_port;
  3046. host_and_port += HOST;
  3047. host_and_port += ":";
  3048. host_and_port += std::to_string(PORT);
  3049. req.headers.emplace("Host", host_and_port.c_str());
  3050. req.headers.emplace("Accept", "*/*");
  3051. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3052. req.headers.emplace(
  3053. "Header-Name",
  3054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3082. "@@@@@@@@@@@@@@@@");
  3083. auto res = std::make_shared<Response>();
  3084. auto error = Error::Success;
  3085. auto ret = cli_.send(req, *res, error);
  3086. ASSERT_TRUE(ret);
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. }
  3089. TEST_F(ServerTest, LongQueryValue) {
  3090. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3091. ASSERT_TRUE(res);
  3092. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3093. }
  3094. TEST_F(ServerTest, TooLongHeader) {
  3095. Request req;
  3096. req.method = "GET";
  3097. req.path = "/hi";
  3098. std::string host_and_port;
  3099. host_and_port += HOST;
  3100. host_and_port += ":";
  3101. host_and_port += std::to_string(PORT);
  3102. req.headers.emplace("Host", host_and_port.c_str());
  3103. req.headers.emplace("Accept", "*/*");
  3104. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3105. req.headers.emplace(
  3106. "Header-Name",
  3107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3135. "@@@@@@@@@@@@@@@@@");
  3136. auto res = std::make_shared<Response>();
  3137. auto error = Error::Success;
  3138. auto ret = cli_.send(req, *res, error);
  3139. ASSERT_TRUE(ret);
  3140. EXPECT_EQ(StatusCode::OK_200, res->status);
  3141. }
  3142. TEST_F(ServerTest, PercentEncoding) {
  3143. auto res = cli_.Get("/e%6edwith%");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. }
  3147. TEST_F(ServerTest, PercentEncodingUnicode) {
  3148. auto res = cli_.Get("/e%u006edwith%");
  3149. ASSERT_TRUE(res);
  3150. EXPECT_EQ(StatusCode::OK_200, res->status);
  3151. }
  3152. TEST_F(ServerTest, InvalidPercentEncoding) {
  3153. auto res = cli_.Get("/%endwith%");
  3154. ASSERT_TRUE(res);
  3155. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3156. }
  3157. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3158. auto res = cli_.Get("/%uendwith%");
  3159. ASSERT_TRUE(res);
  3160. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3161. }
  3162. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3163. auto res = cli_.Get("/hello?aaa=bbb%");
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3166. }
  3167. TEST_F(ServerTest, PlusSignEncoding) {
  3168. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3169. ASSERT_TRUE(res);
  3170. EXPECT_EQ(StatusCode::OK_200, res->status);
  3171. EXPECT_EQ("a +b", res->body);
  3172. }
  3173. TEST_F(ServerTest, MultipartFormData) {
  3174. MultipartFormDataItems items = {
  3175. {"text1", "text default", "", ""},
  3176. {"text2", "aωb", "", ""},
  3177. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3178. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3179. {"file3", "", "", "application/octet-stream"},
  3180. {"file4", "", "", " application/json tmp-string "}};
  3181. auto res = cli_.Post("/multipart", items);
  3182. ASSERT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. }
  3185. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3186. MultipartFormDataItems items = {
  3187. {"text", "default text", "", ""},
  3188. {"multi_text1", "aaaaa", "", ""},
  3189. {"multi_text1", "bbbbb", "", ""},
  3190. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3191. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3192. "application/json"},
  3193. };
  3194. auto res = cli_.Post("/multipart/multi_file_values", items);
  3195. ASSERT_TRUE(res);
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. }
  3198. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3199. auto res = cli_.Get("/hi");
  3200. ASSERT_TRUE(res);
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3203. EXPECT_EQ("Hello World!", res->body);
  3204. }
  3205. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3206. Request req;
  3207. req.method = "POST";
  3208. req.path = "/chunked";
  3209. std::string host_and_port;
  3210. host_and_port += HOST;
  3211. host_and_port += ":";
  3212. host_and_port += std::to_string(PORT);
  3213. req.headers.emplace("Host", host_and_port.c_str());
  3214. req.headers.emplace("Accept", "*/*");
  3215. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3216. req.headers.emplace("Content-Type", "text/plain");
  3217. req.headers.emplace("Content-Length", "0");
  3218. req.headers.emplace(
  3219. "Transfer-Encoding",
  3220. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3221. // Client does not chunk, so make a chunked body manually.
  3222. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3223. auto res = std::make_shared<Response>();
  3224. auto error = Error::Success;
  3225. auto ret = cli_.send(req, *res, error);
  3226. ASSERT_TRUE(ret);
  3227. EXPECT_EQ(StatusCode::OK_200, res->status);
  3228. }
  3229. TEST_F(ServerTest, GetStreamed2) {
  3230. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3231. ASSERT_TRUE(res);
  3232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3233. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3234. EXPECT_EQ(true, res->has_header("Content-Range"));
  3235. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3236. EXPECT_EQ(std::string("ab"), res->body);
  3237. }
  3238. TEST_F(ServerTest, GetStreamed) {
  3239. auto res = cli_.Get("/streamed");
  3240. ASSERT_TRUE(res);
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3243. EXPECT_EQ(std::string("aaabbb"), res->body);
  3244. }
  3245. TEST_F(ServerTest, GetStreamedWithRange1) {
  3246. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3249. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3250. EXPECT_EQ(true, res->has_header("Content-Range"));
  3251. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3252. EXPECT_EQ(std::string("def"), res->body);
  3253. }
  3254. TEST_F(ServerTest, GetStreamedWithRange2) {
  3255. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3258. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3259. EXPECT_EQ(true, res->has_header("Content-Range"));
  3260. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3261. EXPECT_EQ(std::string("bcdefg"), res->body);
  3262. }
  3263. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3264. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3265. ASSERT_TRUE(res);
  3266. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3267. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3268. EXPECT_EQ(true, res->has_header("Content-Range"));
  3269. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3270. EXPECT_EQ(std::string("efg"), res->body);
  3271. }
  3272. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3273. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3274. ASSERT_TRUE(res);
  3275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3277. EXPECT_EQ(false, res->has_header("Content-Range"));
  3278. EXPECT_EQ(0U, res->body.size());
  3279. }
  3280. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3281. auto res = cli_.Get("/streamed-with-range",
  3282. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3283. "92233720368547758079223372036854775807"}});
  3284. ASSERT_TRUE(res);
  3285. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3287. EXPECT_EQ(false, res->has_header("Content-Range"));
  3288. EXPECT_EQ(0U, res->body.size());
  3289. }
  3290. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3291. auto res = cli_.Get(
  3292. "/with-range",
  3293. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3294. {"Accept-Encoding", ""}});
  3295. ASSERT_TRUE(res);
  3296. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3297. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3298. EXPECT_EQ(true, res->has_header("Content-Range"));
  3299. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3300. EXPECT_EQ(std::string("abcdefg"), res->body);
  3301. }
  3302. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3303. auto res = cli_.Get("/with-range", {
  3304. {"Range", "bytes=0-"},
  3305. {"Accept-Encoding", ""},
  3306. });
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3309. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3310. EXPECT_EQ(true, res->has_header("Content-Range"));
  3311. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3312. EXPECT_EQ(std::string("abcdefg"), res->body);
  3313. }
  3314. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3315. auto res =
  3316. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3317. ASSERT_TRUE(res);
  3318. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3319. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3320. EXPECT_EQ(false, res->has_header("Content-Range"));
  3321. EXPECT_EQ(267U, res->body.size());
  3322. }
  3323. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3324. Ranges ranges;
  3325. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3326. ranges.emplace_back(0, -1);
  3327. }
  3328. auto res =
  3329. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3332. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3333. EXPECT_EQ(false, res->has_header("Content-Range"));
  3334. EXPECT_EQ(0U, res->body.size());
  3335. }
  3336. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3337. auto res = cli_.Get("/streamed-with-range?error",
  3338. {{make_range_header({{0, -1}, {0, -1}})}});
  3339. ASSERT_TRUE(res);
  3340. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3341. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3342. EXPECT_EQ(false, res->has_header("Content-Range"));
  3343. EXPECT_EQ(0U, res->body.size());
  3344. }
  3345. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3346. auto res = cli_.Get("/streamed-with-range?error",
  3347. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3348. ASSERT_TRUE(res);
  3349. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3350. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3351. EXPECT_EQ(false, res->has_header("Content-Range"));
  3352. EXPECT_EQ(0U, res->body.size());
  3353. }
  3354. TEST_F(ServerTest, GetStreamedEndless) {
  3355. uint64_t offset = 0;
  3356. auto res = cli_.Get("/streamed-cancel",
  3357. [&](const char * /*data*/, uint64_t data_length) {
  3358. if (offset < 100) {
  3359. offset += data_length;
  3360. return true;
  3361. }
  3362. return false;
  3363. });
  3364. ASSERT_TRUE(!res);
  3365. EXPECT_EQ(Error::Canceled, res.error());
  3366. }
  3367. TEST_F(ServerTest, ClientStop) {
  3368. std::atomic_size_t count{4};
  3369. std::vector<std::thread> threads;
  3370. for (auto i = count.load(); i != 0; --i) {
  3371. threads.emplace_back([&]() {
  3372. auto res = cli_.Get("/streamed-cancel",
  3373. [&](const char *, uint64_t) { return true; });
  3374. --count;
  3375. ASSERT_TRUE(!res);
  3376. EXPECT_TRUE(res.error() == Error::Canceled ||
  3377. res.error() == Error::Read || res.error() == Error::Write);
  3378. });
  3379. }
  3380. std::this_thread::sleep_for(std::chrono::seconds(2));
  3381. while (count != 0) {
  3382. cli_.stop();
  3383. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3384. }
  3385. for (auto &t : threads) {
  3386. t.join();
  3387. }
  3388. }
  3389. TEST_F(ServerTest, GetWithRange1) {
  3390. auto res = cli_.Get("/with-range", {
  3391. make_range_header({{3, 5}}),
  3392. {"Accept-Encoding", ""},
  3393. });
  3394. ASSERT_TRUE(res);
  3395. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3396. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3397. EXPECT_EQ(true, res->has_header("Content-Range"));
  3398. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3399. EXPECT_EQ(std::string("def"), res->body);
  3400. }
  3401. TEST_F(ServerTest, GetWithRange2) {
  3402. auto res = cli_.Get("/with-range", {
  3403. make_range_header({{1, -1}}),
  3404. {"Accept-Encoding", ""},
  3405. });
  3406. ASSERT_TRUE(res);
  3407. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3408. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3409. EXPECT_EQ(true, res->has_header("Content-Range"));
  3410. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3411. EXPECT_EQ(std::string("bcdefg"), res->body);
  3412. }
  3413. TEST_F(ServerTest, GetWithRange3) {
  3414. auto res = cli_.Get("/with-range", {
  3415. make_range_header({{0, 0}}),
  3416. {"Accept-Encoding", ""},
  3417. });
  3418. ASSERT_TRUE(res);
  3419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3420. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3421. EXPECT_EQ(true, res->has_header("Content-Range"));
  3422. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3423. EXPECT_EQ(std::string("a"), res->body);
  3424. }
  3425. TEST_F(ServerTest, GetWithRange4) {
  3426. auto res = cli_.Get("/with-range", {
  3427. make_range_header({{-1, 2}}),
  3428. {"Accept-Encoding", ""},
  3429. });
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3432. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3433. EXPECT_EQ(true, res->has_header("Content-Range"));
  3434. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3435. EXPECT_EQ(std::string("fg"), res->body);
  3436. }
  3437. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3438. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3441. }
  3442. TEST_F(ServerTest, GetWithRangeMultipart) {
  3443. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3446. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3447. EXPECT_EQ(false, res->has_header("Content-Range"));
  3448. EXPECT_EQ(267U, res->body.size());
  3449. }
  3450. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3451. auto res =
  3452. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3455. }
  3456. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3457. auto res = cli_.Get("/with-range-customized-response",
  3458. {{make_range_header({{1, 2}})}});
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3461. EXPECT_EQ(true, res->has_header("Content-Length"));
  3462. EXPECT_EQ(false, res->has_header("Content-Range"));
  3463. EXPECT_EQ(JSON_DATA, res->body);
  3464. }
  3465. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3466. auto res = cli_.Get("/with-range-customized-response",
  3467. {{make_range_header({{1, 2}, {4, 5}})}});
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3470. EXPECT_EQ(true, res->has_header("Content-Length"));
  3471. EXPECT_EQ(false, res->has_header("Content-Range"));
  3472. EXPECT_EQ(JSON_DATA, res->body);
  3473. }
  3474. TEST_F(ServerTest, Issue1772) {
  3475. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3478. }
  3479. TEST_F(ServerTest, Issue609) {
  3480. auto res = cli_.Delete("/issue609");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ(std::string("ok"), res->body);
  3484. }
  3485. TEST_F(ServerTest, GetStreamedChunked) {
  3486. auto res = cli_.Get("/streamed-chunked");
  3487. ASSERT_TRUE(res);
  3488. EXPECT_EQ(StatusCode::OK_200, res->status);
  3489. EXPECT_EQ(std::string("123456789"), res->body);
  3490. }
  3491. TEST_F(ServerTest, GetStreamedChunked2) {
  3492. auto res = cli_.Get("/streamed-chunked2");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. EXPECT_EQ(std::string("123456789"), res->body);
  3496. }
  3497. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3498. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::OK_200, res->status);
  3501. EXPECT_EQ(std::string("123456789"), res->body);
  3502. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3503. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3504. }
  3505. TEST_F(ServerTest, LargeChunkedPost) {
  3506. Request req;
  3507. req.method = "POST";
  3508. req.path = "/large-chunked";
  3509. std::string host_and_port;
  3510. host_and_port += HOST;
  3511. host_and_port += ":";
  3512. host_and_port += std::to_string(PORT);
  3513. req.headers.emplace("Host", host_and_port.c_str());
  3514. req.headers.emplace("Accept", "*/*");
  3515. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3516. req.headers.emplace("Content-Type", "text/plain");
  3517. req.headers.emplace("Content-Length", "0");
  3518. req.headers.emplace("Transfer-Encoding", "chunked");
  3519. std::string long_string(30 * 1024u, 'a');
  3520. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3521. // Attempt to make a large enough post to exceed OS buffers, to test that
  3522. // the server handles short reads if the full chunk data isn't available.
  3523. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3524. auto res = std::make_shared<Response>();
  3525. auto error = Error::Success;
  3526. auto ret = cli_.send(req, *res, error);
  3527. ASSERT_TRUE(ret);
  3528. EXPECT_EQ(StatusCode::OK_200, res->status);
  3529. }
  3530. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3531. auto res = cli_.Get("/remote_addr");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3535. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3536. }
  3537. TEST_F(ServerTest, GetMethodLocalAddr) {
  3538. auto res = cli_.Get("/local_addr");
  3539. ASSERT_TRUE(res);
  3540. EXPECT_EQ(StatusCode::OK_200, res->status);
  3541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3542. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3543. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3544. }
  3545. TEST_F(ServerTest, HTTPResponseSplitting) {
  3546. auto res = cli_.Get("/http_response_splitting");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::OK_200, res->status);
  3549. }
  3550. TEST_F(ServerTest, SlowRequest) {
  3551. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3552. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3553. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3554. }
  3555. #if 0
  3556. TEST_F(ServerTest, SlowPost) {
  3557. char buffer[64 * 1024];
  3558. memset(buffer, 0x42, sizeof(buffer));
  3559. auto res = cli_.Post(
  3560. "/slowpost", 64 * 1024 * 1024,
  3561. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3562. auto ret = sink.write(buffer, sizeof(buffer));
  3563. EXPECT_TRUE(ret);
  3564. return true;
  3565. },
  3566. "text/plain");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. }
  3570. TEST_F(ServerTest, SlowPostFail) {
  3571. char buffer[64 * 1024];
  3572. memset(buffer, 0x42, sizeof(buffer));
  3573. cli_.set_write_timeout(std::chrono::seconds(0));
  3574. auto res = cli_.Post(
  3575. "/slowpost", 64 * 1024 * 1024,
  3576. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3577. sink.write(buffer, sizeof(buffer));
  3578. return true;
  3579. },
  3580. "text/plain");
  3581. ASSERT_TRUE(!res);
  3582. EXPECT_EQ(Error::Write, res.error());
  3583. }
  3584. #endif
  3585. TEST_F(ServerTest, Put) {
  3586. auto res = cli_.Put("/put", "PUT", "text/plain");
  3587. ASSERT_TRUE(res);
  3588. EXPECT_EQ(StatusCode::OK_200, res->status);
  3589. EXPECT_EQ("PUT", res->body);
  3590. }
  3591. TEST_F(ServerTest, PutWithContentProvider) {
  3592. auto res = cli_.Put(
  3593. "/put", 3,
  3594. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3595. sink.os << "PUT";
  3596. return true;
  3597. },
  3598. "text/plain");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::OK_200, res->status);
  3601. EXPECT_EQ("PUT", res->body);
  3602. }
  3603. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3604. auto res = cli_.Post(
  3605. "/post", 42,
  3606. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3607. return false;
  3608. },
  3609. "text/plain");
  3610. ASSERT_TRUE(!res);
  3611. EXPECT_EQ(Error::Canceled, res.error());
  3612. }
  3613. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3614. auto res = cli_.Put(
  3615. "/put",
  3616. [](size_t /*offset*/, DataSink &sink) {
  3617. sink.os << "PUT";
  3618. sink.done();
  3619. return true;
  3620. },
  3621. "text/plain");
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::OK_200, res->status);
  3624. EXPECT_EQ("PUT", res->body);
  3625. }
  3626. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3627. auto res = cli_.Post(
  3628. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3629. "text/plain");
  3630. ASSERT_TRUE(!res);
  3631. EXPECT_EQ(Error::Canceled, res.error());
  3632. }
  3633. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3634. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3635. cli_.set_compress(true);
  3636. auto res = cli_.Put(
  3637. "/put", 3,
  3638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3639. sink.os << "PUT";
  3640. return true;
  3641. },
  3642. "text/plain");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("PUT", res->body);
  3646. }
  3647. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3648. cli_.set_compress(true);
  3649. auto res = cli_.Post(
  3650. "/post", 42,
  3651. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3652. return false;
  3653. },
  3654. "text/plain");
  3655. ASSERT_TRUE(!res);
  3656. EXPECT_EQ(Error::Canceled, res.error());
  3657. }
  3658. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3659. cli_.set_compress(true);
  3660. auto res = cli_.Put(
  3661. "/put",
  3662. [](size_t /*offset*/, DataSink &sink) {
  3663. sink.os << "PUT";
  3664. sink.done();
  3665. return true;
  3666. },
  3667. "text/plain");
  3668. ASSERT_TRUE(res);
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. EXPECT_EQ("PUT", res->body);
  3671. }
  3672. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3673. cli_.set_compress(true);
  3674. auto res = cli_.Post(
  3675. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3676. "text/plain");
  3677. ASSERT_TRUE(!res);
  3678. EXPECT_EQ(Error::Canceled, res.error());
  3679. }
  3680. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3681. cli_.set_compress(true);
  3682. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ(LARGE_DATA, res->body);
  3686. }
  3687. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3688. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3689. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3690. Client cli(s.c_str());
  3691. cli.enable_server_certificate_verification(false);
  3692. #else
  3693. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3694. Client cli(s.c_str());
  3695. #endif
  3696. cli.set_compress(true);
  3697. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3698. ASSERT_TRUE(res);
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. EXPECT_EQ(LARGE_DATA, res->body);
  3701. // The compressed size should be less than a 10th of the original. May vary
  3702. // depending on the zlib library.
  3703. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  3704. static_cast<uint64_t>(10 * 1024 * 1024));
  3705. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3706. }
  3707. TEST_F(ServerTest, PutContentWithDeflate) {
  3708. cli_.set_compress(false);
  3709. Headers headers;
  3710. headers.emplace("Content-Encoding", "deflate");
  3711. // PUT in deflate format:
  3712. auto res = cli_.Put("/put", headers,
  3713. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("PUT", res->body);
  3717. }
  3718. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3719. Headers headers;
  3720. headers.emplace("Accept-Encoding", "gzip, deflate");
  3721. auto res = cli_.Get("/streamed-chunked", headers);
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. EXPECT_EQ(std::string("123456789"), res->body);
  3725. }
  3726. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3727. Headers headers;
  3728. headers.emplace("Accept-Encoding", "gzip, deflate");
  3729. auto res = cli_.Get("/streamed-chunked2", headers);
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ(std::string("123456789"), res->body);
  3733. }
  3734. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3735. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. }
  3739. TEST(GzipDecompressor, ChunkedDecompression) {
  3740. std::string data;
  3741. for (size_t i = 0; i < 32 * 1024; ++i) {
  3742. data.push_back(static_cast<char>('a' + i % 26));
  3743. }
  3744. std::string compressed_data;
  3745. {
  3746. httplib::detail::gzip_compressor compressor;
  3747. bool result = compressor.compress(
  3748. data.data(), data.size(),
  3749. /*last=*/true,
  3750. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3751. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3752. compressed_data_size);
  3753. return true;
  3754. });
  3755. ASSERT_TRUE(result);
  3756. }
  3757. std::string decompressed_data;
  3758. {
  3759. httplib::detail::gzip_decompressor decompressor;
  3760. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3761. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3762. size_t chunk_size = 130;
  3763. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3764. chunk_begin += chunk_size) {
  3765. size_t current_chunk_size =
  3766. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3767. bool result = decompressor.decompress(
  3768. compressed_data.data() + chunk_begin, current_chunk_size,
  3769. [&](const char *decompressed_data_chunk,
  3770. size_t decompressed_data_chunk_size) {
  3771. decompressed_data.insert(decompressed_data.size(),
  3772. decompressed_data_chunk,
  3773. decompressed_data_chunk_size);
  3774. return true;
  3775. });
  3776. ASSERT_TRUE(result);
  3777. }
  3778. }
  3779. ASSERT_EQ(data, decompressed_data);
  3780. }
  3781. TEST(GzipDecompressor, DeflateDecompression) {
  3782. std::string original_text = "Raw deflate without gzip";
  3783. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3784. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3785. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3786. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3787. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3788. std::string decompressed_data;
  3789. {
  3790. httplib::detail::gzip_decompressor decompressor;
  3791. bool result = decompressor.decompress(
  3792. compressed_data.data(), compressed_data.size(),
  3793. [&](const char *decompressed_data_chunk,
  3794. size_t decompressed_data_chunk_size) {
  3795. decompressed_data.insert(decompressed_data.size(),
  3796. decompressed_data_chunk,
  3797. decompressed_data_chunk_size);
  3798. return true;
  3799. });
  3800. ASSERT_TRUE(result);
  3801. }
  3802. ASSERT_EQ(original_text, decompressed_data);
  3803. }
  3804. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3805. std::string original_text = "Raw deflate without gzip";
  3806. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3807. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3808. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3809. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3810. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3811. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3812. std::string decompressed_data;
  3813. {
  3814. httplib::detail::gzip_decompressor decompressor;
  3815. bool result = decompressor.decompress(
  3816. compressed_data.data(), compressed_data.size(),
  3817. [&](const char *decompressed_data_chunk,
  3818. size_t decompressed_data_chunk_size) {
  3819. decompressed_data.insert(decompressed_data.size(),
  3820. decompressed_data_chunk,
  3821. decompressed_data_chunk_size);
  3822. return true;
  3823. });
  3824. ASSERT_TRUE(result);
  3825. }
  3826. ASSERT_EQ(original_text, decompressed_data);
  3827. }
  3828. #ifdef _WIN32
  3829. TEST(GzipDecompressor, LargeRandomData) {
  3830. // prepare large random data that is difficult to be compressed and is
  3831. // expected to have large size even when compressed
  3832. std::random_device seed_gen;
  3833. std::mt19937 random(seed_gen());
  3834. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3835. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3836. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3837. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3838. // compress data over 4GiB
  3839. std::string compressed_data;
  3840. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3841. httplib::detail::gzip_compressor compressor;
  3842. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3843. data.size() * sizeof(std::uint32_t), true,
  3844. [&](const char *data, size_t size) {
  3845. compressed_data.insert(
  3846. compressed_data.size(), data, size);
  3847. return true;
  3848. });
  3849. ASSERT_TRUE(result);
  3850. // FIXME: compressed data size is expected to be greater than 4GiB,
  3851. // but there is no guarantee
  3852. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3853. // decompress data over 4GiB
  3854. std::string decompressed_data;
  3855. decompressed_data.reserve(data_size);
  3856. httplib::detail::gzip_decompressor decompressor;
  3857. result = decompressor.decompress(
  3858. compressed_data.data(), compressed_data.size(),
  3859. [&](const char *data, size_t size) {
  3860. decompressed_data.insert(decompressed_data.size(), data, size);
  3861. return true;
  3862. });
  3863. ASSERT_TRUE(result);
  3864. // compare
  3865. ASSERT_EQ(data_size, decompressed_data.size());
  3866. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3867. 0);
  3868. }
  3869. #endif
  3870. #endif
  3871. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3872. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3873. Headers headers;
  3874. headers.emplace("Accept-Encoding", "br");
  3875. auto res = cli_.Get("/streamed-chunked", headers);
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ(std::string("123456789"), res->body);
  3879. }
  3880. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3881. Headers headers;
  3882. headers.emplace("Accept-Encoding", "br");
  3883. auto res = cli_.Get("/streamed-chunked2", headers);
  3884. ASSERT_TRUE(res);
  3885. EXPECT_EQ(StatusCode::OK_200, res->status);
  3886. EXPECT_EQ(std::string("123456789"), res->body);
  3887. }
  3888. #endif
  3889. TEST_F(ServerTest, Patch) {
  3890. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::OK_200, res->status);
  3893. EXPECT_EQ("PATCH", res->body);
  3894. }
  3895. TEST_F(ServerTest, Delete) {
  3896. auto res = cli_.Delete("/delete");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::OK_200, res->status);
  3899. EXPECT_EQ("DELETE", res->body);
  3900. }
  3901. TEST_F(ServerTest, DeleteContentReceiver) {
  3902. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::OK_200, res->status);
  3905. EXPECT_EQ("content", res->body);
  3906. }
  3907. TEST_F(ServerTest, Options) {
  3908. auto res = cli_.Options("*");
  3909. ASSERT_TRUE(res);
  3910. EXPECT_EQ(StatusCode::OK_200, res->status);
  3911. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3912. EXPECT_TRUE(res->body.empty());
  3913. }
  3914. TEST_F(ServerTest, URL) {
  3915. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, ArrayParam) {
  3920. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. }
  3924. TEST_F(ServerTest, NoMultipleHeaders) {
  3925. Headers headers = {{"Content-Length", "5"}};
  3926. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3927. "text/plain");
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::OK_200, res->status);
  3930. }
  3931. TEST_F(ServerTest, PostContentReceiver) {
  3932. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3933. ASSERT_TRUE(res);
  3934. ASSERT_EQ(StatusCode::OK_200, res->status);
  3935. ASSERT_EQ("content", res->body);
  3936. }
  3937. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3938. MultipartFormDataItems items = {
  3939. {"text1", "text default", "", ""},
  3940. {"text2", "aωb", "", ""},
  3941. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3942. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3943. {"file3", "", "", "application/octet-stream"},
  3944. };
  3945. auto res = cli_.Post("/content_receiver", items);
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. }
  3949. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3950. MultipartFormDataItems items = {
  3951. {"text1", "text default", "", ""},
  3952. {"text2", "aωb", "", ""},
  3953. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3954. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3955. {"file3", "", "", "application/octet-stream"},
  3956. };
  3957. auto boundary = std::string("+++++");
  3958. std::string body;
  3959. for (const auto &item : items) {
  3960. body += "--" + boundary + "\r\n";
  3961. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3962. if (!item.filename.empty()) {
  3963. body += "; filename=\"" + item.filename + "\"";
  3964. }
  3965. body += "\r\n";
  3966. if (!item.content_type.empty()) {
  3967. body += "Content-Type: " + item.content_type + "\r\n";
  3968. }
  3969. body += "\r\n";
  3970. body += item.content + "\r\n";
  3971. }
  3972. body += "--" + boundary + "--\r\n";
  3973. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3974. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::OK_200, res->status);
  3977. }
  3978. TEST_F(ServerTest, PostContentReceiverGzip) {
  3979. cli_.set_compress(true);
  3980. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3981. ASSERT_TRUE(res);
  3982. ASSERT_EQ(StatusCode::OK_200, res->status);
  3983. ASSERT_EQ("content", res->body);
  3984. }
  3985. TEST_F(ServerTest, PutContentReceiver) {
  3986. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3987. ASSERT_TRUE(res);
  3988. ASSERT_EQ(StatusCode::OK_200, res->status);
  3989. ASSERT_EQ("content", res->body);
  3990. }
  3991. TEST_F(ServerTest, PatchContentReceiver) {
  3992. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3993. ASSERT_TRUE(res);
  3994. ASSERT_EQ(StatusCode::OK_200, res->status);
  3995. ASSERT_EQ("content", res->body);
  3996. }
  3997. TEST_F(ServerTest, PostQueryStringAndBody) {
  3998. auto res =
  3999. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4000. ASSERT_TRUE(res);
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. }
  4003. TEST_F(ServerTest, HTTP2Magic) {
  4004. Request req;
  4005. req.method = "PRI";
  4006. req.path = "*";
  4007. req.body = "SM";
  4008. auto res = std::make_shared<Response>();
  4009. auto error = Error::Success;
  4010. auto ret = cli_.send(req, *res, error);
  4011. ASSERT_TRUE(ret);
  4012. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4013. }
  4014. TEST_F(ServerTest, KeepAlive) {
  4015. auto res = cli_.Get("/hi");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::OK_200, res->status);
  4018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4019. EXPECT_EQ("Hello World!", res->body);
  4020. res = cli_.Get("/hi");
  4021. ASSERT_TRUE(res);
  4022. EXPECT_EQ(StatusCode::OK_200, res->status);
  4023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4024. EXPECT_EQ("Hello World!", res->body);
  4025. res = cli_.Get("/hi");
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::OK_200, res->status);
  4028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4029. EXPECT_EQ("Hello World!", res->body);
  4030. res = cli_.Get("/not-exist");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4033. res = cli_.Post("/empty", "", "text/plain");
  4034. ASSERT_TRUE(res);
  4035. EXPECT_EQ(StatusCode::OK_200, res->status);
  4036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4037. EXPECT_EQ("empty", res->body);
  4038. EXPECT_EQ("close", res->get_header_value("Connection"));
  4039. res = cli_.Post(
  4040. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4041. "text/plain");
  4042. ASSERT_TRUE(res);
  4043. EXPECT_EQ(StatusCode::OK_200, res->status);
  4044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4045. EXPECT_EQ("empty", res->body);
  4046. cli_.set_keep_alive(false);
  4047. res = cli_.Get("/last-request");
  4048. ASSERT_TRUE(res);
  4049. EXPECT_EQ(StatusCode::OK_200, res->status);
  4050. EXPECT_EQ("close", res->get_header_value("Connection"));
  4051. }
  4052. TEST_F(ServerTest, TooManyRedirect) {
  4053. cli_.set_follow_location(true);
  4054. auto res = cli_.Get("/redirect/0");
  4055. ASSERT_TRUE(!res);
  4056. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4057. }
  4058. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4059. TEST_F(ServerTest, Gzip) {
  4060. Headers headers;
  4061. headers.emplace("Accept-Encoding", "gzip, deflate");
  4062. auto res = cli_.Get("/compress", headers);
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4066. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4068. "7890123456789012345678901234567890",
  4069. res->body);
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. }
  4072. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4073. Headers headers;
  4074. headers.emplace("Accept-Encoding", "");
  4075. auto res = cli_.Get("/compress", headers);
  4076. ASSERT_TRUE(res);
  4077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4081. "7890123456789012345678901234567890",
  4082. res->body);
  4083. EXPECT_EQ(StatusCode::OK_200, res->status);
  4084. }
  4085. TEST_F(ServerTest, GzipWithContentReceiver) {
  4086. Headers headers;
  4087. headers.emplace("Accept-Encoding", "gzip, deflate");
  4088. std::string body;
  4089. auto res = cli_.Get("/compress", headers,
  4090. [&](const char *data, uint64_t data_length) {
  4091. EXPECT_EQ(100U, data_length);
  4092. body.append(data, data_length);
  4093. return true;
  4094. });
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4098. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4100. "7890123456789012345678901234567890",
  4101. body);
  4102. EXPECT_EQ(StatusCode::OK_200, res->status);
  4103. }
  4104. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4105. Headers headers;
  4106. headers.emplace("Accept-Encoding", "gzip, deflate");
  4107. cli_.set_decompress(false);
  4108. auto res = cli_.Get("/compress", headers);
  4109. ASSERT_TRUE(res);
  4110. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4112. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4113. EXPECT_EQ(33U, res->body.size());
  4114. EXPECT_EQ(StatusCode::OK_200, res->status);
  4115. }
  4116. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4117. Headers headers;
  4118. headers.emplace("Accept-Encoding", "");
  4119. std::string body;
  4120. auto res = cli_.Get("/compress", headers,
  4121. [&](const char *data, uint64_t data_length) {
  4122. EXPECT_EQ(100U, data_length);
  4123. body.append(data, data_length);
  4124. return true;
  4125. });
  4126. ASSERT_TRUE(res);
  4127. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4129. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4130. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4131. "7890123456789012345678901234567890",
  4132. body);
  4133. EXPECT_EQ(StatusCode::OK_200, res->status);
  4134. }
  4135. TEST_F(ServerTest, NoGzip) {
  4136. Headers headers;
  4137. headers.emplace("Accept-Encoding", "gzip, deflate");
  4138. auto res = cli_.Get("/nocompress", headers);
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4144. "7890123456789012345678901234567890",
  4145. res->body);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. }
  4148. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4149. Headers headers;
  4150. headers.emplace("Accept-Encoding", "gzip, deflate");
  4151. std::string body;
  4152. auto res = cli_.Get("/nocompress", headers,
  4153. [&](const char *data, uint64_t data_length) {
  4154. EXPECT_EQ(100U, data_length);
  4155. body.append(data, data_length);
  4156. return true;
  4157. });
  4158. ASSERT_TRUE(res);
  4159. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4160. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4163. "7890123456789012345678901234567890",
  4164. body);
  4165. EXPECT_EQ(StatusCode::OK_200, res->status);
  4166. }
  4167. TEST_F(ServerTest, MultipartFormDataGzip) {
  4168. MultipartFormDataItems items = {
  4169. {"key1", "test", "", ""},
  4170. {"key2", "--abcdefg123", "", ""},
  4171. };
  4172. cli_.set_compress(true);
  4173. auto res = cli_.Post("/compress-multipart", items);
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. }
  4177. #endif
  4178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4179. TEST_F(ServerTest, Brotli) {
  4180. Headers headers;
  4181. headers.emplace("Accept-Encoding", "br");
  4182. auto res = cli_.Get("/compress", headers);
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4186. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4188. "7890123456789012345678901234567890",
  4189. res->body);
  4190. EXPECT_EQ(StatusCode::OK_200, res->status);
  4191. }
  4192. #endif
  4193. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4194. TEST_F(ServerTest, Zstd) {
  4195. Headers headers;
  4196. headers.emplace("Accept-Encoding", "zstd");
  4197. auto res = cli_.Get("/compress", headers);
  4198. ASSERT_TRUE(res);
  4199. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4201. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4202. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4203. "7890123456789012345678901234567890",
  4204. res->body);
  4205. EXPECT_EQ(StatusCode::OK_200, res->status);
  4206. }
  4207. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4208. Headers headers;
  4209. headers.emplace("Accept-Encoding", "");
  4210. auto res = cli_.Get("/compress", headers);
  4211. ASSERT_TRUE(res);
  4212. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4214. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4215. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4216. "7890123456789012345678901234567890",
  4217. res->body);
  4218. EXPECT_EQ(StatusCode::OK_200, res->status);
  4219. }
  4220. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4221. Headers headers;
  4222. headers.emplace("Accept-Encoding", "zstd");
  4223. std::string body;
  4224. auto res = cli_.Get("/compress", headers,
  4225. [&](const char *data, uint64_t data_length) {
  4226. EXPECT_EQ(100U, data_length);
  4227. body.append(data, data_length);
  4228. return true;
  4229. });
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4233. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4235. "7890123456789012345678901234567890",
  4236. body);
  4237. EXPECT_EQ(StatusCode::OK_200, res->status);
  4238. }
  4239. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4240. Headers headers;
  4241. headers.emplace("Accept-Encoding", "zstd");
  4242. cli_.set_decompress(false);
  4243. auto res = cli_.Get("/compress", headers);
  4244. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4245. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4246. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4247. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4250. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4251. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. ASSERT_EQ(26U, res->body.size());
  4254. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4255. 0);
  4256. }
  4257. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4258. Headers headers;
  4259. headers.emplace("Accept-Encoding", "");
  4260. std::string body;
  4261. auto res = cli_.Get("/compress", headers,
  4262. [&](const char *data, uint64_t data_length) {
  4263. EXPECT_EQ(100U, data_length);
  4264. body.append(data, data_length);
  4265. return true;
  4266. });
  4267. ASSERT_TRUE(res);
  4268. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4269. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4270. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4271. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4272. "7890123456789012345678901234567890",
  4273. body);
  4274. EXPECT_EQ(StatusCode::OK_200, res->status);
  4275. }
  4276. TEST_F(ServerTest, NoZstd) {
  4277. Headers headers;
  4278. headers.emplace("Accept-Encoding", "zstd");
  4279. auto res = cli_.Get("/nocompress", headers);
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4282. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4283. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4285. "7890123456789012345678901234567890",
  4286. res->body);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. }
  4289. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4290. Headers headers;
  4291. headers.emplace("Accept-Encoding", "zstd");
  4292. std::string body;
  4293. auto res = cli_.Get("/nocompress", headers,
  4294. [&](const char *data, uint64_t data_length) {
  4295. EXPECT_EQ(100U, data_length);
  4296. body.append(data, data_length);
  4297. return true;
  4298. });
  4299. ASSERT_TRUE(res);
  4300. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4301. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4304. "7890123456789012345678901234567890",
  4305. body);
  4306. EXPECT_EQ(StatusCode::OK_200, res->status);
  4307. }
  4308. // TODO: How to enable zstd ??
  4309. TEST_F(ServerTest, MultipartFormDataZstd) {
  4310. MultipartFormDataItems items = {
  4311. {"key1", "test", "", ""},
  4312. {"key2", "--abcdefg123", "", ""},
  4313. };
  4314. Headers headers;
  4315. headers.emplace("Accept-Encoding", "zstd");
  4316. cli_.set_compress(true);
  4317. auto res = cli_.Post("/compress-multipart", headers, items);
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. }
  4321. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4322. Headers headers;
  4323. headers.emplace("Accept-Encoding", "zstd");
  4324. cli_.set_compress(true);
  4325. auto res = cli_.Put(
  4326. "/put", headers, 3,
  4327. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4328. sink.os << "PUT";
  4329. return true;
  4330. },
  4331. "text/plain");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("PUT", res->body);
  4335. }
  4336. TEST(ZstdDecompressor, ChunkedDecompression) {
  4337. std::string data;
  4338. for (size_t i = 0; i < 32 * 1024; ++i) {
  4339. data.push_back(static_cast<char>('a' + i % 26));
  4340. }
  4341. std::string compressed_data;
  4342. {
  4343. httplib::detail::zstd_compressor compressor;
  4344. bool result = compressor.compress(
  4345. data.data(), data.size(),
  4346. /*last=*/true,
  4347. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4348. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4349. compressed_data_size);
  4350. return true;
  4351. });
  4352. ASSERT_TRUE(result);
  4353. }
  4354. std::string decompressed_data;
  4355. {
  4356. httplib::detail::zstd_decompressor decompressor;
  4357. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4358. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4359. size_t chunk_size = 130;
  4360. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4361. chunk_begin += chunk_size) {
  4362. size_t current_chunk_size =
  4363. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4364. bool result = decompressor.decompress(
  4365. compressed_data.data() + chunk_begin, current_chunk_size,
  4366. [&](const char *decompressed_data_chunk,
  4367. size_t decompressed_data_chunk_size) {
  4368. decompressed_data.insert(decompressed_data.size(),
  4369. decompressed_data_chunk,
  4370. decompressed_data_chunk_size);
  4371. return true;
  4372. });
  4373. ASSERT_TRUE(result);
  4374. }
  4375. }
  4376. ASSERT_EQ(data, decompressed_data);
  4377. }
  4378. TEST(ZstdDecompressor, Decompress) {
  4379. std::string original_text = "Compressed with ZSTD";
  4380. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4381. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4382. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4383. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4384. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4385. std::string decompressed_data;
  4386. {
  4387. httplib::detail::zstd_decompressor decompressor;
  4388. bool result = decompressor.decompress(
  4389. compressed_data.data(), compressed_data.size(),
  4390. [&](const char *decompressed_data_chunk,
  4391. size_t decompressed_data_chunk_size) {
  4392. decompressed_data.insert(decompressed_data.size(),
  4393. decompressed_data_chunk,
  4394. decompressed_data_chunk_size);
  4395. return true;
  4396. });
  4397. ASSERT_TRUE(result);
  4398. }
  4399. ASSERT_EQ(original_text, decompressed_data);
  4400. }
  4401. #endif
  4402. // Sends a raw request to a server listening at HOST:PORT.
  4403. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4404. std::string *resp = nullptr) {
  4405. auto error = Error::Success;
  4406. auto client_sock = detail::create_client_socket(
  4407. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4408. /*connection_timeout_sec=*/5, 0,
  4409. /*read_timeout_sec=*/5, 0,
  4410. /*write_timeout_sec=*/5, 0, std::string(), error);
  4411. if (client_sock == INVALID_SOCKET) { return false; }
  4412. auto ret = detail::process_client_socket(
  4413. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4414. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4415. if (req.size() !=
  4416. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4417. return false;
  4418. }
  4419. char buf[512];
  4420. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4421. while (line_reader.getline()) {
  4422. if (resp) { *resp += line_reader.ptr(); }
  4423. }
  4424. return true;
  4425. });
  4426. detail::close_socket(client_sock);
  4427. return ret;
  4428. }
  4429. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4430. Server svr;
  4431. std::string header_value;
  4432. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4433. header_value = req.get_header_value("foo");
  4434. res.set_content("ok", "text/plain");
  4435. });
  4436. thread t = thread([&] { svr.listen(HOST, PORT); });
  4437. auto se = detail::scope_exit([&] {
  4438. svr.stop();
  4439. t.join();
  4440. ASSERT_FALSE(svr.is_running());
  4441. });
  4442. svr.wait_until_ready();
  4443. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4444. // like characters are not treated the same - use vertical tab and escape.
  4445. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4446. "foo: \t \v bar \x1B\t \r\n"
  4447. "Connection: close\r\n"
  4448. "\r\n";
  4449. std::string res;
  4450. ASSERT_TRUE(send_request(5, req, &res));
  4451. EXPECT_EQ(header_value, "");
  4452. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4453. }
  4454. // Sends a raw request and verifies that there isn't a crash or exception.
  4455. static void test_raw_request(const std::string &req,
  4456. std::string *out = nullptr) {
  4457. Server svr;
  4458. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4459. res.set_content("ok", "text/plain");
  4460. });
  4461. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4462. res.set_content("ok", "text/plain");
  4463. });
  4464. svr.Get("/header_field_value_check",
  4465. [&](const Request & /*req*/, Response &res) {
  4466. res.set_content("ok", "text/plain");
  4467. });
  4468. // Server read timeout must be longer than the client read timeout for the
  4469. // bug to reproduce, probably to force the server to process a request
  4470. // without a trailing blank line.
  4471. const time_t client_read_timeout_sec = 1;
  4472. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4473. bool listen_thread_ok = false;
  4474. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4475. auto se = detail::scope_exit([&] {
  4476. svr.stop();
  4477. t.join();
  4478. ASSERT_FALSE(svr.is_running());
  4479. EXPECT_TRUE(listen_thread_ok);
  4480. });
  4481. svr.wait_until_ready();
  4482. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4483. }
  4484. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4485. // A certain header line causes an exception if the header property is parsed
  4486. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4487. test_raw_request(
  4488. "GET /hi HTTP/1.1\r\n"
  4489. " : "
  4490. " "
  4491. " ");
  4492. }
  4493. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4494. // A certain header line causes an exception if the header property *name* is
  4495. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4496. // greedy matcher and requires backtracking when there are a lot of ":"
  4497. // characters.
  4498. // This occurs with libc++ but not libstdc++.
  4499. test_raw_request(
  4500. "GET /hi HTTP/1.1\r\n"
  4501. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4502. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4503. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4504. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4505. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4506. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4507. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4508. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4509. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4510. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4511. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4512. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4513. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4514. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4515. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4516. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4517. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4518. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4519. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4520. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4521. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4522. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4523. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4524. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4525. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4526. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4527. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4528. "&&&%%%");
  4529. }
  4530. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4531. // Make sure this doesn't crash the server.
  4532. // In a previous version of the header line regex, the "\r" rendered the line
  4533. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4534. // a new position where the leading white space ended and the field value
  4535. // began.
  4536. // The crash occurs with libc++ but not libstdc++.
  4537. test_raw_request("GET /hi HTTP/1.1\r\n"
  4538. "a:" +
  4539. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4540. "\r\n"
  4541. "\r\n");
  4542. }
  4543. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4544. std::string out;
  4545. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4546. "Content-Type: text/plain\r\n"
  4547. "Transfer-Encoding: chunked\r\n"
  4548. "\r\n"
  4549. "nothex\r\n",
  4550. &out);
  4551. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4552. }
  4553. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4554. std::string out;
  4555. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4556. "Content-Type: text/plain\r\n"
  4557. "Transfer-Encoding: chunked\r\n"
  4558. "\r\n"
  4559. "3\r\n"
  4560. "xyz\r\n"
  4561. "NaN\r\n",
  4562. &out);
  4563. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4564. }
  4565. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4566. std::string out;
  4567. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4568. "Content-Type: text/plain\r\n"
  4569. "Transfer-Encoding: chunked\r\n"
  4570. "\r\n"
  4571. // Length is too large for 64 bits.
  4572. "1ffffffffffffffff\r\n"
  4573. "xyz\r\n",
  4574. &out);
  4575. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4576. }
  4577. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4578. test_raw_request("GET /hi HTTP/1.1\r\n"
  4579. "Content-Type: text/plain\r\n\r");
  4580. }
  4581. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4582. std::string out;
  4583. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4584. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4585. }
  4586. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4587. std::string out;
  4588. std::string request(
  4589. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4590. test_raw_request(request, &out);
  4591. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4592. }
  4593. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  4594. std::string out;
  4595. std::string request(
  4596. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  4597. test_raw_request(request, &out);
  4598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4599. }
  4600. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  4601. std::string out;
  4602. std::string request(
  4603. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  4604. test_raw_request(request, &out);
  4605. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4606. }
  4607. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  4608. std::string out;
  4609. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  4610. "Test: \r\n\r\n",
  4611. &out);
  4612. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  4613. }
  4614. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4615. Server svr;
  4616. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4617. res.set_header("Cache-Control", "no-cache");
  4618. res.set_chunked_content_provider(
  4619. "text/event-stream", [](size_t offset, DataSink &sink) {
  4620. std::string s = "data:";
  4621. s += std::to_string(offset);
  4622. s += "\n\n";
  4623. auto ret = sink.write(s.data(), s.size());
  4624. EXPECT_TRUE(ret);
  4625. std::this_thread::sleep_for(std::chrono::seconds(1));
  4626. return true;
  4627. });
  4628. });
  4629. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4630. svr.wait_until_ready();
  4631. Client client(HOST, PORT);
  4632. const Headers headers = {{"Accept", "text/event-stream"}};
  4633. auto get_thread = std::thread([&client, &headers]() {
  4634. auto res = client.Get(
  4635. "/events", headers,
  4636. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4637. });
  4638. auto se = detail::scope_exit([&] {
  4639. svr.stop();
  4640. get_thread.join();
  4641. listen_thread.join();
  4642. ASSERT_FALSE(svr.is_running());
  4643. });
  4644. // Give GET time to get a few messages.
  4645. std::this_thread::sleep_for(std::chrono::seconds(2));
  4646. }
  4647. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4648. httplib::Server svr;
  4649. svr.Post("/hi",
  4650. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4651. res.status = StatusCode::OK_200;
  4652. });
  4653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4654. svr.wait_until_ready();
  4655. Client cli(HOST, PORT);
  4656. auto res = cli.Post("/hi", "data", "text/plain");
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. svr.stop();
  4660. thread.join();
  4661. ASSERT_FALSE(svr.is_running());
  4662. res = cli.Post("/hi", "data", "text/plain");
  4663. ASSERT_FALSE(res);
  4664. }
  4665. TEST(ServerStopTest, ListenFailure) {
  4666. Server svr;
  4667. auto t = thread([&]() {
  4668. auto ret = svr.listen("????", PORT);
  4669. EXPECT_FALSE(ret);
  4670. });
  4671. svr.wait_until_ready();
  4672. svr.stop();
  4673. t.join();
  4674. }
  4675. TEST(ServerStopTest, Decommision) {
  4676. Server svr;
  4677. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4678. for (int i = 0; i < 4; i++) {
  4679. auto is_even = !(i % 2);
  4680. std::thread t{[&] {
  4681. try {
  4682. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4683. if (is_even) {
  4684. throw std::runtime_error("Some thing that happens to go wrong.");
  4685. }
  4686. svr.listen(HOST, PORT);
  4687. } catch (...) { svr.decommission(); }
  4688. }};
  4689. svr.wait_until_ready();
  4690. // Server is up
  4691. {
  4692. Client cli(HOST, PORT);
  4693. auto res = cli.Get("/hi");
  4694. if (is_even) {
  4695. EXPECT_FALSE(res);
  4696. } else {
  4697. EXPECT_TRUE(res);
  4698. EXPECT_EQ("hi...", res->body);
  4699. }
  4700. }
  4701. svr.stop();
  4702. t.join();
  4703. // Server is down...
  4704. {
  4705. Client cli(HOST, PORT);
  4706. auto res = cli.Get("/hi");
  4707. EXPECT_FALSE(res);
  4708. }
  4709. }
  4710. }
  4711. TEST(StreamingTest, NoContentLengthStreaming) {
  4712. Server svr;
  4713. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4714. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4715. if (offset < 6) {
  4716. sink.os << (offset < 3 ? "a" : "b");
  4717. } else {
  4718. sink.done();
  4719. }
  4720. return true;
  4721. });
  4722. });
  4723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4724. auto listen_se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. listen_thread.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. Client client(HOST, PORT);
  4731. auto get_thread = std::thread([&client]() {
  4732. std::string s;
  4733. auto res =
  4734. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4735. s += std::string(data, len);
  4736. return true;
  4737. });
  4738. ASSERT_TRUE(res);
  4739. EXPECT_EQ(StatusCode::OK_200, res->status);
  4740. EXPECT_EQ("aaabbb", s);
  4741. });
  4742. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4743. // Give GET time to get a few messages.
  4744. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4745. }
  4746. TEST(MountTest, Unmount) {
  4747. Server svr;
  4748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4749. auto se = detail::scope_exit([&] {
  4750. svr.stop();
  4751. listen_thread.join();
  4752. ASSERT_FALSE(svr.is_running());
  4753. });
  4754. svr.wait_until_ready();
  4755. Client cli("localhost", PORT);
  4756. svr.set_mount_point("/mount2", "./www2");
  4757. auto res = cli.Get("/");
  4758. ASSERT_TRUE(res);
  4759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4760. res = cli.Get("/mount2/dir/test.html");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. svr.set_mount_point("/", "./www");
  4764. res = cli.Get("/dir/");
  4765. ASSERT_TRUE(res);
  4766. EXPECT_EQ(StatusCode::OK_200, res->status);
  4767. svr.remove_mount_point("/");
  4768. res = cli.Get("/dir/");
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4771. svr.remove_mount_point("/mount2");
  4772. res = cli.Get("/mount2/dir/test.html");
  4773. ASSERT_TRUE(res);
  4774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4775. }
  4776. TEST(MountTest, Redicect) {
  4777. Server svr;
  4778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. listen_thread.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.set_mount_point("/", "./www");
  4785. svr.wait_until_ready();
  4786. Client cli("localhost", PORT);
  4787. auto res = cli.Get("/dir/");
  4788. ASSERT_TRUE(res);
  4789. EXPECT_EQ(StatusCode::OK_200, res->status);
  4790. res = cli.Get("/dir");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4793. res = cli.Get("/file");
  4794. ASSERT_TRUE(res);
  4795. EXPECT_EQ(StatusCode::OK_200, res->status);
  4796. res = cli.Get("/file/");
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4799. cli.set_follow_location(true);
  4800. res = cli.Get("/dir");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. }
  4804. TEST(MountTest, MultibytesPathName) {
  4805. Server svr;
  4806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4807. auto se = detail::scope_exit([&] {
  4808. svr.stop();
  4809. listen_thread.join();
  4810. ASSERT_FALSE(svr.is_running());
  4811. });
  4812. svr.set_mount_point("/", "./www");
  4813. svr.wait_until_ready();
  4814. Client cli("localhost", PORT);
  4815. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  4816. ASSERT_TRUE(res);
  4817. EXPECT_EQ(StatusCode::OK_200, res->status);
  4818. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  4819. }
  4820. TEST(KeepAliveTest, ReadTimeout) {
  4821. Server svr;
  4822. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4823. std::this_thread::sleep_for(std::chrono::seconds(2));
  4824. res.set_content("a", "text/plain");
  4825. });
  4826. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4827. res.set_content("b", "text/plain");
  4828. });
  4829. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4830. auto se = detail::scope_exit([&] {
  4831. svr.stop();
  4832. listen_thread.join();
  4833. ASSERT_FALSE(svr.is_running());
  4834. });
  4835. svr.wait_until_ready();
  4836. Client cli("localhost", PORT);
  4837. cli.set_keep_alive(true);
  4838. cli.set_read_timeout(std::chrono::seconds(1));
  4839. auto resa = cli.Get("/a");
  4840. ASSERT_FALSE(resa);
  4841. EXPECT_EQ(Error::Read, resa.error());
  4842. auto resb = cli.Get("/b");
  4843. ASSERT_TRUE(resb);
  4844. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4845. EXPECT_EQ("b", resb->body);
  4846. }
  4847. TEST(KeepAliveTest, Issue1041) {
  4848. Server svr;
  4849. svr.set_keep_alive_timeout(3);
  4850. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4851. res.set_content("Hello World!", "text/plain");
  4852. });
  4853. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4854. auto se = detail::scope_exit([&] {
  4855. svr.stop();
  4856. listen_thread.join();
  4857. ASSERT_FALSE(svr.is_running());
  4858. });
  4859. svr.wait_until_ready();
  4860. Client cli(HOST, PORT);
  4861. cli.set_keep_alive(true);
  4862. auto result = cli.Get("/hi");
  4863. ASSERT_TRUE(result);
  4864. EXPECT_EQ(StatusCode::OK_200, result->status);
  4865. std::this_thread::sleep_for(std::chrono::seconds(5));
  4866. result = cli.Get("/hi");
  4867. ASSERT_TRUE(result);
  4868. EXPECT_EQ(StatusCode::OK_200, result->status);
  4869. }
  4870. TEST(KeepAliveTest, Issue1959) {
  4871. Server svr;
  4872. svr.set_keep_alive_timeout(5);
  4873. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4874. res.set_content("a", "text/plain");
  4875. });
  4876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4877. auto se = detail::scope_exit([&] {
  4878. if (!svr.is_running()) return;
  4879. svr.stop();
  4880. listen_thread.join();
  4881. ASSERT_FALSE(svr.is_running());
  4882. });
  4883. svr.wait_until_ready();
  4884. Client cli("localhost", PORT);
  4885. cli.set_keep_alive(true);
  4886. using namespace std::chrono;
  4887. auto start = steady_clock::now();
  4888. cli.Get("/a");
  4889. svr.stop();
  4890. listen_thread.join();
  4891. auto end = steady_clock::now();
  4892. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4893. EXPECT_LT(elapsed, 5000);
  4894. }
  4895. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4896. TEST(KeepAliveTest, SSLClientReconnection) {
  4897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4898. ASSERT_TRUE(svr.is_valid());
  4899. svr.set_keep_alive_timeout(1);
  4900. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4901. res.set_content("Hello World!", "text/plain");
  4902. });
  4903. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4904. auto se = detail::scope_exit([&] {
  4905. svr.stop();
  4906. listen_thread.join();
  4907. ASSERT_FALSE(svr.is_running());
  4908. });
  4909. svr.wait_until_ready();
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. cli.set_keep_alive(true);
  4913. auto result = cli.Get("/hi");
  4914. ASSERT_TRUE(result);
  4915. EXPECT_EQ(StatusCode::OK_200, result->status);
  4916. result = cli.Get("/hi");
  4917. ASSERT_TRUE(result);
  4918. EXPECT_EQ(StatusCode::OK_200, result->status);
  4919. std::this_thread::sleep_for(std::chrono::seconds(2));
  4920. // Recoonect
  4921. result = cli.Get("/hi");
  4922. ASSERT_TRUE(result);
  4923. EXPECT_EQ(StatusCode::OK_200, result->status);
  4924. result = cli.Get("/hi");
  4925. ASSERT_TRUE(result);
  4926. EXPECT_EQ(StatusCode::OK_200, result->status);
  4927. }
  4928. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4930. ASSERT_TRUE(svr.is_valid());
  4931. svr.set_keep_alive_timeout(1);
  4932. std::string content = "reconnect";
  4933. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4934. res.set_content("Hello World!", "text/plain");
  4935. });
  4936. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. listen_thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. SSLClient cli(HOST, PORT);
  4944. cli.enable_server_certificate_verification(false);
  4945. cli.set_keep_alive(true);
  4946. auto result = cli.Post(
  4947. "/hi", content.size(),
  4948. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4949. sink.write(content.c_str(), content.size());
  4950. return true;
  4951. },
  4952. "text/plain");
  4953. ASSERT_TRUE(result);
  4954. EXPECT_EQ(200, result->status);
  4955. std::this_thread::sleep_for(std::chrono::seconds(2));
  4956. // Recoonect
  4957. result = cli.Post(
  4958. "/hi", content.size(),
  4959. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4960. sink.write(content.c_str(), content.size());
  4961. return true;
  4962. },
  4963. "text/plain");
  4964. ASSERT_TRUE(result);
  4965. EXPECT_EQ(200, result->status);
  4966. result = cli.Post(
  4967. "/hi", content.size(),
  4968. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4969. sink.write(content.c_str(), content.size());
  4970. return true;
  4971. },
  4972. "text/plain");
  4973. ASSERT_TRUE(result);
  4974. EXPECT_EQ(200, result->status);
  4975. }
  4976. #endif
  4977. TEST(ClientProblemDetectionTest, ContentProvider) {
  4978. Server svr;
  4979. size_t content_length = 1024 * 1024;
  4980. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4981. res.set_content_provider(
  4982. content_length, "text/plain",
  4983. [&](size_t offset, size_t length, DataSink &sink) {
  4984. auto out_len = std::min(length, static_cast<size_t>(1024));
  4985. std::string out(out_len, '@');
  4986. sink.write(out.data(), out_len);
  4987. return offset < 4096;
  4988. },
  4989. [](bool success) { ASSERT_FALSE(success); });
  4990. });
  4991. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4992. res.set_content_provider(
  4993. 0, "text/plain",
  4994. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4995. EXPECT_TRUE(false);
  4996. return true;
  4997. },
  4998. [](bool success) { ASSERT_FALSE(success); });
  4999. });
  5000. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5001. auto se = detail::scope_exit([&] {
  5002. svr.stop();
  5003. listen_thread.join();
  5004. ASSERT_FALSE(svr.is_running());
  5005. });
  5006. svr.wait_until_ready();
  5007. Client cli("localhost", PORT);
  5008. {
  5009. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5010. size_t /*data_length*/) { return false; });
  5011. ASSERT_FALSE(res);
  5012. }
  5013. {
  5014. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5015. size_t /*data_length*/) { return false; });
  5016. ASSERT_TRUE(res);
  5017. }
  5018. }
  5019. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5020. Server svr;
  5021. svr.set_error_handler([](Request const &, Response &res) -> void {
  5022. res.set_chunked_content_provider(
  5023. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5024. sink.os << "hello";
  5025. sink.os << "world";
  5026. sink.done();
  5027. return true;
  5028. });
  5029. });
  5030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5031. auto se = detail::scope_exit([&] {
  5032. svr.stop();
  5033. listen_thread.join();
  5034. ASSERT_FALSE(svr.is_running());
  5035. });
  5036. svr.wait_until_ready();
  5037. Client cli("localhost", PORT);
  5038. auto res = cli.Get("/");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5041. EXPECT_EQ("helloworld", res->body);
  5042. }
  5043. TEST(LongPollingTest, ClientCloseDetection) {
  5044. Server svr;
  5045. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5046. res.set_chunked_content_provider(
  5047. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5048. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5049. sink.os << "hello";
  5050. auto count = 10;
  5051. while (count > 0 && sink.is_writable()) {
  5052. this_thread::sleep_for(chrono::milliseconds(10));
  5053. count--;
  5054. }
  5055. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5056. return true;
  5057. });
  5058. });
  5059. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5060. auto se = detail::scope_exit([&] {
  5061. svr.stop();
  5062. listen_thread.join();
  5063. ASSERT_FALSE(svr.is_running());
  5064. });
  5065. svr.wait_until_ready();
  5066. Client cli("localhost", PORT);
  5067. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5068. EXPECT_EQ("hello", string(data, data_length));
  5069. return false; // close the socket immediately.
  5070. });
  5071. ASSERT_FALSE(res);
  5072. }
  5073. TEST(GetWithParametersTest, GetWithParameters) {
  5074. Server svr;
  5075. svr.Get("/", [&](const Request &req, Response &) {
  5076. EXPECT_EQ("world", req.get_param_value("hello"));
  5077. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5078. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5079. });
  5080. svr.Get("/params", [&](const Request &req, Response &) {
  5081. EXPECT_EQ("world", req.get_param_value("hello"));
  5082. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5083. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5084. });
  5085. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5086. EXPECT_EQ("resource-id", req.matches[1]);
  5087. EXPECT_EQ("foo", req.get_param_value("param1"));
  5088. EXPECT_EQ("bar", req.get_param_value("param2"));
  5089. });
  5090. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5091. EXPECT_EQ("user-id", req.path_params.at("id"));
  5092. EXPECT_EQ("foo", req.get_param_value("param1"));
  5093. EXPECT_EQ("bar", req.get_param_value("param2"));
  5094. });
  5095. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5096. auto se = detail::scope_exit([&] {
  5097. svr.stop();
  5098. listen_thread.join();
  5099. ASSERT_FALSE(svr.is_running());
  5100. });
  5101. svr.wait_until_ready();
  5102. {
  5103. Client cli(HOST, PORT);
  5104. Params params;
  5105. params.emplace("hello", "world");
  5106. params.emplace("hello2", "world2");
  5107. params.emplace("hello3", "world3");
  5108. auto res = cli.Get("/", params, Headers{});
  5109. ASSERT_TRUE(res);
  5110. EXPECT_EQ(StatusCode::OK_200, res->status);
  5111. }
  5112. {
  5113. Client cli(HOST, PORT);
  5114. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. }
  5118. {
  5119. Client cli(HOST, PORT);
  5120. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5121. ASSERT_TRUE(res);
  5122. EXPECT_EQ(StatusCode::OK_200, res->status);
  5123. }
  5124. {
  5125. Client cli(HOST, PORT);
  5126. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5127. ASSERT_TRUE(res);
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. }
  5130. }
  5131. TEST(GetWithParametersTest, GetWithParameters2) {
  5132. Server svr;
  5133. svr.Get("/", [&](const Request &req, Response &res) {
  5134. auto text = req.get_param_value("hello");
  5135. res.set_content(text, "text/plain");
  5136. });
  5137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5138. auto se = detail::scope_exit([&] {
  5139. svr.stop();
  5140. listen_thread.join();
  5141. ASSERT_FALSE(svr.is_running());
  5142. });
  5143. svr.wait_until_ready();
  5144. Client cli("localhost", PORT);
  5145. Params params;
  5146. params.emplace("hello", "world");
  5147. std::string body;
  5148. auto res = cli.Get("/", params, Headers{},
  5149. [&](const char *data, size_t data_length) {
  5150. body.append(data, data_length);
  5151. return true;
  5152. });
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("world", body);
  5156. }
  5157. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5158. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5159. auto host = "httpbin.org";
  5160. auto path = std::string{"/range/32"};
  5161. #else
  5162. auto host = "nghttp2.org";
  5163. auto path = std::string{"/httpbin/range/32"};
  5164. #endif
  5165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5166. SSLClient cli(host);
  5167. #else
  5168. Client cli(host);
  5169. #endif
  5170. cli.set_default_headers({make_range_header({{1, 10}})});
  5171. cli.set_connection_timeout(5);
  5172. {
  5173. auto res = cli.Get(path);
  5174. ASSERT_TRUE(res);
  5175. EXPECT_EQ("bcdefghijk", res->body);
  5176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5177. }
  5178. {
  5179. auto res = cli.Get(path);
  5180. ASSERT_TRUE(res);
  5181. EXPECT_EQ("bcdefghijk", res->body);
  5182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5183. }
  5184. }
  5185. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5186. Server svr;
  5187. svr.set_default_headers({{"Hello", "World"}});
  5188. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5189. res.set_content("ok", "text/plain");
  5190. });
  5191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5192. auto se = detail::scope_exit([&] {
  5193. svr.stop();
  5194. listen_thread.join();
  5195. ASSERT_FALSE(svr.is_running());
  5196. });
  5197. svr.wait_until_ready();
  5198. Client cli("localhost", PORT);
  5199. auto res = cli.Get("/");
  5200. ASSERT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::OK_200, res->status);
  5202. EXPECT_EQ("ok", res->body);
  5203. EXPECT_EQ("World", res->get_header_value("Hello"));
  5204. }
  5205. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5206. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5208. ASSERT_TRUE(svr.is_valid());
  5209. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5210. std::this_thread::sleep_for(std::chrono::seconds(2));
  5211. res.set_content("a", "text/plain");
  5212. });
  5213. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5214. res.set_content("b", "text/plain");
  5215. });
  5216. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5217. auto se = detail::scope_exit([&] {
  5218. svr.stop();
  5219. listen_thread.join();
  5220. ASSERT_FALSE(svr.is_running());
  5221. });
  5222. svr.wait_until_ready();
  5223. SSLClient cli("localhost", PORT);
  5224. cli.enable_server_certificate_verification(false);
  5225. cli.set_keep_alive(true);
  5226. cli.set_read_timeout(std::chrono::seconds(1));
  5227. auto resa = cli.Get("/a");
  5228. ASSERT_TRUE(!resa);
  5229. EXPECT_EQ(Error::Read, resa.error());
  5230. auto resb = cli.Get("/b");
  5231. ASSERT_TRUE(resb);
  5232. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5233. EXPECT_EQ("b", resb->body);
  5234. }
  5235. #endif
  5236. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5237. protected:
  5238. ServerTestWithAI_PASSIVE()
  5239. : cli_(HOST, PORT)
  5240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5241. ,
  5242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5243. #endif
  5244. {
  5245. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5246. cli_.enable_server_certificate_verification(false);
  5247. #endif
  5248. }
  5249. virtual void SetUp() {
  5250. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5251. res.set_content("Hello World!", "text/plain");
  5252. });
  5253. t_ = thread(
  5254. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5255. svr_.wait_until_ready();
  5256. }
  5257. virtual void TearDown() {
  5258. svr_.stop();
  5259. t_.join();
  5260. }
  5261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5262. SSLClient cli_;
  5263. SSLServer svr_;
  5264. #else
  5265. Client cli_;
  5266. Server svr_;
  5267. #endif
  5268. thread t_;
  5269. };
  5270. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5271. auto res = cli_.Get("/hi");
  5272. ASSERT_TRUE(res);
  5273. EXPECT_EQ(StatusCode::OK_200, res->status);
  5274. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5275. EXPECT_EQ("Hello World!", res->body);
  5276. }
  5277. class ServerUpDownTest : public ::testing::Test {
  5278. protected:
  5279. ServerUpDownTest() : cli_(HOST, PORT) {}
  5280. virtual void SetUp() {
  5281. t_ = thread([&]() {
  5282. svr_.bind_to_any_port(HOST);
  5283. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5284. ASSERT_TRUE(svr_.listen_after_bind());
  5285. });
  5286. svr_.wait_until_ready();
  5287. }
  5288. virtual void TearDown() {
  5289. svr_.stop();
  5290. t_.join();
  5291. }
  5292. Client cli_;
  5293. Server svr_;
  5294. thread t_;
  5295. };
  5296. TEST_F(ServerUpDownTest, QuickStartStop) {
  5297. // Should not crash, especially when run with
  5298. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5299. }
  5300. class PayloadMaxLengthTest : public ::testing::Test {
  5301. protected:
  5302. PayloadMaxLengthTest()
  5303. : cli_(HOST, PORT)
  5304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5305. ,
  5306. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5307. #endif
  5308. {
  5309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5310. cli_.enable_server_certificate_verification(false);
  5311. #endif
  5312. }
  5313. virtual void SetUp() {
  5314. svr_.set_payload_max_length(8);
  5315. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5316. res.set_content("test", "text/plain");
  5317. });
  5318. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5319. svr_.wait_until_ready();
  5320. }
  5321. virtual void TearDown() {
  5322. svr_.stop();
  5323. t_.join();
  5324. }
  5325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5326. SSLClient cli_;
  5327. SSLServer svr_;
  5328. #else
  5329. Client cli_;
  5330. Server svr_;
  5331. #endif
  5332. thread t_;
  5333. };
  5334. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5335. auto res = cli_.Post("/test", "123456789", "text/plain");
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5338. res = cli_.Post("/test", "12345678", "text/plain");
  5339. ASSERT_TRUE(res);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. }
  5342. TEST(HostAndPortPropertiesTest, NoSSL) {
  5343. httplib::Client cli("www.google.com", 1234);
  5344. ASSERT_EQ("www.google.com", cli.host());
  5345. ASSERT_EQ(1234, cli.port());
  5346. }
  5347. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5348. httplib::Client cli("www.google.com:1234");
  5349. ASSERT_EQ("www.google.com", cli.host());
  5350. ASSERT_EQ(1234, cli.port());
  5351. }
  5352. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5353. TEST(HostAndPortPropertiesTest, SSL) {
  5354. httplib::SSLClient cli("www.google.com");
  5355. ASSERT_EQ("www.google.com", cli.host());
  5356. ASSERT_EQ(443, cli.port());
  5357. }
  5358. #endif
  5359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5360. TEST(SSLClientTest, UpdateCAStore) {
  5361. httplib::SSLClient httplib_client("www.google.com");
  5362. auto ca_store_1 = X509_STORE_new();
  5363. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5364. nullptr);
  5365. httplib_client.set_ca_cert_store(ca_store_1);
  5366. auto ca_store_2 = X509_STORE_new();
  5367. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5368. nullptr);
  5369. httplib_client.set_ca_cert_store(ca_store_2);
  5370. }
  5371. TEST(SSLClientTest, ServerNameIndication_Online) {
  5372. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5373. auto host = "httpbin.org";
  5374. auto path = std::string{"/get"};
  5375. #else
  5376. auto host = "nghttp2.org";
  5377. auto path = std::string{"/httpbin/get"};
  5378. #endif
  5379. SSLClient cli(host, 443);
  5380. auto res = cli.Get(path);
  5381. ASSERT_TRUE(res);
  5382. ASSERT_EQ(StatusCode::OK_200, res->status);
  5383. }
  5384. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5385. Client cli("https://google.com");
  5386. auto res = cli.Get("/");
  5387. ASSERT_TRUE(res);
  5388. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5389. }
  5390. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5391. SSLClient cli("google.com");
  5392. cli.enable_server_certificate_verification(true);
  5393. cli.set_ca_cert_path("hello");
  5394. auto res = cli.Get("/");
  5395. ASSERT_TRUE(!res);
  5396. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5397. }
  5398. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5399. SSLClient cli("google.com");
  5400. cli.set_ca_cert_path(CA_CERT_FILE);
  5401. auto res = cli.Get("/");
  5402. ASSERT_TRUE(res);
  5403. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5404. }
  5405. TEST(SSLClientTest, ServerCertificateVerification4) {
  5406. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5407. ASSERT_TRUE(svr.is_valid());
  5408. svr.Get("/test", [&](const Request &, Response &res) {
  5409. res.set_content("test", "text/plain");
  5410. svr.stop();
  5411. ASSERT_TRUE(true);
  5412. });
  5413. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5414. auto se = detail::scope_exit([&] {
  5415. t.join();
  5416. ASSERT_FALSE(svr.is_running());
  5417. });
  5418. svr.wait_until_ready();
  5419. SSLClient cli("127.0.0.1", PORT);
  5420. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5421. cli.enable_server_certificate_verification(true);
  5422. cli.set_connection_timeout(30);
  5423. auto res = cli.Get("/test");
  5424. ASSERT_TRUE(res);
  5425. ASSERT_EQ(StatusCode::OK_200, res->status);
  5426. }
  5427. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5428. std::string cert;
  5429. read_file(CA_CERT_FILE, cert);
  5430. SSLClient cli("google.com");
  5431. cli.load_ca_cert_store(cert.data(), cert.size());
  5432. const auto res = cli.Get("/");
  5433. ASSERT_TRUE(res);
  5434. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5435. }
  5436. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5437. // clang-format off
  5438. static constexpr char cert[] =
  5439. "GlobalSign Root CA\n"
  5440. "==================\n"
  5441. "-----BEGIN CERTIFICATE-----\n"
  5442. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5443. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5444. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5445. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5446. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5447. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5448. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5449. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5450. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5451. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5452. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5453. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5454. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5455. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5456. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5457. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5458. "-----END CERTIFICATE-----\n";
  5459. // clang-format on
  5460. SSLClient cli("google.com");
  5461. cli.load_ca_cert_store(cert, sizeof(cert));
  5462. const auto res = cli.Get("/");
  5463. ASSERT_TRUE(res);
  5464. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5465. }
  5466. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5467. SSLClient cli("www.youtube.com");
  5468. cli.set_ca_cert_path(CA_CERT_FILE);
  5469. cli.enable_server_certificate_verification(true);
  5470. cli.set_follow_location(true);
  5471. auto res = cli.Get("/");
  5472. ASSERT_TRUE(res);
  5473. ASSERT_EQ(StatusCode::OK_200, res->status);
  5474. }
  5475. TEST(SSLClientTest, Issue2004_Online) {
  5476. Client client("https://google.com");
  5477. client.set_follow_location(true);
  5478. auto res = client.Get("/");
  5479. ASSERT_TRUE(res);
  5480. ASSERT_EQ(StatusCode::OK_200, res->status);
  5481. auto body = res->body;
  5482. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5483. }
  5484. #if 0
  5485. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5486. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5487. ASSERT_TRUE(cli != nullptr);
  5488. cli->set_address_family(AF_INET6);
  5489. cli->set_interface("en0");
  5490. auto res = cli->Get("/get");
  5491. ASSERT_TRUE(res);
  5492. ASSERT_EQ(StatusCode::OK_200, res->status);
  5493. }
  5494. #endif
  5495. void ClientCertPresent(
  5496. const std::string &client_cert_file,
  5497. const std::string &client_private_key_file,
  5498. const std::string &client_encrypted_private_key_pass = std::string()) {
  5499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5500. CLIENT_CA_CERT_DIR);
  5501. ASSERT_TRUE(svr.is_valid());
  5502. svr.Get("/test", [&](const Request &req, Response &res) {
  5503. res.set_content("test", "text/plain");
  5504. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5505. ASSERT_TRUE(peer_cert != nullptr);
  5506. auto subject_name = X509_get_subject_name(peer_cert);
  5507. ASSERT_TRUE(subject_name != nullptr);
  5508. std::string common_name;
  5509. {
  5510. char name[BUFSIZ];
  5511. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5512. name, sizeof(name));
  5513. common_name.assign(name, static_cast<size_t>(name_len));
  5514. }
  5515. EXPECT_EQ("Common Name", common_name);
  5516. X509_free(peer_cert);
  5517. });
  5518. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5519. auto se = detail::scope_exit([&] {
  5520. svr.stop();
  5521. t.join();
  5522. ASSERT_FALSE(svr.is_running());
  5523. });
  5524. svr.wait_until_ready();
  5525. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5526. client_encrypted_private_key_pass);
  5527. cli.enable_server_certificate_verification(false);
  5528. cli.set_connection_timeout(30);
  5529. auto res = cli.Get("/test");
  5530. ASSERT_TRUE(res);
  5531. ASSERT_EQ(StatusCode::OK_200, res->status);
  5532. }
  5533. TEST(SSLClientServerTest, ClientCertPresent) {
  5534. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5535. }
  5536. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5537. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5538. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5539. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5540. }
  5541. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5542. void MemoryClientCertPresent(
  5543. const std::string &client_cert_file,
  5544. const std::string &client_private_key_file,
  5545. const std::string &client_encrypted_private_key_pass = std::string()) {
  5546. auto f = fopen(SERVER_CERT_FILE, "r+");
  5547. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5548. fclose(f);
  5549. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5550. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5551. fclose(f);
  5552. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5553. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5554. auto client_ca_cert_store = X509_STORE_new();
  5555. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5556. X509_free(client_cert);
  5557. fclose(f);
  5558. f = fopen(client_cert_file.c_str(), "r+");
  5559. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5560. fclose(f);
  5561. f = fopen(client_private_key_file.c_str(), "r+");
  5562. auto client_private_key = PEM_read_PrivateKey(
  5563. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5564. fclose(f);
  5565. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5566. ASSERT_TRUE(svr.is_valid());
  5567. svr.Get("/test", [&](const Request &req, Response &res) {
  5568. res.set_content("test", "text/plain");
  5569. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5570. ASSERT_TRUE(peer_cert != nullptr);
  5571. auto subject_name = X509_get_subject_name(peer_cert);
  5572. ASSERT_TRUE(subject_name != nullptr);
  5573. std::string common_name;
  5574. {
  5575. char name[BUFSIZ];
  5576. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5577. name, sizeof(name));
  5578. common_name.assign(name, static_cast<size_t>(name_len));
  5579. }
  5580. EXPECT_EQ("Common Name", common_name);
  5581. X509_free(peer_cert);
  5582. });
  5583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5584. auto se = detail::scope_exit([&] {
  5585. svr.stop();
  5586. t.join();
  5587. ASSERT_FALSE(svr.is_running());
  5588. });
  5589. svr.wait_until_ready();
  5590. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5591. client_encrypted_private_key_pass);
  5592. cli.enable_server_certificate_verification(false);
  5593. cli.set_connection_timeout(30);
  5594. auto res = cli.Get("/test");
  5595. ASSERT_TRUE(res);
  5596. ASSERT_EQ(StatusCode::OK_200, res->status);
  5597. X509_free(server_cert);
  5598. EVP_PKEY_free(server_private_key);
  5599. X509_free(client_cert);
  5600. EVP_PKEY_free(client_private_key);
  5601. }
  5602. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5603. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5604. }
  5605. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5606. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5607. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5608. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5609. }
  5610. #endif
  5611. TEST(SSLClientServerTest, ClientCertMissing) {
  5612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5613. CLIENT_CA_CERT_DIR);
  5614. ASSERT_TRUE(svr.is_valid());
  5615. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5617. auto se = detail::scope_exit([&] {
  5618. svr.stop();
  5619. t.join();
  5620. ASSERT_FALSE(svr.is_running());
  5621. });
  5622. svr.wait_until_ready();
  5623. SSLClient cli(HOST, PORT);
  5624. auto res = cli.Get("/test");
  5625. cli.set_connection_timeout(30);
  5626. ASSERT_TRUE(!res);
  5627. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5628. }
  5629. TEST(SSLClientServerTest, TrustDirOptional) {
  5630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5631. ASSERT_TRUE(svr.is_valid());
  5632. svr.Get("/test", [&](const Request &, Response &res) {
  5633. res.set_content("test", "text/plain");
  5634. });
  5635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5636. auto se = detail::scope_exit([&] {
  5637. svr.stop();
  5638. t.join();
  5639. ASSERT_FALSE(svr.is_running());
  5640. });
  5641. svr.wait_until_ready();
  5642. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5643. cli.enable_server_certificate_verification(false);
  5644. cli.set_connection_timeout(30);
  5645. auto res = cli.Get("/test");
  5646. ASSERT_TRUE(res);
  5647. ASSERT_EQ(StatusCode::OK_200, res->status);
  5648. }
  5649. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5650. class NoListenSSLServer : public SSLServer {
  5651. public:
  5652. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5653. const char *client_ca_cert_file_path,
  5654. const char *client_ca_cert_dir_path = nullptr)
  5655. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5656. client_ca_cert_dir_path),
  5657. stop_(false) {}
  5658. std::atomic_bool stop_;
  5659. private:
  5660. bool process_and_close_socket(socket_t /*sock*/) override {
  5661. // Don't create SSL context
  5662. while (!stop_.load()) {
  5663. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5664. }
  5665. return true;
  5666. }
  5667. };
  5668. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5669. CLIENT_CA_CERT_FILE);
  5670. ASSERT_TRUE(svr.is_valid());
  5671. svr.Get("/test", [&](const Request &, Response &res) {
  5672. res.set_content("test", "text/plain");
  5673. });
  5674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5675. auto se = detail::scope_exit([&] {
  5676. svr.stop_ = true;
  5677. svr.stop();
  5678. t.join();
  5679. ASSERT_FALSE(svr.is_running());
  5680. });
  5681. svr.wait_until_ready();
  5682. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5683. cli.enable_server_certificate_verification(false);
  5684. cli.set_connection_timeout(1);
  5685. auto res = cli.Get("/test");
  5686. ASSERT_TRUE(!res);
  5687. EXPECT_EQ(Error::SSLConnection, res.error());
  5688. }
  5689. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5690. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5691. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5692. SSL_CTX_set_options(&ssl_ctx,
  5693. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5694. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5695. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5696. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5697. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5698. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5699. "ECDHE-DSS-AES128-SHA256:"
  5700. "ECDHE-RSA-AES256-SHA256:"
  5701. "ECDHE-DSS-AES256-SHA256:";
  5702. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5703. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5704. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5705. SSL_FILETYPE_PEM) != 1) {
  5706. return false;
  5707. }
  5708. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5709. CLIENT_CA_CERT_DIR);
  5710. SSL_CTX_set_verify(
  5711. &ssl_ctx,
  5712. SSL_VERIFY_PEER |
  5713. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5714. nullptr);
  5715. return true;
  5716. };
  5717. SSLServer svr(setup_ssl_ctx_callback);
  5718. ASSERT_TRUE(svr.is_valid());
  5719. svr.Get("/test", [&](const Request &req, Response &res) {
  5720. res.set_content("test", "text/plain");
  5721. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5722. ASSERT_TRUE(peer_cert != nullptr);
  5723. auto subject_name = X509_get_subject_name(peer_cert);
  5724. ASSERT_TRUE(subject_name != nullptr);
  5725. std::string common_name;
  5726. {
  5727. char name[BUFSIZ];
  5728. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5729. name, sizeof(name));
  5730. common_name.assign(name, static_cast<size_t>(name_len));
  5731. }
  5732. EXPECT_EQ("Common Name", common_name);
  5733. X509_free(peer_cert);
  5734. });
  5735. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5736. auto se = detail::scope_exit([&] {
  5737. svr.stop();
  5738. t.join();
  5739. ASSERT_FALSE(svr.is_running());
  5740. });
  5741. svr.wait_until_ready();
  5742. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5743. cli.enable_server_certificate_verification(false);
  5744. cli.set_connection_timeout(30);
  5745. auto res = cli.Get("/test");
  5746. ASSERT_TRUE(res);
  5747. ASSERT_EQ(StatusCode::OK_200, res->status);
  5748. }
  5749. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5750. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5751. // prepare large data
  5752. std::random_device seed_gen;
  5753. std::mt19937 random(seed_gen());
  5754. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5755. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5756. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5757. // server
  5758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5759. ASSERT_TRUE(svr.is_valid());
  5760. svr.Post("/binary", [&](const Request &req, Response &res) {
  5761. EXPECT_EQ(large_size_byte, req.body.size());
  5762. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5763. res.set_content(req.body, "application/octet-stream");
  5764. });
  5765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5766. auto se = detail::scope_exit([&] {
  5767. svr.stop();
  5768. listen_thread.join();
  5769. ASSERT_FALSE(svr.is_running());
  5770. });
  5771. svr.wait_until_ready();
  5772. // client POST
  5773. SSLClient cli("localhost", PORT);
  5774. cli.enable_server_certificate_verification(false);
  5775. cli.set_read_timeout(std::chrono::seconds(100));
  5776. cli.set_write_timeout(std::chrono::seconds(100));
  5777. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5778. large_size_byte, "application/octet-stream");
  5779. // compare
  5780. EXPECT_EQ(StatusCode::OK_200, res->status);
  5781. EXPECT_EQ(large_size_byte, res->body.size());
  5782. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5783. }
  5784. #endif
  5785. #ifdef _WIN32
  5786. TEST(CleanupTest, WSACleanup) {
  5787. int ret = WSACleanup();
  5788. ASSERT_EQ(0, ret);
  5789. }
  5790. #endif
  5791. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5792. TEST(NoSSLSupport, SimpleInterface) {
  5793. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5794. }
  5795. #endif
  5796. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5797. TEST(InvalidScheme, SimpleInterface) {
  5798. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5799. }
  5800. #endif
  5801. TEST(NoScheme, SimpleInterface) {
  5802. Client cli("yahoo.com:80");
  5803. ASSERT_TRUE(cli.is_valid());
  5804. }
  5805. TEST(SendAPI, SimpleInterface_Online) {
  5806. Client cli("http://yahoo.com");
  5807. Request req;
  5808. req.method = "GET";
  5809. req.path = "/";
  5810. auto res = cli.send(req);
  5811. ASSERT_TRUE(res);
  5812. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5813. }
  5814. TEST(SendAPI, WithParamsInRequest) {
  5815. Server svr;
  5816. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  5817. EXPECT_TRUE(req.has_param("test"));
  5818. EXPECT_EQ("test_value", req.get_param_value("test"));
  5819. });
  5820. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  5821. auto se = detail::scope_exit([&] {
  5822. svr.stop();
  5823. t.join();
  5824. ASSERT_FALSE(svr.is_running());
  5825. });
  5826. svr.wait_until_ready();
  5827. Client cli(HOST, PORT);
  5828. {
  5829. Request req;
  5830. req.method = "GET";
  5831. req.path = "/";
  5832. req.params.emplace("test", "test_value");
  5833. auto res = cli.send(req);
  5834. ASSERT_TRUE(res);
  5835. }
  5836. {
  5837. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  5838. ASSERT_TRUE(res);
  5839. }
  5840. }
  5841. TEST(ClientImplMethods, GetSocketTest) {
  5842. httplib::Server svr;
  5843. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5844. res.status = StatusCode::OK_200;
  5845. });
  5846. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5847. auto se = detail::scope_exit([&] {
  5848. svr.stop();
  5849. thread.join();
  5850. ASSERT_FALSE(svr.is_running());
  5851. });
  5852. svr.wait_until_ready();
  5853. {
  5854. httplib::Client cli("http://127.0.0.1:3333");
  5855. cli.set_keep_alive(true);
  5856. // Use the behavior of cpp-httplib of opening the connection
  5857. // only when the first request happens. If that changes,
  5858. // this test would be obsolete.
  5859. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5860. // This also implicitly tests the server. But other tests would fail much
  5861. // earlier than this one to be considered.
  5862. auto res = cli.Get("/");
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5866. }
  5867. }
  5868. // Disabled due to out-of-memory problem on GitHub Actions
  5869. #ifdef _WIN64
  5870. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5871. // allocate content size larger than 2GB in memory
  5872. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5873. char *content = (char *)malloc(content_size);
  5874. ASSERT_TRUE(content);
  5875. Server svr;
  5876. svr.Get("/foo",
  5877. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5878. res.set_content(content, content_size, "application/octet-stream");
  5879. });
  5880. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5881. auto se = detail::scope_exit([&] {
  5882. svr.stop();
  5883. listen_thread.join();
  5884. if (content) free(content);
  5885. ASSERT_FALSE(svr.is_running());
  5886. });
  5887. svr.wait_until_ready();
  5888. Client cli(HOST, PORT);
  5889. auto res = cli.Get("/foo");
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. EXPECT_EQ(content_size, res->body.length());
  5893. }
  5894. #endif
  5895. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5896. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5897. Client cli("http://yahoo.com");
  5898. auto res = cli.Get("/");
  5899. ASSERT_TRUE(res);
  5900. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5901. cli.set_follow_location(true);
  5902. res = cli.Get("/");
  5903. ASSERT_TRUE(res);
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5906. }
  5907. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5908. Client cli("https://yahoo.com");
  5909. auto res = cli.Get("/");
  5910. ASSERT_TRUE(res);
  5911. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5912. cli.set_follow_location(true);
  5913. res = cli.Get("/");
  5914. ASSERT_TRUE(res);
  5915. EXPECT_EQ(StatusCode::OK_200, res->status);
  5916. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5917. }
  5918. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5919. Client cli("https://yahoo.com");
  5920. auto res = cli.Get("/");
  5921. ASSERT_TRUE(res);
  5922. ASSERT_FALSE(!res);
  5923. ASSERT_TRUE(res);
  5924. ASSERT_FALSE(res == nullptr);
  5925. ASSERT_TRUE(res != nullptr);
  5926. EXPECT_EQ(Error::Success, res.error());
  5927. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5928. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5929. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5930. cli.set_follow_location(true);
  5931. res = cli.Get("/");
  5932. ASSERT_TRUE(res);
  5933. EXPECT_EQ(Error::Success, res.error());
  5934. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5935. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5936. EXPECT_EQ(StatusCode::OK_200, res->status);
  5937. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5938. }
  5939. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5940. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5941. Client cli("https://cdnjs.cloudflare.com");
  5942. auto res =
  5943. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5944. ASSERT_TRUE(res);
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. EXPECT_EQ(287630U, res->body.size());
  5947. EXPECT_EQ("application/javascript; charset=utf-8",
  5948. res->get_header_value("Content-Type"));
  5949. }
  5950. #endif
  5951. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  5952. #undef REDIR_HOST // Silence compiler warning
  5953. #define REDIR_HOST "https://httpbingo.org"
  5954. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5955. Client cli(REDIR_HOST);
  5956. cli.set_follow_location(true);
  5957. auto res =
  5958. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  5959. ASSERT_TRUE(res);
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. }
  5962. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5963. Client cli(REDIR_HOST);
  5964. cli.set_follow_location(true);
  5965. Params params;
  5966. params.emplace("url", "http://example.com");
  5967. params.emplace("status_code", "302");
  5968. auto res = cli.Get(REDIR_PATH, params, Headers{});
  5969. ASSERT_TRUE(res);
  5970. EXPECT_EQ(StatusCode::OK_200, res->status);
  5971. }
  5972. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5973. Client cli(REDIR_HOST);
  5974. cli.set_follow_location(true);
  5975. Params params;
  5976. params.emplace("url", "http://example.com");
  5977. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  5978. ASSERT_TRUE(res);
  5979. EXPECT_EQ(StatusCode::OK_200, res->status);
  5980. }
  5981. TEST(HttpToHttpsRedirectTest, CertFile) {
  5982. Server svr;
  5983. ASSERT_TRUE(svr.is_valid());
  5984. svr.Get("/index", [&](const Request &, Response &res) {
  5985. res.set_redirect("https://127.0.0.1:1235/index");
  5986. svr.stop();
  5987. });
  5988. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5989. ASSERT_TRUE(ssl_svr.is_valid());
  5990. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5991. res.set_content("test", "text/plain");
  5992. ssl_svr.stop();
  5993. });
  5994. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5995. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5996. auto se = detail::scope_exit([&] {
  5997. t2.join();
  5998. t.join();
  5999. ASSERT_FALSE(svr.is_running());
  6000. });
  6001. svr.wait_until_ready();
  6002. ssl_svr.wait_until_ready();
  6003. Client cli("127.0.0.1", PORT);
  6004. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6005. cli.enable_server_certificate_verification(true);
  6006. cli.set_follow_location(true);
  6007. cli.set_connection_timeout(30);
  6008. auto res = cli.Get("/index");
  6009. ASSERT_TRUE(res);
  6010. ASSERT_EQ(StatusCode::OK_200, res->status);
  6011. }
  6012. TEST(MultipartFormDataTest, LargeData) {
  6013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6014. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6015. const ContentReader &content_reader) {
  6016. if (req.is_multipart_form_data()) {
  6017. MultipartFormDataItems files;
  6018. content_reader(
  6019. [&](const MultipartFormData &file) {
  6020. files.push_back(file);
  6021. return true;
  6022. },
  6023. [&](const char *data, size_t data_length) {
  6024. files.back().content.append(data, data_length);
  6025. return true;
  6026. });
  6027. EXPECT_TRUE(std::string(files[0].name) == "document");
  6028. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6029. EXPECT_TRUE(files[0].filename == "2MB_data");
  6030. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6031. EXPECT_TRUE(files[1].name == "hello");
  6032. EXPECT_TRUE(files[1].content == "world");
  6033. EXPECT_TRUE(files[1].filename == "");
  6034. EXPECT_TRUE(files[1].content_type == "");
  6035. } else {
  6036. std::string body;
  6037. content_reader([&](const char *data, size_t data_length) {
  6038. body.append(data, data_length);
  6039. return true;
  6040. });
  6041. }
  6042. });
  6043. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6044. auto se = detail::scope_exit([&] {
  6045. svr.stop();
  6046. t.join();
  6047. ASSERT_FALSE(svr.is_running());
  6048. });
  6049. svr.wait_until_ready();
  6050. {
  6051. std::string data(1024 * 1024 * 2, '.');
  6052. std::stringstream buffer;
  6053. buffer << data;
  6054. Client cli("https://localhost:8080");
  6055. cli.enable_server_certificate_verification(false);
  6056. MultipartFormDataItems items{
  6057. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6058. {"hello", "world", "", ""},
  6059. };
  6060. auto res = cli.Post("/post", items);
  6061. ASSERT_TRUE(res);
  6062. ASSERT_EQ(StatusCode::OK_200, res->status);
  6063. }
  6064. }
  6065. TEST(MultipartFormDataTest, DataProviderItems) {
  6066. std::random_device seed_gen;
  6067. std::mt19937 random(seed_gen());
  6068. std::string rand1;
  6069. rand1.resize(1000);
  6070. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6071. std::string rand2;
  6072. rand2.resize(3000);
  6073. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6075. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6076. const ContentReader &content_reader) {
  6077. ASSERT_FALSE(req.is_multipart_form_data());
  6078. std::string body;
  6079. content_reader([&](const char *data, size_t data_length) {
  6080. body.append(data, data_length);
  6081. return true;
  6082. });
  6083. EXPECT_EQ(body, "");
  6084. });
  6085. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6086. const ContentReader &content_reader) {
  6087. ASSERT_TRUE(req.is_multipart_form_data());
  6088. MultipartFormDataItems files;
  6089. content_reader(
  6090. [&](const MultipartFormData &file) {
  6091. files.push_back(file);
  6092. return true;
  6093. },
  6094. [&](const char *data, size_t data_length) {
  6095. files.back().content.append(data, data_length);
  6096. return true;
  6097. });
  6098. ASSERT_TRUE(files.size() == 2);
  6099. EXPECT_EQ(std::string(files[0].name), "name1");
  6100. EXPECT_EQ(files[0].content, "Testing123");
  6101. EXPECT_EQ(files[0].filename, "filename1");
  6102. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6103. EXPECT_EQ(files[1].name, "name2");
  6104. EXPECT_EQ(files[1].content, "Testing456");
  6105. EXPECT_EQ(files[1].filename, "");
  6106. EXPECT_EQ(files[1].content_type, "");
  6107. });
  6108. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6109. const ContentReader &content_reader) {
  6110. ASSERT_TRUE(req.is_multipart_form_data());
  6111. MultipartFormDataItems files;
  6112. content_reader(
  6113. [&](const MultipartFormData &file) {
  6114. files.push_back(file);
  6115. return true;
  6116. },
  6117. [&](const char *data, size_t data_length) {
  6118. files.back().content.append(data, data_length);
  6119. return true;
  6120. });
  6121. ASSERT_TRUE(files.size() == 2);
  6122. EXPECT_EQ(files[0].name, "name3");
  6123. EXPECT_EQ(files[0].content, rand1);
  6124. EXPECT_EQ(files[0].filename, "filename3");
  6125. EXPECT_EQ(files[0].content_type, "");
  6126. EXPECT_EQ(files[1].name, "name4");
  6127. EXPECT_EQ(files[1].content, rand2);
  6128. EXPECT_EQ(files[1].filename, "filename4");
  6129. EXPECT_EQ(files[1].content_type, "");
  6130. });
  6131. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6132. const ContentReader &content_reader) {
  6133. ASSERT_TRUE(req.is_multipart_form_data());
  6134. MultipartFormDataItems files;
  6135. content_reader(
  6136. [&](const MultipartFormData &file) {
  6137. files.push_back(file);
  6138. return true;
  6139. },
  6140. [&](const char *data, size_t data_length) {
  6141. files.back().content.append(data, data_length);
  6142. return true;
  6143. });
  6144. ASSERT_TRUE(files.size() == 4);
  6145. EXPECT_EQ(std::string(files[0].name), "name1");
  6146. EXPECT_EQ(files[0].content, "Testing123");
  6147. EXPECT_EQ(files[0].filename, "filename1");
  6148. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6149. EXPECT_EQ(files[1].name, "name2");
  6150. EXPECT_EQ(files[1].content, "Testing456");
  6151. EXPECT_EQ(files[1].filename, "");
  6152. EXPECT_EQ(files[1].content_type, "");
  6153. EXPECT_EQ(files[2].name, "name3");
  6154. EXPECT_EQ(files[2].content, rand1);
  6155. EXPECT_EQ(files[2].filename, "filename3");
  6156. EXPECT_EQ(files[2].content_type, "");
  6157. EXPECT_EQ(files[3].name, "name4");
  6158. EXPECT_EQ(files[3].content, rand2);
  6159. EXPECT_EQ(files[3].filename, "filename4");
  6160. EXPECT_EQ(files[3].content_type, "");
  6161. });
  6162. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6163. auto se = detail::scope_exit([&] {
  6164. svr.stop();
  6165. t.join();
  6166. ASSERT_FALSE(svr.is_running());
  6167. });
  6168. svr.wait_until_ready();
  6169. {
  6170. Client cli("https://localhost:8080");
  6171. cli.enable_server_certificate_verification(false);
  6172. MultipartFormDataItems items{
  6173. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6174. {"name2", "Testing456", "", ""}, // not a file
  6175. };
  6176. {
  6177. auto res = cli.Post("/post-none", {}, {}, {});
  6178. ASSERT_TRUE(res);
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. }
  6181. MultipartFormDataProviderItems providers;
  6182. {
  6183. auto res =
  6184. cli.Post("/post-items", {}, items, providers); // empty providers
  6185. ASSERT_TRUE(res);
  6186. ASSERT_EQ(StatusCode::OK_200, res->status);
  6187. }
  6188. providers.push_back({"name3",
  6189. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6190. // test the offset is given correctly at each step
  6191. if (!offset)
  6192. sink.os.write(rand1.data(), 30);
  6193. else if (offset == 30)
  6194. sink.os.write(rand1.data() + 30, 300);
  6195. else if (offset == 330)
  6196. sink.os.write(rand1.data() + 330, 670);
  6197. else if (offset == rand1.size())
  6198. sink.done();
  6199. return true;
  6200. },
  6201. "filename3",
  6202. {}});
  6203. providers.push_back({"name4",
  6204. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6205. // test the offset is given correctly at each step
  6206. if (!offset)
  6207. sink.os.write(rand2.data(), 2000);
  6208. else if (offset == 2000)
  6209. sink.os.write(rand2.data() + 2000, 1);
  6210. else if (offset == 2001)
  6211. sink.os.write(rand2.data() + 2001, 999);
  6212. else if (offset == rand2.size())
  6213. sink.done();
  6214. return true;
  6215. },
  6216. "filename4",
  6217. {}});
  6218. {
  6219. auto res = cli.Post("/post-providers", {}, {}, providers);
  6220. ASSERT_TRUE(res);
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. }
  6223. {
  6224. auto res = cli.Post("/post-both", {}, items, providers);
  6225. ASSERT_TRUE(res);
  6226. ASSERT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. }
  6229. }
  6230. TEST(MultipartFormDataTest, BadHeader) {
  6231. Server svr;
  6232. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6233. res.set_content("ok", "text/plain");
  6234. });
  6235. thread t = thread([&] { svr.listen(HOST, PORT); });
  6236. auto se = detail::scope_exit([&] {
  6237. svr.stop();
  6238. t.join();
  6239. ASSERT_FALSE(svr.is_running());
  6240. });
  6241. svr.wait_until_ready();
  6242. const std::string body =
  6243. "This is the preamble. It is to be ignored, though it\r\n"
  6244. "is a handy place for composition agents to include an\r\n"
  6245. "explanatory note to non-MIME conformant readers.\r\n"
  6246. "\r\n"
  6247. "\r\n"
  6248. "--simple boundary\r\n"
  6249. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6250. ": BAD...\r\n"
  6251. "\r\n"
  6252. "value1\r\n"
  6253. "--simple boundary\r\n"
  6254. "Content-Disposition: form-data; name=\"field2\"; "
  6255. "filename=\"example.txt\"\r\n"
  6256. "\r\n"
  6257. "value2\r\n"
  6258. "--simple boundary--\r\n"
  6259. "This is the epilogue. It is also to be ignored.\r\n";
  6260. std::string content_type =
  6261. R"(multipart/form-data; boundary="simple boundary")";
  6262. Client cli(HOST, PORT);
  6263. auto res = cli.Post("/post", body, content_type.c_str());
  6264. ASSERT_TRUE(res);
  6265. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6266. }
  6267. TEST(MultipartFormDataTest, WithPreamble) {
  6268. Server svr;
  6269. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6270. res.set_content("ok", "text/plain");
  6271. });
  6272. thread t = thread([&] { svr.listen(HOST, PORT); });
  6273. auto se = detail::scope_exit([&] {
  6274. svr.stop();
  6275. t.join();
  6276. ASSERT_FALSE(svr.is_running());
  6277. });
  6278. svr.wait_until_ready();
  6279. const std::string body =
  6280. "This is the preamble. It is to be ignored, though it\r\n"
  6281. "is a handy place for composition agents to include an\r\n"
  6282. "explanatory note to non-MIME conformant readers.\r\n"
  6283. "\r\n"
  6284. "\r\n"
  6285. "--simple boundary\r\n"
  6286. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6287. "\r\n"
  6288. "value1\r\n"
  6289. "--simple boundary\r\n"
  6290. "Content-Disposition: form-data; name=\"field2\"; "
  6291. "filename=\"example.txt\"\r\n"
  6292. "\r\n"
  6293. "value2\r\n"
  6294. "--simple boundary--\r\n"
  6295. "This is the epilogue. It is also to be ignored.\r\n";
  6296. std::string content_type =
  6297. R"(multipart/form-data; boundary="simple boundary")";
  6298. Client cli(HOST, PORT);
  6299. auto res = cli.Post("/post", body, content_type.c_str());
  6300. ASSERT_TRUE(res);
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. }
  6303. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6305. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6306. const ContentReader &content_reader) {
  6307. if (req.is_multipart_form_data()) {
  6308. MultipartFormDataItems files;
  6309. content_reader(
  6310. [&](const MultipartFormData &file) {
  6311. files.push_back(file);
  6312. return true;
  6313. },
  6314. [&](const char *data, size_t data_length) {
  6315. files.back().content.append(data, data_length);
  6316. return true;
  6317. });
  6318. EXPECT_TRUE(std::string(files[0].name) == "document");
  6319. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6320. EXPECT_TRUE(files[0].filename == "2MB_data");
  6321. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6322. EXPECT_TRUE(files[1].name == "hello");
  6323. EXPECT_TRUE(files[1].content == "world");
  6324. EXPECT_TRUE(files[1].filename == "");
  6325. EXPECT_TRUE(files[1].content_type == "");
  6326. } else {
  6327. std::string body;
  6328. content_reader([&](const char *data, size_t data_length) {
  6329. body.append(data, data_length);
  6330. return true;
  6331. });
  6332. }
  6333. });
  6334. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6335. auto se = detail::scope_exit([&] {
  6336. svr.stop();
  6337. t.join();
  6338. ASSERT_FALSE(svr.is_running());
  6339. });
  6340. svr.wait_until_ready();
  6341. {
  6342. std::string data(1024 * 1024 * 2, '.');
  6343. std::stringstream buffer;
  6344. buffer << data;
  6345. Client cli("https://localhost:8080");
  6346. cli.enable_server_certificate_verification(false);
  6347. MultipartFormDataItems items{
  6348. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6349. {"hello", "world", "", ""},
  6350. };
  6351. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6352. ASSERT_TRUE(res);
  6353. ASSERT_EQ(StatusCode::OK_200, res->status);
  6354. }
  6355. }
  6356. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6357. std::string data(1024 * 1024 * 2, '&');
  6358. std::stringstream buffer;
  6359. buffer << data;
  6360. Client cli("https://localhost:8080");
  6361. MultipartFormDataItems items{
  6362. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6363. {"hello", "world", "", ""},
  6364. };
  6365. for (const char &c : " \t\r\n") {
  6366. auto res =
  6367. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6368. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6369. ASSERT_FALSE(res);
  6370. }
  6371. }
  6372. TEST(MultipartFormDataTest, PutFormData) {
  6373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6374. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6375. const ContentReader &content_reader) {
  6376. if (req.is_multipart_form_data()) {
  6377. MultipartFormDataItems files;
  6378. content_reader(
  6379. [&](const MultipartFormData &file) {
  6380. files.push_back(file);
  6381. return true;
  6382. },
  6383. [&](const char *data, size_t data_length) {
  6384. files.back().content.append(data, data_length);
  6385. return true;
  6386. });
  6387. EXPECT_TRUE(std::string(files[0].name) == "document");
  6388. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6389. EXPECT_TRUE(files[0].filename == "2MB_data");
  6390. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6391. EXPECT_TRUE(files[1].name == "hello");
  6392. EXPECT_TRUE(files[1].content == "world");
  6393. EXPECT_TRUE(files[1].filename == "");
  6394. EXPECT_TRUE(files[1].content_type == "");
  6395. } else {
  6396. std::string body;
  6397. content_reader([&](const char *data, size_t data_length) {
  6398. body.append(data, data_length);
  6399. return true;
  6400. });
  6401. }
  6402. });
  6403. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6404. auto se = detail::scope_exit([&] {
  6405. svr.stop();
  6406. t.join();
  6407. ASSERT_FALSE(svr.is_running());
  6408. });
  6409. svr.wait_until_ready();
  6410. {
  6411. std::string data(1024 * 1024 * 2, '&');
  6412. std::stringstream buffer;
  6413. buffer << data;
  6414. Client cli("https://localhost:8080");
  6415. cli.enable_server_certificate_verification(false);
  6416. MultipartFormDataItems items{
  6417. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6418. {"hello", "world", "", ""},
  6419. };
  6420. auto res = cli.Put("/put", items);
  6421. ASSERT_TRUE(res);
  6422. ASSERT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. }
  6425. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6427. svr.Put("/put_customboundary",
  6428. [&](const Request &req, const Response & /*res*/,
  6429. const ContentReader &content_reader) {
  6430. if (req.is_multipart_form_data()) {
  6431. MultipartFormDataItems files;
  6432. content_reader(
  6433. [&](const MultipartFormData &file) {
  6434. files.push_back(file);
  6435. return true;
  6436. },
  6437. [&](const char *data, size_t data_length) {
  6438. files.back().content.append(data, data_length);
  6439. return true;
  6440. });
  6441. EXPECT_TRUE(std::string(files[0].name) == "document");
  6442. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6443. EXPECT_TRUE(files[0].filename == "2MB_data");
  6444. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6445. EXPECT_TRUE(files[1].name == "hello");
  6446. EXPECT_TRUE(files[1].content == "world");
  6447. EXPECT_TRUE(files[1].filename == "");
  6448. EXPECT_TRUE(files[1].content_type == "");
  6449. } else {
  6450. std::string body;
  6451. content_reader([&](const char *data, size_t data_length) {
  6452. body.append(data, data_length);
  6453. return true;
  6454. });
  6455. }
  6456. });
  6457. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6458. auto se = detail::scope_exit([&] {
  6459. svr.stop();
  6460. t.join();
  6461. ASSERT_FALSE(svr.is_running());
  6462. });
  6463. svr.wait_until_ready();
  6464. {
  6465. std::string data(1024 * 1024 * 2, '&');
  6466. std::stringstream buffer;
  6467. buffer << data;
  6468. Client cli("https://localhost:8080");
  6469. cli.enable_server_certificate_verification(false);
  6470. MultipartFormDataItems items{
  6471. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6472. {"hello", "world", "", ""},
  6473. };
  6474. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6475. ASSERT_TRUE(res);
  6476. ASSERT_EQ(StatusCode::OK_200, res->status);
  6477. }
  6478. }
  6479. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6480. std::string data(1024 * 1024 * 2, '&');
  6481. std::stringstream buffer;
  6482. buffer << data;
  6483. Client cli("https://localhost:8080");
  6484. cli.enable_server_certificate_verification(false);
  6485. MultipartFormDataItems items{
  6486. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6487. {"hello", "world", "", ""},
  6488. };
  6489. for (const char &c : " \t\r\n") {
  6490. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6491. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6492. ASSERT_FALSE(res);
  6493. }
  6494. }
  6495. TEST(MultipartFormDataTest, AlternateFilename) {
  6496. auto handled = false;
  6497. Server svr;
  6498. svr.Post("/test", [&](const Request &req, Response &res) {
  6499. ASSERT_EQ(3u, req.files.size());
  6500. auto it = req.files.begin();
  6501. ASSERT_EQ("file1", it->second.name);
  6502. ASSERT_EQ("A.txt", it->second.filename);
  6503. ASSERT_EQ("text/plain", it->second.content_type);
  6504. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6505. ++it;
  6506. ASSERT_EQ("file2", it->second.name);
  6507. ASSERT_EQ("a.html", it->second.filename);
  6508. ASSERT_EQ("text/html", it->second.content_type);
  6509. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6510. it->second.content);
  6511. ++it;
  6512. ASSERT_EQ("text", it->second.name);
  6513. ASSERT_EQ("", it->second.filename);
  6514. ASSERT_EQ("", it->second.content_type);
  6515. ASSERT_EQ("text default", it->second.content);
  6516. res.set_content("ok", "text/plain");
  6517. handled = true;
  6518. });
  6519. thread t = thread([&] { svr.listen(HOST, PORT); });
  6520. auto se = detail::scope_exit([&] {
  6521. svr.stop();
  6522. t.join();
  6523. ASSERT_FALSE(svr.is_running());
  6524. ASSERT_TRUE(handled);
  6525. });
  6526. svr.wait_until_ready();
  6527. auto req = "POST /test HTTP/1.1\r\n"
  6528. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6529. "Content-Length: 399\r\n"
  6530. "\r\n"
  6531. "----------\r\n"
  6532. "Content-Disposition: form-data; name=\"text\"\r\n"
  6533. "\r\n"
  6534. "text default\r\n"
  6535. "----------\r\n"
  6536. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6537. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6538. "Content-Type: text/plain\r\n"
  6539. "\r\n"
  6540. "Content of a.txt.\r\n"
  6541. "\r\n"
  6542. "----------\r\n"
  6543. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6544. "\"a.html\"\r\n"
  6545. "Content-Type: text/html\r\n"
  6546. "\r\n"
  6547. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6548. "\r\n"
  6549. "------------\r\n";
  6550. ASSERT_TRUE(send_request(1, req));
  6551. }
  6552. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6553. auto handled = false;
  6554. Server svr;
  6555. svr.Post("/test", [&](const Request &req, Response &) {
  6556. ASSERT_EQ(2u, req.files.size());
  6557. auto it = req.files.begin();
  6558. ASSERT_EQ("text1", it->second.name);
  6559. ASSERT_EQ("text1", it->second.content);
  6560. ++it;
  6561. ASSERT_EQ("text2", it->second.name);
  6562. ASSERT_EQ("text2", it->second.content);
  6563. handled = true;
  6564. });
  6565. thread t = thread([&] { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. ASSERT_FALSE(svr.is_running());
  6570. ASSERT_TRUE(handled);
  6571. });
  6572. svr.wait_until_ready();
  6573. auto req = "POST /test HTTP/1.1\r\n"
  6574. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6575. "Content-Length: 146\r\n"
  6576. "\r\n----------\r\n"
  6577. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6578. "\r\n"
  6579. "text1"
  6580. "\r\n----------\r\n"
  6581. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6582. "\r\n"
  6583. "text2"
  6584. "\r\n------------";
  6585. std::string response;
  6586. ASSERT_TRUE(send_request(1, req, &response));
  6587. ASSERT_EQ("200", response.substr(9, 3));
  6588. }
  6589. TEST(MultipartFormDataTest, ContentLength) {
  6590. auto handled = false;
  6591. Server svr;
  6592. svr.Post("/test", [&](const Request &req, Response &) {
  6593. ASSERT_EQ(2u, req.files.size());
  6594. auto it = req.files.begin();
  6595. ASSERT_EQ("text1", it->second.name);
  6596. ASSERT_EQ("text1", it->second.content);
  6597. ++it;
  6598. ASSERT_EQ("text2", it->second.name);
  6599. ASSERT_EQ("text2", it->second.content);
  6600. handled = true;
  6601. });
  6602. thread t = thread([&] { svr.listen(HOST, PORT); });
  6603. auto se = detail::scope_exit([&] {
  6604. svr.stop();
  6605. t.join();
  6606. ASSERT_FALSE(svr.is_running());
  6607. ASSERT_TRUE(handled);
  6608. });
  6609. svr.wait_until_ready();
  6610. auto req = "POST /test HTTP/1.1\r\n"
  6611. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6612. "Content-Length: 167\r\n"
  6613. "\r\n----------\r\n"
  6614. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6615. "Content-Length: 5\r\n"
  6616. "\r\n"
  6617. "text1"
  6618. "\r\n----------\r\n"
  6619. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6620. "\r\n"
  6621. "text2"
  6622. "\r\n------------\r\n";
  6623. std::string response;
  6624. ASSERT_TRUE(send_request(1, req, &response));
  6625. ASSERT_EQ("200", response.substr(9, 3));
  6626. }
  6627. #endif
  6628. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6629. static constexpr unsigned int number_of_tasks{1000000};
  6630. std::atomic_uint count{0};
  6631. std::unique_ptr<TaskQueue> task_queue{
  6632. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6633. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6634. auto queued = task_queue->enqueue(
  6635. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6636. EXPECT_TRUE(queued);
  6637. }
  6638. EXPECT_NO_THROW(task_queue->shutdown());
  6639. EXPECT_EQ(number_of_tasks, count.load());
  6640. }
  6641. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6642. static constexpr unsigned int number_of_tasks{1000000};
  6643. static constexpr unsigned int qlimit{2};
  6644. unsigned int queued_count{0};
  6645. std::atomic_uint count{0};
  6646. std::unique_ptr<TaskQueue> task_queue{
  6647. new ThreadPool{/*num_threads=*/1, qlimit}};
  6648. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6649. if (task_queue->enqueue(
  6650. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6651. queued_count++;
  6652. }
  6653. }
  6654. EXPECT_NO_THROW(task_queue->shutdown());
  6655. EXPECT_EQ(queued_count, count.load());
  6656. EXPECT_TRUE(queued_count <= number_of_tasks);
  6657. EXPECT_TRUE(queued_count >= qlimit);
  6658. }
  6659. TEST(TaskQueueTest, MaxQueuedRequests) {
  6660. static constexpr unsigned int qlimit{3};
  6661. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6662. std::condition_variable sem_cv;
  6663. std::mutex sem_mtx;
  6664. int credits = 0;
  6665. bool queued;
  6666. /* Fill up the queue with tasks that will block until we give them credits to
  6667. * complete. */
  6668. for (unsigned int n = 0; n <= qlimit;) {
  6669. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6670. std::unique_lock<std::mutex> lock(sem_mtx);
  6671. while (credits <= 0) {
  6672. sem_cv.wait(lock);
  6673. }
  6674. /* Consume the credit and signal the test code if they are all gone. */
  6675. if (--credits == 0) { sem_cv.notify_one(); }
  6676. });
  6677. if (n < qlimit) {
  6678. /* The first qlimit enqueues must succeed. */
  6679. EXPECT_TRUE(queued);
  6680. } else {
  6681. /* The last one will succeed only when the worker thread
  6682. * starts and dequeues the first blocking task. Although
  6683. * not necessary for the correctness of this test, we sleep for
  6684. * a short while to avoid busy waiting. */
  6685. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6686. }
  6687. if (queued) { n++; }
  6688. }
  6689. /* Further enqueues must fail since the queue is full. */
  6690. for (auto i = 0; i < 4; i++) {
  6691. queued = task_queue->enqueue([] {});
  6692. EXPECT_FALSE(queued);
  6693. }
  6694. /* Give the credits to allow the previous tasks to complete. */
  6695. {
  6696. std::unique_lock<std::mutex> lock(sem_mtx);
  6697. credits += qlimit + 1;
  6698. }
  6699. sem_cv.notify_all();
  6700. /* Wait for all the credits to be consumed. */
  6701. {
  6702. std::unique_lock<std::mutex> lock(sem_mtx);
  6703. while (credits > 0) {
  6704. sem_cv.wait(lock);
  6705. }
  6706. }
  6707. /* Check that we are able again to enqueue at least qlimit tasks. */
  6708. for (unsigned int i = 0; i < qlimit; i++) {
  6709. queued = task_queue->enqueue([] {});
  6710. EXPECT_TRUE(queued);
  6711. }
  6712. EXPECT_NO_THROW(task_queue->shutdown());
  6713. }
  6714. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6715. Server svr;
  6716. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6717. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6718. });
  6719. svr.Get("/hello", [](const Request &req, Response &res) {
  6720. res.set_content(req.get_param_value("key"), "text/plain");
  6721. });
  6722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. thread.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. {
  6730. Client cli(HOST, PORT);
  6731. cli.set_follow_location(true);
  6732. auto res = cli.Get("/");
  6733. ASSERT_TRUE(res);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. EXPECT_EQ("val&key2=val2", res->body);
  6736. }
  6737. }
  6738. TEST(VulnerabilityTest, CRLFInjection) {
  6739. Server svr;
  6740. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6741. res.set_content("Hello 1", "text/plain");
  6742. });
  6743. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6744. res.set_content("Hello 2", "text/plain");
  6745. });
  6746. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6747. res.set_content("Hello 3", "text/plain");
  6748. });
  6749. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6750. res.set_content("Hello 4", "text/plain");
  6751. });
  6752. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6753. for (const auto &x : req.headers) {
  6754. auto key = x.first;
  6755. EXPECT_STRNE("evil", key.c_str());
  6756. }
  6757. });
  6758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6759. auto se = detail::scope_exit([&] {
  6760. svr.stop();
  6761. thread.join();
  6762. ASSERT_FALSE(svr.is_running());
  6763. });
  6764. svr.wait_until_ready();
  6765. {
  6766. Client cli(HOST, PORT);
  6767. cli.Post("/test1", "A=B",
  6768. "application/x-www-form-urlencoded\r\nevil: hello1");
  6769. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6770. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6771. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6772. }
  6773. }
  6774. TEST(PathParamsTest, StaticMatch) {
  6775. const auto pattern = "/users/all";
  6776. detail::PathParamsMatcher matcher(pattern);
  6777. Request request;
  6778. request.path = "/users/all";
  6779. ASSERT_TRUE(matcher.match(request));
  6780. std::unordered_map<std::string, std::string> expected_params = {};
  6781. EXPECT_EQ(request.path_params, expected_params);
  6782. }
  6783. TEST(PathParamsTest, StaticMismatch) {
  6784. const auto pattern = "/users/all";
  6785. detail::PathParamsMatcher matcher(pattern);
  6786. Request request;
  6787. request.path = "/users/1";
  6788. ASSERT_FALSE(matcher.match(request));
  6789. }
  6790. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6791. const auto pattern = "/users/:id/subscriptions";
  6792. detail::PathParamsMatcher matcher(pattern);
  6793. Request request;
  6794. request.path = "/users/42/subscriptions";
  6795. ASSERT_TRUE(matcher.match(request));
  6796. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6797. EXPECT_EQ(request.path_params, expected_params);
  6798. }
  6799. TEST(PathParamsTest, SingleParamInTheEnd) {
  6800. const auto pattern = "/users/:id";
  6801. detail::PathParamsMatcher matcher(pattern);
  6802. Request request;
  6803. request.path = "/users/24";
  6804. ASSERT_TRUE(matcher.match(request));
  6805. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6806. EXPECT_EQ(request.path_params, expected_params);
  6807. }
  6808. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6809. const auto pattern = "/users/:id/";
  6810. detail::PathParamsMatcher matcher(pattern);
  6811. Request request;
  6812. request.path = "/users/42/";
  6813. ASSERT_TRUE(matcher.match(request));
  6814. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6815. EXPECT_EQ(request.path_params, expected_params);
  6816. }
  6817. TEST(PathParamsTest, EmptyParam) {
  6818. const auto pattern = "/users/:id/";
  6819. detail::PathParamsMatcher matcher(pattern);
  6820. Request request;
  6821. request.path = "/users//";
  6822. ASSERT_TRUE(matcher.match(request));
  6823. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6824. EXPECT_EQ(request.path_params, expected_params);
  6825. }
  6826. TEST(PathParamsTest, FragmentMismatch) {
  6827. const auto pattern = "/users/:id/";
  6828. detail::PathParamsMatcher matcher(pattern);
  6829. Request request;
  6830. request.path = "/admins/24/";
  6831. ASSERT_FALSE(matcher.match(request));
  6832. }
  6833. TEST(PathParamsTest, ExtraFragments) {
  6834. const auto pattern = "/users/:id";
  6835. detail::PathParamsMatcher matcher(pattern);
  6836. Request request;
  6837. request.path = "/users/42/subscriptions";
  6838. ASSERT_FALSE(matcher.match(request));
  6839. }
  6840. TEST(PathParamsTest, MissingTrailingParam) {
  6841. const auto pattern = "/users/:id";
  6842. detail::PathParamsMatcher matcher(pattern);
  6843. Request request;
  6844. request.path = "/users";
  6845. ASSERT_FALSE(matcher.match(request));
  6846. }
  6847. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6848. const auto pattern = "/users/:id/subscriptions";
  6849. detail::PathParamsMatcher matcher(pattern);
  6850. Request request;
  6851. request.path = "/users/subscriptions";
  6852. ASSERT_FALSE(matcher.match(request));
  6853. }
  6854. TEST(PathParamsTest, MultipleParams) {
  6855. const auto pattern = "/users/:userid/subscriptions/:subid";
  6856. detail::PathParamsMatcher matcher(pattern);
  6857. Request request;
  6858. request.path = "/users/42/subscriptions/2";
  6859. ASSERT_TRUE(matcher.match(request));
  6860. std::unordered_map<std::string, std::string> expected_params = {
  6861. {"userid", "42"}, {"subid", "2"}};
  6862. EXPECT_EQ(request.path_params, expected_params);
  6863. }
  6864. TEST(PathParamsTest, SequenceOfParams) {
  6865. const auto pattern = "/values/:x/:y/:z";
  6866. detail::PathParamsMatcher matcher(pattern);
  6867. Request request;
  6868. request.path = "/values/1/2/3";
  6869. ASSERT_TRUE(matcher.match(request));
  6870. std::unordered_map<std::string, std::string> expected_params = {
  6871. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6872. EXPECT_EQ(request.path_params, expected_params);
  6873. }
  6874. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6875. const auto pattern = "/prefix:suffix";
  6876. detail::PathParamsMatcher matcher(pattern);
  6877. Request request;
  6878. request.path = "/prefix:suffix";
  6879. ASSERT_TRUE(matcher.match(request));
  6880. const std::unordered_map<std::string, std::string> expected_params = {};
  6881. EXPECT_EQ(request.path_params, expected_params);
  6882. }
  6883. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6884. // If ipv6 regex working, regex match codepath is taken.
  6885. // else port will default to 80 in Client impl
  6886. int clientImplMagicPort = 80;
  6887. int port = 4321;
  6888. // above ports must be different to avoid false negative
  6889. EXPECT_NE(clientImplMagicPort, port);
  6890. std::string ipV6TestURL = "http://[ff06::c3]";
  6891. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6892. CLIENT_PRIVATE_KEY_FILE);
  6893. EXPECT_EQ(cli.port(), port);
  6894. }
  6895. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6896. auto file_path = "./www/dir/index.html";
  6897. auto dir_path = "./www/dir";
  6898. detail::FileStat stat_file(file_path);
  6899. EXPECT_TRUE(stat_file.is_file());
  6900. EXPECT_FALSE(stat_file.is_dir());
  6901. detail::FileStat stat_dir(dir_path);
  6902. EXPECT_FALSE(stat_dir.is_file());
  6903. EXPECT_TRUE(stat_dir.is_dir());
  6904. }
  6905. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6906. Server svr;
  6907. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6908. EXPECT_EQ(res.status, 400);
  6909. });
  6910. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6911. auto se = detail::scope_exit([&] {
  6912. svr.stop();
  6913. thread.join();
  6914. ASSERT_FALSE(svr.is_running());
  6915. });
  6916. svr.wait_until_ready();
  6917. Client cli(HOST, PORT);
  6918. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6919. }
  6920. TEST(InvalidHeaderCharsTest, is_field_name) {
  6921. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  6922. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  6923. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  6924. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  6925. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  6926. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  6927. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  6928. EXPECT_FALSE(detail::fields::is_field_name(""));
  6929. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  6930. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  6931. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  6932. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  6933. }
  6934. TEST(InvalidHeaderCharsTest, is_field_value) {
  6935. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  6936. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  6937. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  6938. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  6939. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  6940. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  6941. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  6942. EXPECT_TRUE(detail::fields::is_field_value(""));
  6943. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  6944. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  6945. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  6946. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  6947. EXPECT_TRUE(detail::fields::is_field_value("0"));
  6948. }
  6949. TEST(InvalidHeaderCharsTest, OnServer) {
  6950. Server svr;
  6951. svr.Get("/test_name", [&](const Request &req, Response &res) {
  6952. std::string header = "Not Set";
  6953. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6954. res.set_header(header, "value");
  6955. res.set_content("Page Content Page Content", "text/plain");
  6956. });
  6957. svr.Get("/test_value", [&](const Request &req, Response &res) {
  6958. std::string header = "Not Set";
  6959. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6960. res.set_header("X-Test", header);
  6961. res.set_content("Page Content Page Content", "text/plain");
  6962. });
  6963. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6964. auto se = detail::scope_exit([&] {
  6965. svr.stop();
  6966. thread.join();
  6967. ASSERT_FALSE(svr.is_running());
  6968. });
  6969. svr.wait_until_ready();
  6970. Client cli(HOST, PORT);
  6971. {
  6972. auto res = cli.Get(
  6973. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6974. ASSERT_TRUE(res);
  6975. EXPECT_EQ("Page Content Page Content", res->body);
  6976. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6977. }
  6978. {
  6979. auto res = cli.Get(
  6980. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6981. ASSERT_TRUE(res);
  6982. EXPECT_EQ("Page Content Page Content", res->body);
  6983. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6984. }
  6985. }
  6986. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  6987. auto handled = false;
  6988. Server svr;
  6989. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  6990. thread t = thread([&] { svr.listen(HOST, PORT); });
  6991. auto se = detail::scope_exit([&] {
  6992. svr.stop();
  6993. t.join();
  6994. ASSERT_FALSE(svr.is_running());
  6995. ASSERT_FALSE(handled);
  6996. });
  6997. svr.wait_until_ready();
  6998. auto req = "POST /test HTTP/1.1\r\n"
  6999. "Content-Length: x\r\n"
  7000. "\r\n";
  7001. std::string response;
  7002. ASSERT_TRUE(send_request(1, req, &response));
  7003. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7004. response.substr(0, response.find("\r\n")));
  7005. }
  7006. #ifndef _WIN32
  7007. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7008. static constexpr char reject[] = "Unauthorized";
  7009. static constexpr char accept[] = "Upload accepted";
  7010. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7011. Server svr;
  7012. svr.set_expect_100_continue_handler(
  7013. [](const Request & /*req*/, Response &res) {
  7014. res.status = StatusCode::Unauthorized_401;
  7015. res.set_content(reject, "text/plain");
  7016. return res.status;
  7017. });
  7018. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7019. res.set_content(accept, "text/plain");
  7020. });
  7021. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7022. auto se = detail::scope_exit([&] {
  7023. svr.stop();
  7024. thread.join();
  7025. ASSERT_FALSE(svr.is_running());
  7026. });
  7027. svr.wait_until_ready();
  7028. {
  7029. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7030. curl_easy_init(), &curl_easy_cleanup};
  7031. ASSERT_NE(curl, nullptr);
  7032. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7033. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7034. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7035. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7036. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7037. &curl_slist_free_all};
  7038. ASSERT_NE(list, nullptr);
  7039. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7040. struct read_data {
  7041. size_t read_size;
  7042. size_t total_size;
  7043. } data = {0, total_size};
  7044. using read_callback_t =
  7045. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7046. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7047. void *userdata) -> size_t {
  7048. read_data *data = (read_data *)userdata;
  7049. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7050. std::fill_n(ptr, size * nmemb, 'A');
  7051. data->read_size += size * nmemb;
  7052. return size * nmemb;
  7053. };
  7054. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7055. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7056. std::vector<char> buffer;
  7057. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7058. using write_callback_t =
  7059. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7060. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7061. void *userdata) -> size_t {
  7062. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7063. buffer->reserve(buffer->size() + size * nmemb + 1);
  7064. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7065. return size * nmemb;
  7066. };
  7067. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7068. {
  7069. const auto res = curl_easy_perform(curl.get());
  7070. ASSERT_EQ(res, CURLE_OK);
  7071. }
  7072. {
  7073. auto response_code = long{};
  7074. const auto res =
  7075. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7076. ASSERT_EQ(res, CURLE_OK);
  7077. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7078. }
  7079. {
  7080. auto dl = curl_off_t{};
  7081. const auto res =
  7082. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7083. ASSERT_EQ(res, CURLE_OK);
  7084. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7085. }
  7086. {
  7087. buffer.push_back('\0');
  7088. ASSERT_STRCASEEQ(buffer.data(), reject);
  7089. }
  7090. }
  7091. }
  7092. #endif
  7093. template <typename S, typename C>
  7094. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7095. svr.Get("/stream", [&](const Request &, Response &res) {
  7096. auto data = new std::string("01234567890123456789");
  7097. res.set_content_provider(
  7098. data->size(), "text/plain",
  7099. [&, data](size_t offset, size_t length, DataSink &sink) {
  7100. const size_t DATA_CHUNK_SIZE = 4;
  7101. const auto &d = *data;
  7102. std::this_thread::sleep_for(std::chrono::seconds(1));
  7103. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7104. return true;
  7105. },
  7106. [data](bool success) {
  7107. EXPECT_FALSE(success);
  7108. delete data;
  7109. });
  7110. });
  7111. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7112. auto i = new size_t(0);
  7113. res.set_content_provider(
  7114. "text/plain",
  7115. [i](size_t, DataSink &sink) {
  7116. if (*i < 5) {
  7117. std::this_thread::sleep_for(std::chrono::seconds(1));
  7118. sink.write("abcd", 4);
  7119. (*i)++;
  7120. } else {
  7121. sink.done();
  7122. }
  7123. return true;
  7124. },
  7125. [i](bool success) {
  7126. EXPECT_FALSE(success);
  7127. delete i;
  7128. });
  7129. });
  7130. svr.Get("/chunked", [&](const Request &, Response &res) {
  7131. auto i = new size_t(0);
  7132. res.set_chunked_content_provider(
  7133. "text/plain",
  7134. [i](size_t, DataSink &sink) {
  7135. if (*i < 5) {
  7136. std::this_thread::sleep_for(std::chrono::seconds(1));
  7137. sink.os << "abcd";
  7138. (*i)++;
  7139. } else {
  7140. sink.done();
  7141. }
  7142. return true;
  7143. },
  7144. [i](bool success) {
  7145. EXPECT_FALSE(success);
  7146. delete i;
  7147. });
  7148. });
  7149. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7150. auto se = detail::scope_exit([&] {
  7151. svr.stop();
  7152. listen_thread.join();
  7153. ASSERT_FALSE(svr.is_running());
  7154. });
  7155. svr.wait_until_ready();
  7156. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7157. {
  7158. auto start = std::chrono::steady_clock::now();
  7159. auto res = cli.Get("/stream");
  7160. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7161. std::chrono::steady_clock::now() - start)
  7162. .count();
  7163. ASSERT_FALSE(res);
  7164. EXPECT_EQ(Error::Read, res.error());
  7165. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7166. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7167. }
  7168. {
  7169. auto start = std::chrono::steady_clock::now();
  7170. auto res = cli.Get("/stream_without_length");
  7171. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7172. std::chrono::steady_clock::now() - start)
  7173. .count();
  7174. ASSERT_FALSE(res);
  7175. EXPECT_EQ(Error::Read, res.error());
  7176. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7177. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7178. }
  7179. {
  7180. auto start = std::chrono::steady_clock::now();
  7181. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  7182. EXPECT_EQ("abcd", string(data, data_length));
  7183. return true;
  7184. });
  7185. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7186. std::chrono::steady_clock::now() - start)
  7187. .count();
  7188. ASSERT_FALSE(res);
  7189. EXPECT_EQ(Error::Read, res.error());
  7190. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7191. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7192. }
  7193. }
  7194. TEST(MaxTimeoutTest, ContentStream) {
  7195. time_t timeout = 2000;
  7196. time_t threshold = 200;
  7197. Server svr;
  7198. Client cli("localhost", PORT);
  7199. max_timeout_test(svr, cli, timeout, threshold);
  7200. }
  7201. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7202. TEST(MaxTimeoutTest, ContentStreamSSL) {
  7203. time_t timeout = 2000;
  7204. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  7205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7206. SSLClient cli("localhost", PORT);
  7207. cli.enable_server_certificate_verification(false);
  7208. max_timeout_test(svr, cli, timeout, threshold);
  7209. }
  7210. #endif
  7211. class EventDispatcher {
  7212. public:
  7213. EventDispatcher() {}
  7214. void wait_event(DataSink *sink) {
  7215. unique_lock<mutex> lk(m_);
  7216. int id = id_;
  7217. cv_.wait(lk, [&] { return cid_ == id; });
  7218. sink->write(message_.data(), message_.size());
  7219. }
  7220. void send_event(const string &message) {
  7221. lock_guard<mutex> lk(m_);
  7222. cid_ = id_++;
  7223. message_ = message;
  7224. cv_.notify_all();
  7225. }
  7226. private:
  7227. mutex m_;
  7228. condition_variable cv_;
  7229. atomic_int id_{0};
  7230. atomic_int cid_{-1};
  7231. string message_;
  7232. };
  7233. TEST(ClientInThreadTest, Issue2068) {
  7234. EventDispatcher ed;
  7235. Server svr;
  7236. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  7237. res.set_chunked_content_provider("text/event-stream",
  7238. [&](size_t /*offset*/, DataSink &sink) {
  7239. ed.wait_event(&sink);
  7240. return true;
  7241. });
  7242. });
  7243. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7244. svr.wait_until_ready();
  7245. thread event_thread([&] {
  7246. int id = 0;
  7247. while (svr.is_running()) {
  7248. this_thread::sleep_for(chrono::milliseconds(500));
  7249. std::stringstream ss;
  7250. ss << "data: " << id << "\n\n";
  7251. ed.send_event(ss.str());
  7252. id++;
  7253. }
  7254. });
  7255. auto se = detail::scope_exit([&] {
  7256. svr.stop();
  7257. listen_thread.join();
  7258. event_thread.join();
  7259. ASSERT_FALSE(svr.is_running());
  7260. });
  7261. {
  7262. auto client = detail::make_unique<Client>(HOST, PORT);
  7263. client->set_read_timeout(std::chrono::minutes(10));
  7264. std::atomic<bool> stop{false};
  7265. std::thread t([&] {
  7266. client->Get("/event1",
  7267. [&](const char *, size_t) -> bool { return !stop; });
  7268. });
  7269. std::this_thread::sleep_for(std::chrono::seconds(2));
  7270. stop = true;
  7271. client->stop();
  7272. client.reset();
  7273. t.join();
  7274. }
  7275. }