test.cc 262 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715
  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. #ifndef _WIN32
  63. class UnixSocketTest : public ::testing::Test {
  64. protected:
  65. void TearDown() override { std::remove(pathname_.c_str()); }
  66. void client_GET(const std::string &addr) {
  67. httplib::Client cli{addr};
  68. cli.set_address_family(AF_UNIX);
  69. ASSERT_TRUE(cli.is_valid());
  70. const auto &result = cli.Get(pattern_);
  71. ASSERT_TRUE(result) << "error: " << result.error();
  72. const auto &resp = result.value();
  73. EXPECT_EQ(resp.status, StatusCode::OK_200);
  74. EXPECT_EQ(resp.body, content_);
  75. }
  76. const std::string pathname_{"./httplib-server.sock"};
  77. const std::string pattern_{"/hi"};
  78. const std::string content_{"Hello World!"};
  79. };
  80. TEST_F(UnixSocketTest, pathname) {
  81. httplib::Server svr;
  82. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  83. res.set_content(content_, "text/plain");
  84. });
  85. std::thread t{[&] {
  86. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  87. }};
  88. auto se = detail::scope_exit([&] {
  89. svr.stop();
  90. t.join();
  91. ASSERT_FALSE(svr.is_running());
  92. });
  93. svr.wait_until_ready();
  94. ASSERT_TRUE(svr.is_running());
  95. client_GET(pathname_);
  96. }
  97. #if defined(__linux__) || \
  98. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  99. TEST_F(UnixSocketTest, PeerPid) {
  100. httplib::Server svr;
  101. std::string remote_port_val;
  102. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  103. res.set_content(content_, "text/plain");
  104. remote_port_val = req.get_header_value("REMOTE_PORT");
  105. });
  106. std::thread t{[&] {
  107. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  108. }};
  109. auto se = detail::scope_exit([&] {
  110. svr.stop();
  111. t.join();
  112. ASSERT_FALSE(svr.is_running());
  113. });
  114. svr.wait_until_ready();
  115. ASSERT_TRUE(svr.is_running());
  116. client_GET(pathname_);
  117. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  118. }
  119. #endif
  120. #ifdef __linux__
  121. TEST_F(UnixSocketTest, abstract) {
  122. constexpr char svr_path[]{"\x00httplib-server.sock"};
  123. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  124. httplib::Server svr;
  125. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  126. res.set_content(content_, "text/plain");
  127. });
  128. std::thread t{[&] {
  129. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  130. }};
  131. auto se = detail::scope_exit([&] {
  132. svr.stop();
  133. t.join();
  134. ASSERT_FALSE(svr.is_running());
  135. });
  136. svr.wait_until_ready();
  137. ASSERT_TRUE(svr.is_running());
  138. client_GET(abstract_addr);
  139. }
  140. #endif
  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. EXPECT_EQ("aaabbb", s);
  4739. });
  4740. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4741. // Give GET time to get a few messages.
  4742. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4743. }
  4744. TEST(MountTest, Unmount) {
  4745. Server svr;
  4746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4747. auto se = detail::scope_exit([&] {
  4748. svr.stop();
  4749. listen_thread.join();
  4750. ASSERT_FALSE(svr.is_running());
  4751. });
  4752. svr.wait_until_ready();
  4753. Client cli("localhost", PORT);
  4754. svr.set_mount_point("/mount2", "./www2");
  4755. auto res = cli.Get("/");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4758. res = cli.Get("/mount2/dir/test.html");
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. svr.set_mount_point("/", "./www");
  4762. res = cli.Get("/dir/");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. svr.remove_mount_point("/");
  4766. res = cli.Get("/dir/");
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4769. svr.remove_mount_point("/mount2");
  4770. res = cli.Get("/mount2/dir/test.html");
  4771. ASSERT_TRUE(res);
  4772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4773. }
  4774. TEST(MountTest, Redicect) {
  4775. Server svr;
  4776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4777. auto se = detail::scope_exit([&] {
  4778. svr.stop();
  4779. listen_thread.join();
  4780. ASSERT_FALSE(svr.is_running());
  4781. });
  4782. svr.set_mount_point("/", "./www");
  4783. svr.wait_until_ready();
  4784. Client cli("localhost", PORT);
  4785. auto res = cli.Get("/dir/");
  4786. ASSERT_TRUE(res);
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. res = cli.Get("/dir");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4791. res = cli.Get("/file");
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. res = cli.Get("/file/");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4797. cli.set_follow_location(true);
  4798. res = cli.Get("/dir");
  4799. ASSERT_TRUE(res);
  4800. EXPECT_EQ(StatusCode::OK_200, res->status);
  4801. }
  4802. TEST(MountTest, MultibytesPathName) {
  4803. Server svr;
  4804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4805. auto se = detail::scope_exit([&] {
  4806. svr.stop();
  4807. listen_thread.join();
  4808. ASSERT_FALSE(svr.is_running());
  4809. });
  4810. svr.set_mount_point("/", "./www");
  4811. svr.wait_until_ready();
  4812. Client cli("localhost", PORT);
  4813. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  4817. }
  4818. TEST(KeepAliveTest, ReadTimeout) {
  4819. Server svr;
  4820. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4821. std::this_thread::sleep_for(std::chrono::seconds(2));
  4822. res.set_content("a", "text/plain");
  4823. });
  4824. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4825. res.set_content("b", "text/plain");
  4826. });
  4827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4828. auto se = detail::scope_exit([&] {
  4829. svr.stop();
  4830. listen_thread.join();
  4831. ASSERT_FALSE(svr.is_running());
  4832. });
  4833. svr.wait_until_ready();
  4834. Client cli("localhost", PORT);
  4835. cli.set_keep_alive(true);
  4836. cli.set_read_timeout(std::chrono::seconds(1));
  4837. auto resa = cli.Get("/a");
  4838. ASSERT_FALSE(resa);
  4839. EXPECT_EQ(Error::Read, resa.error());
  4840. auto resb = cli.Get("/b");
  4841. ASSERT_TRUE(resb);
  4842. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4843. EXPECT_EQ("b", resb->body);
  4844. }
  4845. TEST(KeepAliveTest, Issue1041) {
  4846. Server svr;
  4847. svr.set_keep_alive_timeout(3);
  4848. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4849. res.set_content("Hello World!", "text/plain");
  4850. });
  4851. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4852. auto se = detail::scope_exit([&] {
  4853. svr.stop();
  4854. listen_thread.join();
  4855. ASSERT_FALSE(svr.is_running());
  4856. });
  4857. svr.wait_until_ready();
  4858. Client cli(HOST, PORT);
  4859. cli.set_keep_alive(true);
  4860. auto result = cli.Get("/hi");
  4861. ASSERT_TRUE(result);
  4862. EXPECT_EQ(StatusCode::OK_200, result->status);
  4863. std::this_thread::sleep_for(std::chrono::seconds(5));
  4864. result = cli.Get("/hi");
  4865. ASSERT_TRUE(result);
  4866. EXPECT_EQ(StatusCode::OK_200, result->status);
  4867. }
  4868. TEST(KeepAliveTest, Issue1959) {
  4869. Server svr;
  4870. svr.set_keep_alive_timeout(5);
  4871. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4872. res.set_content("a", "text/plain");
  4873. });
  4874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4875. auto se = detail::scope_exit([&] {
  4876. if (!svr.is_running()) return;
  4877. svr.stop();
  4878. listen_thread.join();
  4879. ASSERT_FALSE(svr.is_running());
  4880. });
  4881. svr.wait_until_ready();
  4882. Client cli("localhost", PORT);
  4883. cli.set_keep_alive(true);
  4884. using namespace std::chrono;
  4885. auto start = steady_clock::now();
  4886. cli.Get("/a");
  4887. svr.stop();
  4888. listen_thread.join();
  4889. auto end = steady_clock::now();
  4890. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4891. EXPECT_LT(elapsed, 5000);
  4892. }
  4893. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4894. TEST(KeepAliveTest, SSLClientReconnection) {
  4895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4896. ASSERT_TRUE(svr.is_valid());
  4897. svr.set_keep_alive_timeout(1);
  4898. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4899. res.set_content("Hello World!", "text/plain");
  4900. });
  4901. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4902. auto se = detail::scope_exit([&] {
  4903. svr.stop();
  4904. listen_thread.join();
  4905. ASSERT_FALSE(svr.is_running());
  4906. });
  4907. svr.wait_until_ready();
  4908. SSLClient cli(HOST, PORT);
  4909. cli.enable_server_certificate_verification(false);
  4910. cli.set_keep_alive(true);
  4911. auto result = cli.Get("/hi");
  4912. ASSERT_TRUE(result);
  4913. EXPECT_EQ(StatusCode::OK_200, result->status);
  4914. result = cli.Get("/hi");
  4915. ASSERT_TRUE(result);
  4916. EXPECT_EQ(StatusCode::OK_200, result->status);
  4917. std::this_thread::sleep_for(std::chrono::seconds(2));
  4918. // Recoonect
  4919. result = cli.Get("/hi");
  4920. ASSERT_TRUE(result);
  4921. EXPECT_EQ(StatusCode::OK_200, result->status);
  4922. result = cli.Get("/hi");
  4923. ASSERT_TRUE(result);
  4924. EXPECT_EQ(StatusCode::OK_200, result->status);
  4925. }
  4926. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4928. ASSERT_TRUE(svr.is_valid());
  4929. svr.set_keep_alive_timeout(1);
  4930. std::string content = "reconnect";
  4931. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4932. res.set_content("Hello World!", "text/plain");
  4933. });
  4934. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4935. auto se = detail::scope_exit([&] {
  4936. svr.stop();
  4937. listen_thread.join();
  4938. ASSERT_FALSE(svr.is_running());
  4939. });
  4940. svr.wait_until_ready();
  4941. SSLClient cli(HOST, PORT);
  4942. cli.enable_server_certificate_verification(false);
  4943. cli.set_keep_alive(true);
  4944. auto result = cli.Post(
  4945. "/hi", content.size(),
  4946. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4947. sink.write(content.c_str(), content.size());
  4948. return true;
  4949. },
  4950. "text/plain");
  4951. ASSERT_TRUE(result);
  4952. EXPECT_EQ(200, result->status);
  4953. std::this_thread::sleep_for(std::chrono::seconds(2));
  4954. // Recoonect
  4955. result = cli.Post(
  4956. "/hi", content.size(),
  4957. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4958. sink.write(content.c_str(), content.size());
  4959. return true;
  4960. },
  4961. "text/plain");
  4962. ASSERT_TRUE(result);
  4963. EXPECT_EQ(200, result->status);
  4964. result = cli.Post(
  4965. "/hi", content.size(),
  4966. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4967. sink.write(content.c_str(), content.size());
  4968. return true;
  4969. },
  4970. "text/plain");
  4971. ASSERT_TRUE(result);
  4972. EXPECT_EQ(200, result->status);
  4973. }
  4974. #endif
  4975. TEST(ClientProblemDetectionTest, ContentProvider) {
  4976. Server svr;
  4977. size_t content_length = 1024 * 1024;
  4978. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4979. res.set_content_provider(
  4980. content_length, "text/plain",
  4981. [&](size_t offset, size_t length, DataSink &sink) {
  4982. auto out_len = std::min(length, static_cast<size_t>(1024));
  4983. std::string out(out_len, '@');
  4984. sink.write(out.data(), out_len);
  4985. return offset < 4096;
  4986. },
  4987. [](bool success) { ASSERT_FALSE(success); });
  4988. });
  4989. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4990. res.set_content_provider(
  4991. 0, "text/plain",
  4992. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4993. EXPECT_TRUE(false);
  4994. return true;
  4995. },
  4996. [](bool success) { ASSERT_FALSE(success); });
  4997. });
  4998. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4999. auto se = detail::scope_exit([&] {
  5000. svr.stop();
  5001. listen_thread.join();
  5002. ASSERT_FALSE(svr.is_running());
  5003. });
  5004. svr.wait_until_ready();
  5005. Client cli("localhost", PORT);
  5006. {
  5007. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5008. size_t /*data_length*/) { return false; });
  5009. ASSERT_FALSE(res);
  5010. }
  5011. {
  5012. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5013. size_t /*data_length*/) { return false; });
  5014. ASSERT_TRUE(res);
  5015. }
  5016. }
  5017. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5018. Server svr;
  5019. svr.set_error_handler([](Request const &, Response &res) -> void {
  5020. res.set_chunked_content_provider(
  5021. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5022. sink.os << "hello";
  5023. sink.os << "world";
  5024. sink.done();
  5025. return true;
  5026. });
  5027. });
  5028. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5029. auto se = detail::scope_exit([&] {
  5030. svr.stop();
  5031. listen_thread.join();
  5032. ASSERT_FALSE(svr.is_running());
  5033. });
  5034. svr.wait_until_ready();
  5035. Client cli("localhost", PORT);
  5036. auto res = cli.Get("/");
  5037. ASSERT_TRUE(res);
  5038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5039. EXPECT_EQ("helloworld", res->body);
  5040. }
  5041. TEST(LongPollingTest, ClientCloseDetection) {
  5042. Server svr;
  5043. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5044. res.set_chunked_content_provider(
  5045. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5046. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5047. sink.os << "hello";
  5048. auto count = 10;
  5049. while (count > 0 && sink.is_writable()) {
  5050. this_thread::sleep_for(chrono::milliseconds(10));
  5051. count--;
  5052. }
  5053. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5054. return true;
  5055. });
  5056. });
  5057. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5058. auto se = detail::scope_exit([&] {
  5059. svr.stop();
  5060. listen_thread.join();
  5061. ASSERT_FALSE(svr.is_running());
  5062. });
  5063. svr.wait_until_ready();
  5064. Client cli("localhost", PORT);
  5065. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5066. EXPECT_EQ("hello", string(data, data_length));
  5067. return false; // close the socket immediately.
  5068. });
  5069. ASSERT_FALSE(res);
  5070. }
  5071. TEST(GetWithParametersTest, GetWithParameters) {
  5072. Server svr;
  5073. svr.Get("/", [&](const Request &req, Response &) {
  5074. EXPECT_EQ("world", req.get_param_value("hello"));
  5075. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5076. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5077. });
  5078. svr.Get("/params", [&](const Request &req, Response &) {
  5079. EXPECT_EQ("world", req.get_param_value("hello"));
  5080. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5081. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5082. });
  5083. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5084. EXPECT_EQ("resource-id", req.matches[1]);
  5085. EXPECT_EQ("foo", req.get_param_value("param1"));
  5086. EXPECT_EQ("bar", req.get_param_value("param2"));
  5087. });
  5088. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5089. EXPECT_EQ("user-id", req.path_params.at("id"));
  5090. EXPECT_EQ("foo", req.get_param_value("param1"));
  5091. EXPECT_EQ("bar", req.get_param_value("param2"));
  5092. });
  5093. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5094. auto se = detail::scope_exit([&] {
  5095. svr.stop();
  5096. listen_thread.join();
  5097. ASSERT_FALSE(svr.is_running());
  5098. });
  5099. svr.wait_until_ready();
  5100. {
  5101. Client cli(HOST, PORT);
  5102. Params params;
  5103. params.emplace("hello", "world");
  5104. params.emplace("hello2", "world2");
  5105. params.emplace("hello3", "world3");
  5106. auto res = cli.Get("/", params, Headers{});
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. }
  5110. {
  5111. Client cli(HOST, PORT);
  5112. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ(StatusCode::OK_200, res->status);
  5115. }
  5116. {
  5117. Client cli(HOST, PORT);
  5118. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5119. ASSERT_TRUE(res);
  5120. EXPECT_EQ(StatusCode::OK_200, res->status);
  5121. }
  5122. {
  5123. Client cli(HOST, PORT);
  5124. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. }
  5128. }
  5129. TEST(GetWithParametersTest, GetWithParameters2) {
  5130. Server svr;
  5131. svr.Get("/", [&](const Request &req, Response &res) {
  5132. auto text = req.get_param_value("hello");
  5133. res.set_content(text, "text/plain");
  5134. });
  5135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5136. auto se = detail::scope_exit([&] {
  5137. svr.stop();
  5138. listen_thread.join();
  5139. ASSERT_FALSE(svr.is_running());
  5140. });
  5141. svr.wait_until_ready();
  5142. Client cli("localhost", PORT);
  5143. Params params;
  5144. params.emplace("hello", "world");
  5145. std::string body;
  5146. auto res = cli.Get("/", params, Headers{},
  5147. [&](const char *data, size_t data_length) {
  5148. body.append(data, data_length);
  5149. return true;
  5150. });
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("world", body);
  5154. }
  5155. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5156. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5157. auto host = "httpbin.org";
  5158. auto path = std::string{"/range/32"};
  5159. #else
  5160. auto host = "nghttp2.org";
  5161. auto path = std::string{"/httpbin/range/32"};
  5162. #endif
  5163. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5164. SSLClient cli(host);
  5165. #else
  5166. Client cli(host);
  5167. #endif
  5168. cli.set_default_headers({make_range_header({{1, 10}})});
  5169. cli.set_connection_timeout(5);
  5170. {
  5171. auto res = cli.Get(path);
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ("bcdefghijk", res->body);
  5174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5175. }
  5176. {
  5177. auto res = cli.Get(path);
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ("bcdefghijk", res->body);
  5180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5181. }
  5182. }
  5183. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5184. Server svr;
  5185. svr.set_default_headers({{"Hello", "World"}});
  5186. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5187. res.set_content("ok", "text/plain");
  5188. });
  5189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5190. auto se = detail::scope_exit([&] {
  5191. svr.stop();
  5192. listen_thread.join();
  5193. ASSERT_FALSE(svr.is_running());
  5194. });
  5195. svr.wait_until_ready();
  5196. Client cli("localhost", PORT);
  5197. auto res = cli.Get("/");
  5198. ASSERT_TRUE(res);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("ok", res->body);
  5201. EXPECT_EQ("World", res->get_header_value("Hello"));
  5202. }
  5203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5204. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5206. ASSERT_TRUE(svr.is_valid());
  5207. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5208. std::this_thread::sleep_for(std::chrono::seconds(2));
  5209. res.set_content("a", "text/plain");
  5210. });
  5211. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5212. res.set_content("b", "text/plain");
  5213. });
  5214. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5215. auto se = detail::scope_exit([&] {
  5216. svr.stop();
  5217. listen_thread.join();
  5218. ASSERT_FALSE(svr.is_running());
  5219. });
  5220. svr.wait_until_ready();
  5221. SSLClient cli("localhost", PORT);
  5222. cli.enable_server_certificate_verification(false);
  5223. cli.set_keep_alive(true);
  5224. cli.set_read_timeout(std::chrono::seconds(1));
  5225. auto resa = cli.Get("/a");
  5226. ASSERT_TRUE(!resa);
  5227. EXPECT_EQ(Error::Read, resa.error());
  5228. auto resb = cli.Get("/b");
  5229. ASSERT_TRUE(resb);
  5230. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5231. EXPECT_EQ("b", resb->body);
  5232. }
  5233. #endif
  5234. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5235. protected:
  5236. ServerTestWithAI_PASSIVE()
  5237. : cli_(HOST, PORT)
  5238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5239. ,
  5240. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5241. #endif
  5242. {
  5243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5244. cli_.enable_server_certificate_verification(false);
  5245. #endif
  5246. }
  5247. virtual void SetUp() {
  5248. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5249. res.set_content("Hello World!", "text/plain");
  5250. });
  5251. t_ = thread(
  5252. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5253. svr_.wait_until_ready();
  5254. }
  5255. virtual void TearDown() {
  5256. svr_.stop();
  5257. t_.join();
  5258. }
  5259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5260. SSLClient cli_;
  5261. SSLServer svr_;
  5262. #else
  5263. Client cli_;
  5264. Server svr_;
  5265. #endif
  5266. thread t_;
  5267. };
  5268. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5269. auto res = cli_.Get("/hi");
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5273. EXPECT_EQ("Hello World!", res->body);
  5274. }
  5275. class ServerUpDownTest : public ::testing::Test {
  5276. protected:
  5277. ServerUpDownTest() : cli_(HOST, PORT) {}
  5278. virtual void SetUp() {
  5279. t_ = thread([&]() {
  5280. svr_.bind_to_any_port(HOST);
  5281. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5282. ASSERT_TRUE(svr_.listen_after_bind());
  5283. });
  5284. svr_.wait_until_ready();
  5285. }
  5286. virtual void TearDown() {
  5287. svr_.stop();
  5288. t_.join();
  5289. }
  5290. Client cli_;
  5291. Server svr_;
  5292. thread t_;
  5293. };
  5294. TEST_F(ServerUpDownTest, QuickStartStop) {
  5295. // Should not crash, especially when run with
  5296. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5297. }
  5298. class PayloadMaxLengthTest : public ::testing::Test {
  5299. protected:
  5300. PayloadMaxLengthTest()
  5301. : cli_(HOST, PORT)
  5302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5303. ,
  5304. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5305. #endif
  5306. {
  5307. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5308. cli_.enable_server_certificate_verification(false);
  5309. #endif
  5310. }
  5311. virtual void SetUp() {
  5312. svr_.set_payload_max_length(8);
  5313. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5314. res.set_content("test", "text/plain");
  5315. });
  5316. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5317. svr_.wait_until_ready();
  5318. }
  5319. virtual void TearDown() {
  5320. svr_.stop();
  5321. t_.join();
  5322. }
  5323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5324. SSLClient cli_;
  5325. SSLServer svr_;
  5326. #else
  5327. Client cli_;
  5328. Server svr_;
  5329. #endif
  5330. thread t_;
  5331. };
  5332. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5333. auto res = cli_.Post("/test", "123456789", "text/plain");
  5334. ASSERT_TRUE(res);
  5335. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5336. res = cli_.Post("/test", "12345678", "text/plain");
  5337. ASSERT_TRUE(res);
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. }
  5340. TEST(HostAndPortPropertiesTest, NoSSL) {
  5341. httplib::Client cli("www.google.com", 1234);
  5342. ASSERT_EQ("www.google.com", cli.host());
  5343. ASSERT_EQ(1234, cli.port());
  5344. }
  5345. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5346. httplib::Client cli("www.google.com:1234");
  5347. ASSERT_EQ("www.google.com", cli.host());
  5348. ASSERT_EQ(1234, cli.port());
  5349. }
  5350. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5351. TEST(HostAndPortPropertiesTest, SSL) {
  5352. httplib::SSLClient cli("www.google.com");
  5353. ASSERT_EQ("www.google.com", cli.host());
  5354. ASSERT_EQ(443, cli.port());
  5355. }
  5356. #endif
  5357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5358. TEST(SSLClientTest, UpdateCAStore) {
  5359. httplib::SSLClient httplib_client("www.google.com");
  5360. auto ca_store_1 = X509_STORE_new();
  5361. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5362. nullptr);
  5363. httplib_client.set_ca_cert_store(ca_store_1);
  5364. auto ca_store_2 = X509_STORE_new();
  5365. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5366. nullptr);
  5367. httplib_client.set_ca_cert_store(ca_store_2);
  5368. }
  5369. TEST(SSLClientTest, ServerNameIndication_Online) {
  5370. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5371. auto host = "httpbin.org";
  5372. auto path = std::string{"/get"};
  5373. #else
  5374. auto host = "nghttp2.org";
  5375. auto path = std::string{"/httpbin/get"};
  5376. #endif
  5377. SSLClient cli(host, 443);
  5378. auto res = cli.Get(path);
  5379. ASSERT_TRUE(res);
  5380. ASSERT_EQ(StatusCode::OK_200, res->status);
  5381. }
  5382. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5383. Client cli("https://google.com");
  5384. auto res = cli.Get("/");
  5385. ASSERT_TRUE(res);
  5386. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5387. }
  5388. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5389. SSLClient cli("google.com");
  5390. cli.enable_server_certificate_verification(true);
  5391. cli.set_ca_cert_path("hello");
  5392. auto res = cli.Get("/");
  5393. ASSERT_TRUE(!res);
  5394. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5395. }
  5396. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5397. SSLClient cli("google.com");
  5398. cli.set_ca_cert_path(CA_CERT_FILE);
  5399. auto res = cli.Get("/");
  5400. ASSERT_TRUE(res);
  5401. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5402. }
  5403. TEST(SSLClientTest, ServerCertificateVerification4) {
  5404. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5405. ASSERT_TRUE(svr.is_valid());
  5406. svr.Get("/test", [&](const Request &, Response &res) {
  5407. res.set_content("test", "text/plain");
  5408. svr.stop();
  5409. ASSERT_TRUE(true);
  5410. });
  5411. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5412. auto se = detail::scope_exit([&] {
  5413. t.join();
  5414. ASSERT_FALSE(svr.is_running());
  5415. });
  5416. svr.wait_until_ready();
  5417. SSLClient cli("127.0.0.1", PORT);
  5418. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5419. cli.enable_server_certificate_verification(true);
  5420. cli.set_connection_timeout(30);
  5421. auto res = cli.Get("/test");
  5422. ASSERT_TRUE(res);
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. }
  5425. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5426. std::string cert;
  5427. read_file(CA_CERT_FILE, cert);
  5428. SSLClient cli("google.com");
  5429. cli.load_ca_cert_store(cert.data(), cert.size());
  5430. const auto res = cli.Get("/");
  5431. ASSERT_TRUE(res);
  5432. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5433. }
  5434. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5435. // clang-format off
  5436. static constexpr char cert[] =
  5437. "GlobalSign Root CA\n"
  5438. "==================\n"
  5439. "-----BEGIN CERTIFICATE-----\n"
  5440. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5441. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5442. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5443. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5444. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5445. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5446. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5447. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5448. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5449. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5450. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5451. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5452. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5453. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5454. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5455. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5456. "-----END CERTIFICATE-----\n";
  5457. // clang-format on
  5458. SSLClient cli("google.com");
  5459. cli.load_ca_cert_store(cert, sizeof(cert));
  5460. const auto res = cli.Get("/");
  5461. ASSERT_TRUE(res);
  5462. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5463. }
  5464. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5465. SSLClient cli("www.youtube.com");
  5466. cli.set_ca_cert_path(CA_CERT_FILE);
  5467. cli.enable_server_certificate_verification(true);
  5468. cli.set_follow_location(true);
  5469. auto res = cli.Get("/");
  5470. ASSERT_TRUE(res);
  5471. ASSERT_EQ(StatusCode::OK_200, res->status);
  5472. }
  5473. TEST(SSLClientTest, Issue2004_Online) {
  5474. Client client("https://google.com");
  5475. client.set_follow_location(true);
  5476. auto res = client.Get("/");
  5477. ASSERT_TRUE(res);
  5478. ASSERT_EQ(StatusCode::OK_200, res->status);
  5479. auto body = res->body;
  5480. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5481. }
  5482. #if 0
  5483. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5484. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5485. ASSERT_TRUE(cli != nullptr);
  5486. cli->set_address_family(AF_INET6);
  5487. cli->set_interface("en0");
  5488. auto res = cli->Get("/get");
  5489. ASSERT_TRUE(res);
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. #endif
  5493. void ClientCertPresent(
  5494. const std::string &client_cert_file,
  5495. const std::string &client_private_key_file,
  5496. const std::string &client_encrypted_private_key_pass = std::string()) {
  5497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5498. CLIENT_CA_CERT_DIR);
  5499. ASSERT_TRUE(svr.is_valid());
  5500. svr.Get("/test", [&](const Request &req, Response &res) {
  5501. res.set_content("test", "text/plain");
  5502. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5503. ASSERT_TRUE(peer_cert != nullptr);
  5504. auto subject_name = X509_get_subject_name(peer_cert);
  5505. ASSERT_TRUE(subject_name != nullptr);
  5506. std::string common_name;
  5507. {
  5508. char name[BUFSIZ];
  5509. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5510. name, sizeof(name));
  5511. common_name.assign(name, static_cast<size_t>(name_len));
  5512. }
  5513. EXPECT_EQ("Common Name", common_name);
  5514. X509_free(peer_cert);
  5515. });
  5516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5517. auto se = detail::scope_exit([&] {
  5518. svr.stop();
  5519. t.join();
  5520. ASSERT_FALSE(svr.is_running());
  5521. });
  5522. svr.wait_until_ready();
  5523. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5524. client_encrypted_private_key_pass);
  5525. cli.enable_server_certificate_verification(false);
  5526. cli.set_connection_timeout(30);
  5527. auto res = cli.Get("/test");
  5528. ASSERT_TRUE(res);
  5529. ASSERT_EQ(StatusCode::OK_200, res->status);
  5530. }
  5531. TEST(SSLClientServerTest, ClientCertPresent) {
  5532. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5533. }
  5534. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5535. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5536. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5537. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5538. }
  5539. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5540. void MemoryClientCertPresent(
  5541. const std::string &client_cert_file,
  5542. const std::string &client_private_key_file,
  5543. const std::string &client_encrypted_private_key_pass = std::string()) {
  5544. auto f = fopen(SERVER_CERT_FILE, "r+");
  5545. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5546. fclose(f);
  5547. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5548. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5549. fclose(f);
  5550. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5551. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5552. auto client_ca_cert_store = X509_STORE_new();
  5553. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5554. X509_free(client_cert);
  5555. fclose(f);
  5556. f = fopen(client_cert_file.c_str(), "r+");
  5557. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5558. fclose(f);
  5559. f = fopen(client_private_key_file.c_str(), "r+");
  5560. auto client_private_key = PEM_read_PrivateKey(
  5561. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5562. fclose(f);
  5563. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5564. ASSERT_TRUE(svr.is_valid());
  5565. svr.Get("/test", [&](const Request &req, Response &res) {
  5566. res.set_content("test", "text/plain");
  5567. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5568. ASSERT_TRUE(peer_cert != nullptr);
  5569. auto subject_name = X509_get_subject_name(peer_cert);
  5570. ASSERT_TRUE(subject_name != nullptr);
  5571. std::string common_name;
  5572. {
  5573. char name[BUFSIZ];
  5574. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5575. name, sizeof(name));
  5576. common_name.assign(name, static_cast<size_t>(name_len));
  5577. }
  5578. EXPECT_EQ("Common Name", common_name);
  5579. X509_free(peer_cert);
  5580. });
  5581. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5582. auto se = detail::scope_exit([&] {
  5583. svr.stop();
  5584. t.join();
  5585. ASSERT_FALSE(svr.is_running());
  5586. });
  5587. svr.wait_until_ready();
  5588. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5589. client_encrypted_private_key_pass);
  5590. cli.enable_server_certificate_verification(false);
  5591. cli.set_connection_timeout(30);
  5592. auto res = cli.Get("/test");
  5593. ASSERT_TRUE(res);
  5594. ASSERT_EQ(StatusCode::OK_200, res->status);
  5595. X509_free(server_cert);
  5596. EVP_PKEY_free(server_private_key);
  5597. X509_free(client_cert);
  5598. EVP_PKEY_free(client_private_key);
  5599. }
  5600. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5601. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5602. }
  5603. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5604. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5605. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5606. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5607. }
  5608. #endif
  5609. TEST(SSLClientServerTest, ClientCertMissing) {
  5610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5611. CLIENT_CA_CERT_DIR);
  5612. ASSERT_TRUE(svr.is_valid());
  5613. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5615. auto se = detail::scope_exit([&] {
  5616. svr.stop();
  5617. t.join();
  5618. ASSERT_FALSE(svr.is_running());
  5619. });
  5620. svr.wait_until_ready();
  5621. SSLClient cli(HOST, PORT);
  5622. auto res = cli.Get("/test");
  5623. cli.set_connection_timeout(30);
  5624. ASSERT_TRUE(!res);
  5625. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5626. }
  5627. TEST(SSLClientServerTest, TrustDirOptional) {
  5628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5629. ASSERT_TRUE(svr.is_valid());
  5630. svr.Get("/test", [&](const Request &, Response &res) {
  5631. res.set_content("test", "text/plain");
  5632. });
  5633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5634. auto se = detail::scope_exit([&] {
  5635. svr.stop();
  5636. t.join();
  5637. ASSERT_FALSE(svr.is_running());
  5638. });
  5639. svr.wait_until_ready();
  5640. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5641. cli.enable_server_certificate_verification(false);
  5642. cli.set_connection_timeout(30);
  5643. auto res = cli.Get("/test");
  5644. ASSERT_TRUE(res);
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. }
  5647. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5648. class NoListenSSLServer : public SSLServer {
  5649. public:
  5650. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5651. const char *client_ca_cert_file_path,
  5652. const char *client_ca_cert_dir_path = nullptr)
  5653. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5654. client_ca_cert_dir_path),
  5655. stop_(false) {}
  5656. std::atomic_bool stop_;
  5657. private:
  5658. bool process_and_close_socket(socket_t /*sock*/) override {
  5659. // Don't create SSL context
  5660. while (!stop_.load()) {
  5661. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5662. }
  5663. return true;
  5664. }
  5665. };
  5666. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5667. CLIENT_CA_CERT_FILE);
  5668. ASSERT_TRUE(svr.is_valid());
  5669. svr.Get("/test", [&](const Request &, Response &res) {
  5670. res.set_content("test", "text/plain");
  5671. });
  5672. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5673. auto se = detail::scope_exit([&] {
  5674. svr.stop_ = true;
  5675. svr.stop();
  5676. t.join();
  5677. ASSERT_FALSE(svr.is_running());
  5678. });
  5679. svr.wait_until_ready();
  5680. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5681. cli.enable_server_certificate_verification(false);
  5682. cli.set_connection_timeout(1);
  5683. auto res = cli.Get("/test");
  5684. ASSERT_TRUE(!res);
  5685. EXPECT_EQ(Error::SSLConnection, res.error());
  5686. }
  5687. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5688. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5689. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5690. SSL_CTX_set_options(&ssl_ctx,
  5691. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5692. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5693. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5694. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5695. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5696. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5697. "ECDHE-DSS-AES128-SHA256:"
  5698. "ECDHE-RSA-AES256-SHA256:"
  5699. "ECDHE-DSS-AES256-SHA256:";
  5700. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5701. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5702. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5703. SSL_FILETYPE_PEM) != 1) {
  5704. return false;
  5705. }
  5706. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5707. CLIENT_CA_CERT_DIR);
  5708. SSL_CTX_set_verify(
  5709. &ssl_ctx,
  5710. SSL_VERIFY_PEER |
  5711. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5712. nullptr);
  5713. return true;
  5714. };
  5715. SSLServer svr(setup_ssl_ctx_callback);
  5716. ASSERT_TRUE(svr.is_valid());
  5717. svr.Get("/test", [&](const Request &req, Response &res) {
  5718. res.set_content("test", "text/plain");
  5719. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5720. ASSERT_TRUE(peer_cert != nullptr);
  5721. auto subject_name = X509_get_subject_name(peer_cert);
  5722. ASSERT_TRUE(subject_name != nullptr);
  5723. std::string common_name;
  5724. {
  5725. char name[BUFSIZ];
  5726. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5727. name, sizeof(name));
  5728. common_name.assign(name, static_cast<size_t>(name_len));
  5729. }
  5730. EXPECT_EQ("Common Name", common_name);
  5731. X509_free(peer_cert);
  5732. });
  5733. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5734. auto se = detail::scope_exit([&] {
  5735. svr.stop();
  5736. t.join();
  5737. ASSERT_FALSE(svr.is_running());
  5738. });
  5739. svr.wait_until_ready();
  5740. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5741. cli.enable_server_certificate_verification(false);
  5742. cli.set_connection_timeout(30);
  5743. auto res = cli.Get("/test");
  5744. ASSERT_TRUE(res);
  5745. ASSERT_EQ(StatusCode::OK_200, res->status);
  5746. }
  5747. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5748. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5749. // prepare large data
  5750. std::random_device seed_gen;
  5751. std::mt19937 random(seed_gen());
  5752. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5753. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5754. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5755. // server
  5756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5757. ASSERT_TRUE(svr.is_valid());
  5758. svr.Post("/binary", [&](const Request &req, Response &res) {
  5759. EXPECT_EQ(large_size_byte, req.body.size());
  5760. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5761. res.set_content(req.body, "application/octet-stream");
  5762. });
  5763. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5764. auto se = detail::scope_exit([&] {
  5765. svr.stop();
  5766. listen_thread.join();
  5767. ASSERT_FALSE(svr.is_running());
  5768. });
  5769. svr.wait_until_ready();
  5770. // client POST
  5771. SSLClient cli("localhost", PORT);
  5772. cli.enable_server_certificate_verification(false);
  5773. cli.set_read_timeout(std::chrono::seconds(100));
  5774. cli.set_write_timeout(std::chrono::seconds(100));
  5775. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5776. large_size_byte, "application/octet-stream");
  5777. // compare
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ(large_size_byte, res->body.size());
  5780. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5781. }
  5782. #endif
  5783. #ifdef _WIN32
  5784. TEST(CleanupTest, WSACleanup) {
  5785. int ret = WSACleanup();
  5786. ASSERT_EQ(0, ret);
  5787. }
  5788. #endif
  5789. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5790. TEST(NoSSLSupport, SimpleInterface) {
  5791. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5792. }
  5793. #endif
  5794. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5795. TEST(InvalidScheme, SimpleInterface) {
  5796. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5797. }
  5798. #endif
  5799. TEST(NoScheme, SimpleInterface) {
  5800. Client cli("yahoo.com:80");
  5801. ASSERT_TRUE(cli.is_valid());
  5802. }
  5803. TEST(SendAPI, SimpleInterface_Online) {
  5804. Client cli("http://yahoo.com");
  5805. Request req;
  5806. req.method = "GET";
  5807. req.path = "/";
  5808. auto res = cli.send(req);
  5809. ASSERT_TRUE(res);
  5810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5811. }
  5812. TEST(SendAPI, WithParamsInRequest) {
  5813. Server svr;
  5814. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  5815. EXPECT_TRUE(req.has_param("test"));
  5816. EXPECT_EQ("test_value", req.get_param_value("test"));
  5817. });
  5818. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  5819. auto se = detail::scope_exit([&] {
  5820. svr.stop();
  5821. t.join();
  5822. ASSERT_FALSE(svr.is_running());
  5823. });
  5824. svr.wait_until_ready();
  5825. Client cli(HOST, PORT);
  5826. {
  5827. Request req;
  5828. req.method = "GET";
  5829. req.path = "/";
  5830. req.params.emplace("test", "test_value");
  5831. auto res = cli.send(req);
  5832. ASSERT_TRUE(res);
  5833. }
  5834. {
  5835. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  5836. ASSERT_TRUE(res);
  5837. }
  5838. }
  5839. TEST(ClientImplMethods, GetSocketTest) {
  5840. httplib::Server svr;
  5841. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5842. res.status = StatusCode::OK_200;
  5843. });
  5844. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5845. auto se = detail::scope_exit([&] {
  5846. svr.stop();
  5847. thread.join();
  5848. ASSERT_FALSE(svr.is_running());
  5849. });
  5850. svr.wait_until_ready();
  5851. {
  5852. httplib::Client cli("http://127.0.0.1:3333");
  5853. cli.set_keep_alive(true);
  5854. // Use the behavior of cpp-httplib of opening the connection
  5855. // only when the first request happens. If that changes,
  5856. // this test would be obsolete.
  5857. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5858. // This also implicitly tests the server. But other tests would fail much
  5859. // earlier than this one to be considered.
  5860. auto res = cli.Get("/");
  5861. ASSERT_TRUE(res);
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5864. }
  5865. }
  5866. // Disabled due to out-of-memory problem on GitHub Actions
  5867. #ifdef _WIN64
  5868. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5869. // allocate content size larger than 2GB in memory
  5870. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5871. char *content = (char *)malloc(content_size);
  5872. ASSERT_TRUE(content);
  5873. Server svr;
  5874. svr.Get("/foo",
  5875. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5876. res.set_content(content, content_size, "application/octet-stream");
  5877. });
  5878. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5879. auto se = detail::scope_exit([&] {
  5880. svr.stop();
  5881. listen_thread.join();
  5882. if (content) free(content);
  5883. ASSERT_FALSE(svr.is_running());
  5884. });
  5885. svr.wait_until_ready();
  5886. Client cli(HOST, PORT);
  5887. auto res = cli.Get("/foo");
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. EXPECT_EQ(content_size, res->body.length());
  5891. }
  5892. #endif
  5893. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5894. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5895. Client cli("http://yahoo.com");
  5896. auto res = cli.Get("/");
  5897. ASSERT_TRUE(res);
  5898. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5899. cli.set_follow_location(true);
  5900. res = cli.Get("/");
  5901. ASSERT_TRUE(res);
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5904. }
  5905. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5906. Client cli("https://yahoo.com");
  5907. auto res = cli.Get("/");
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5910. cli.set_follow_location(true);
  5911. res = cli.Get("/");
  5912. ASSERT_TRUE(res);
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5915. }
  5916. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5917. Client cli("https://yahoo.com");
  5918. auto res = cli.Get("/");
  5919. ASSERT_TRUE(res);
  5920. ASSERT_FALSE(!res);
  5921. ASSERT_TRUE(res);
  5922. ASSERT_FALSE(res == nullptr);
  5923. ASSERT_TRUE(res != nullptr);
  5924. EXPECT_EQ(Error::Success, res.error());
  5925. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5926. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5927. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5928. cli.set_follow_location(true);
  5929. res = cli.Get("/");
  5930. ASSERT_TRUE(res);
  5931. EXPECT_EQ(Error::Success, res.error());
  5932. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5933. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5934. EXPECT_EQ(StatusCode::OK_200, res->status);
  5935. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5936. }
  5937. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5938. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5939. Client cli("https://cdnjs.cloudflare.com");
  5940. auto res =
  5941. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5942. ASSERT_TRUE(res);
  5943. EXPECT_EQ(StatusCode::OK_200, res->status);
  5944. EXPECT_EQ(287630U, res->body.size());
  5945. EXPECT_EQ("application/javascript; charset=utf-8",
  5946. res->get_header_value("Content-Type"));
  5947. }
  5948. #endif
  5949. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  5950. #undef REDIR_HOST // Silence compiler warning
  5951. #define REDIR_HOST "https://httpbingo.org"
  5952. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5953. Client cli(REDIR_HOST);
  5954. cli.set_follow_location(true);
  5955. auto res =
  5956. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  5957. ASSERT_TRUE(res);
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. }
  5960. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5961. Client cli(REDIR_HOST);
  5962. cli.set_follow_location(true);
  5963. Params params;
  5964. params.emplace("url", "http://example.com");
  5965. params.emplace("status_code", "302");
  5966. auto res = cli.Get(REDIR_PATH, params, Headers{});
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. }
  5970. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5971. Client cli(REDIR_HOST);
  5972. cli.set_follow_location(true);
  5973. Params params;
  5974. params.emplace("url", "http://example.com");
  5975. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  5976. ASSERT_TRUE(res);
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST(HttpToHttpsRedirectTest, CertFile) {
  5980. Server svr;
  5981. ASSERT_TRUE(svr.is_valid());
  5982. svr.Get("/index", [&](const Request &, Response &res) {
  5983. res.set_redirect("https://127.0.0.1:1235/index");
  5984. svr.stop();
  5985. });
  5986. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5987. ASSERT_TRUE(ssl_svr.is_valid());
  5988. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5989. res.set_content("test", "text/plain");
  5990. ssl_svr.stop();
  5991. });
  5992. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5993. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5994. auto se = detail::scope_exit([&] {
  5995. t2.join();
  5996. t.join();
  5997. ASSERT_FALSE(svr.is_running());
  5998. });
  5999. svr.wait_until_ready();
  6000. ssl_svr.wait_until_ready();
  6001. Client cli("127.0.0.1", PORT);
  6002. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6003. cli.enable_server_certificate_verification(true);
  6004. cli.set_follow_location(true);
  6005. cli.set_connection_timeout(30);
  6006. auto res = cli.Get("/index");
  6007. ASSERT_TRUE(res);
  6008. ASSERT_EQ(StatusCode::OK_200, res->status);
  6009. }
  6010. TEST(MultipartFormDataTest, LargeData) {
  6011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6012. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6013. const ContentReader &content_reader) {
  6014. if (req.is_multipart_form_data()) {
  6015. MultipartFormDataItems files;
  6016. content_reader(
  6017. [&](const MultipartFormData &file) {
  6018. files.push_back(file);
  6019. return true;
  6020. },
  6021. [&](const char *data, size_t data_length) {
  6022. files.back().content.append(data, data_length);
  6023. return true;
  6024. });
  6025. EXPECT_TRUE(std::string(files[0].name) == "document");
  6026. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6027. EXPECT_TRUE(files[0].filename == "2MB_data");
  6028. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6029. EXPECT_TRUE(files[1].name == "hello");
  6030. EXPECT_TRUE(files[1].content == "world");
  6031. EXPECT_TRUE(files[1].filename == "");
  6032. EXPECT_TRUE(files[1].content_type == "");
  6033. } else {
  6034. std::string body;
  6035. content_reader([&](const char *data, size_t data_length) {
  6036. body.append(data, data_length);
  6037. return true;
  6038. });
  6039. }
  6040. });
  6041. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6042. auto se = detail::scope_exit([&] {
  6043. svr.stop();
  6044. t.join();
  6045. ASSERT_FALSE(svr.is_running());
  6046. });
  6047. svr.wait_until_ready();
  6048. {
  6049. std::string data(1024 * 1024 * 2, '.');
  6050. std::stringstream buffer;
  6051. buffer << data;
  6052. Client cli("https://localhost:8080");
  6053. cli.enable_server_certificate_verification(false);
  6054. MultipartFormDataItems items{
  6055. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6056. {"hello", "world", "", ""},
  6057. };
  6058. auto res = cli.Post("/post", items);
  6059. ASSERT_TRUE(res);
  6060. ASSERT_EQ(StatusCode::OK_200, res->status);
  6061. }
  6062. }
  6063. TEST(MultipartFormDataTest, DataProviderItems) {
  6064. std::random_device seed_gen;
  6065. std::mt19937 random(seed_gen());
  6066. std::string rand1;
  6067. rand1.resize(1000);
  6068. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6069. std::string rand2;
  6070. rand2.resize(3000);
  6071. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6073. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6074. const ContentReader &content_reader) {
  6075. ASSERT_FALSE(req.is_multipart_form_data());
  6076. std::string body;
  6077. content_reader([&](const char *data, size_t data_length) {
  6078. body.append(data, data_length);
  6079. return true;
  6080. });
  6081. EXPECT_EQ(body, "");
  6082. });
  6083. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6084. const ContentReader &content_reader) {
  6085. ASSERT_TRUE(req.is_multipart_form_data());
  6086. MultipartFormDataItems files;
  6087. content_reader(
  6088. [&](const MultipartFormData &file) {
  6089. files.push_back(file);
  6090. return true;
  6091. },
  6092. [&](const char *data, size_t data_length) {
  6093. files.back().content.append(data, data_length);
  6094. return true;
  6095. });
  6096. ASSERT_TRUE(files.size() == 2);
  6097. EXPECT_EQ(std::string(files[0].name), "name1");
  6098. EXPECT_EQ(files[0].content, "Testing123");
  6099. EXPECT_EQ(files[0].filename, "filename1");
  6100. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6101. EXPECT_EQ(files[1].name, "name2");
  6102. EXPECT_EQ(files[1].content, "Testing456");
  6103. EXPECT_EQ(files[1].filename, "");
  6104. EXPECT_EQ(files[1].content_type, "");
  6105. });
  6106. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6107. const ContentReader &content_reader) {
  6108. ASSERT_TRUE(req.is_multipart_form_data());
  6109. MultipartFormDataItems files;
  6110. content_reader(
  6111. [&](const MultipartFormData &file) {
  6112. files.push_back(file);
  6113. return true;
  6114. },
  6115. [&](const char *data, size_t data_length) {
  6116. files.back().content.append(data, data_length);
  6117. return true;
  6118. });
  6119. ASSERT_TRUE(files.size() == 2);
  6120. EXPECT_EQ(files[0].name, "name3");
  6121. EXPECT_EQ(files[0].content, rand1);
  6122. EXPECT_EQ(files[0].filename, "filename3");
  6123. EXPECT_EQ(files[0].content_type, "");
  6124. EXPECT_EQ(files[1].name, "name4");
  6125. EXPECT_EQ(files[1].content, rand2);
  6126. EXPECT_EQ(files[1].filename, "filename4");
  6127. EXPECT_EQ(files[1].content_type, "");
  6128. });
  6129. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6130. const ContentReader &content_reader) {
  6131. ASSERT_TRUE(req.is_multipart_form_data());
  6132. MultipartFormDataItems files;
  6133. content_reader(
  6134. [&](const MultipartFormData &file) {
  6135. files.push_back(file);
  6136. return true;
  6137. },
  6138. [&](const char *data, size_t data_length) {
  6139. files.back().content.append(data, data_length);
  6140. return true;
  6141. });
  6142. ASSERT_TRUE(files.size() == 4);
  6143. EXPECT_EQ(std::string(files[0].name), "name1");
  6144. EXPECT_EQ(files[0].content, "Testing123");
  6145. EXPECT_EQ(files[0].filename, "filename1");
  6146. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6147. EXPECT_EQ(files[1].name, "name2");
  6148. EXPECT_EQ(files[1].content, "Testing456");
  6149. EXPECT_EQ(files[1].filename, "");
  6150. EXPECT_EQ(files[1].content_type, "");
  6151. EXPECT_EQ(files[2].name, "name3");
  6152. EXPECT_EQ(files[2].content, rand1);
  6153. EXPECT_EQ(files[2].filename, "filename3");
  6154. EXPECT_EQ(files[2].content_type, "");
  6155. EXPECT_EQ(files[3].name, "name4");
  6156. EXPECT_EQ(files[3].content, rand2);
  6157. EXPECT_EQ(files[3].filename, "filename4");
  6158. EXPECT_EQ(files[3].content_type, "");
  6159. });
  6160. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6161. auto se = detail::scope_exit([&] {
  6162. svr.stop();
  6163. t.join();
  6164. ASSERT_FALSE(svr.is_running());
  6165. });
  6166. svr.wait_until_ready();
  6167. {
  6168. Client cli("https://localhost:8080");
  6169. cli.enable_server_certificate_verification(false);
  6170. MultipartFormDataItems items{
  6171. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6172. {"name2", "Testing456", "", ""}, // not a file
  6173. };
  6174. {
  6175. auto res = cli.Post("/post-none", {}, {}, {});
  6176. ASSERT_TRUE(res);
  6177. ASSERT_EQ(StatusCode::OK_200, res->status);
  6178. }
  6179. MultipartFormDataProviderItems providers;
  6180. {
  6181. auto res =
  6182. cli.Post("/post-items", {}, items, providers); // empty providers
  6183. ASSERT_TRUE(res);
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. }
  6186. providers.push_back({"name3",
  6187. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6188. // test the offset is given correctly at each step
  6189. if (!offset)
  6190. sink.os.write(rand1.data(), 30);
  6191. else if (offset == 30)
  6192. sink.os.write(rand1.data() + 30, 300);
  6193. else if (offset == 330)
  6194. sink.os.write(rand1.data() + 330, 670);
  6195. else if (offset == rand1.size())
  6196. sink.done();
  6197. return true;
  6198. },
  6199. "filename3",
  6200. {}});
  6201. providers.push_back({"name4",
  6202. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6203. // test the offset is given correctly at each step
  6204. if (!offset)
  6205. sink.os.write(rand2.data(), 2000);
  6206. else if (offset == 2000)
  6207. sink.os.write(rand2.data() + 2000, 1);
  6208. else if (offset == 2001)
  6209. sink.os.write(rand2.data() + 2001, 999);
  6210. else if (offset == rand2.size())
  6211. sink.done();
  6212. return true;
  6213. },
  6214. "filename4",
  6215. {}});
  6216. {
  6217. auto res = cli.Post("/post-providers", {}, {}, providers);
  6218. ASSERT_TRUE(res);
  6219. ASSERT_EQ(StatusCode::OK_200, res->status);
  6220. }
  6221. {
  6222. auto res = cli.Post("/post-both", {}, items, providers);
  6223. ASSERT_TRUE(res);
  6224. ASSERT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. }
  6227. }
  6228. TEST(MultipartFormDataTest, BadHeader) {
  6229. Server svr;
  6230. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6231. res.set_content("ok", "text/plain");
  6232. });
  6233. thread t = thread([&] { svr.listen(HOST, PORT); });
  6234. auto se = detail::scope_exit([&] {
  6235. svr.stop();
  6236. t.join();
  6237. ASSERT_FALSE(svr.is_running());
  6238. });
  6239. svr.wait_until_ready();
  6240. const std::string body =
  6241. "This is the preamble. It is to be ignored, though it\r\n"
  6242. "is a handy place for composition agents to include an\r\n"
  6243. "explanatory note to non-MIME conformant readers.\r\n"
  6244. "\r\n"
  6245. "\r\n"
  6246. "--simple boundary\r\n"
  6247. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6248. ": BAD...\r\n"
  6249. "\r\n"
  6250. "value1\r\n"
  6251. "--simple boundary\r\n"
  6252. "Content-Disposition: form-data; name=\"field2\"; "
  6253. "filename=\"example.txt\"\r\n"
  6254. "\r\n"
  6255. "value2\r\n"
  6256. "--simple boundary--\r\n"
  6257. "This is the epilogue. It is also to be ignored.\r\n";
  6258. std::string content_type =
  6259. R"(multipart/form-data; boundary="simple boundary")";
  6260. Client cli(HOST, PORT);
  6261. auto res = cli.Post("/post", body, content_type.c_str());
  6262. ASSERT_TRUE(res);
  6263. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6264. }
  6265. TEST(MultipartFormDataTest, WithPreamble) {
  6266. Server svr;
  6267. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6268. res.set_content("ok", "text/plain");
  6269. });
  6270. thread t = thread([&] { svr.listen(HOST, PORT); });
  6271. auto se = detail::scope_exit([&] {
  6272. svr.stop();
  6273. t.join();
  6274. ASSERT_FALSE(svr.is_running());
  6275. });
  6276. svr.wait_until_ready();
  6277. const std::string body =
  6278. "This is the preamble. It is to be ignored, though it\r\n"
  6279. "is a handy place for composition agents to include an\r\n"
  6280. "explanatory note to non-MIME conformant readers.\r\n"
  6281. "\r\n"
  6282. "\r\n"
  6283. "--simple boundary\r\n"
  6284. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6285. "\r\n"
  6286. "value1\r\n"
  6287. "--simple boundary\r\n"
  6288. "Content-Disposition: form-data; name=\"field2\"; "
  6289. "filename=\"example.txt\"\r\n"
  6290. "\r\n"
  6291. "value2\r\n"
  6292. "--simple boundary--\r\n"
  6293. "This is the epilogue. It is also to be ignored.\r\n";
  6294. std::string content_type =
  6295. R"(multipart/form-data; boundary="simple boundary")";
  6296. Client cli(HOST, PORT);
  6297. auto res = cli.Post("/post", body, content_type.c_str());
  6298. ASSERT_TRUE(res);
  6299. EXPECT_EQ(StatusCode::OK_200, res->status);
  6300. }
  6301. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6303. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6304. const ContentReader &content_reader) {
  6305. if (req.is_multipart_form_data()) {
  6306. MultipartFormDataItems files;
  6307. content_reader(
  6308. [&](const MultipartFormData &file) {
  6309. files.push_back(file);
  6310. return true;
  6311. },
  6312. [&](const char *data, size_t data_length) {
  6313. files.back().content.append(data, data_length);
  6314. return true;
  6315. });
  6316. EXPECT_TRUE(std::string(files[0].name) == "document");
  6317. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6318. EXPECT_TRUE(files[0].filename == "2MB_data");
  6319. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6320. EXPECT_TRUE(files[1].name == "hello");
  6321. EXPECT_TRUE(files[1].content == "world");
  6322. EXPECT_TRUE(files[1].filename == "");
  6323. EXPECT_TRUE(files[1].content_type == "");
  6324. } else {
  6325. std::string body;
  6326. content_reader([&](const char *data, size_t data_length) {
  6327. body.append(data, data_length);
  6328. return true;
  6329. });
  6330. }
  6331. });
  6332. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6333. auto se = detail::scope_exit([&] {
  6334. svr.stop();
  6335. t.join();
  6336. ASSERT_FALSE(svr.is_running());
  6337. });
  6338. svr.wait_until_ready();
  6339. {
  6340. std::string data(1024 * 1024 * 2, '.');
  6341. std::stringstream buffer;
  6342. buffer << data;
  6343. Client cli("https://localhost:8080");
  6344. cli.enable_server_certificate_verification(false);
  6345. MultipartFormDataItems items{
  6346. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6347. {"hello", "world", "", ""},
  6348. };
  6349. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6350. ASSERT_TRUE(res);
  6351. ASSERT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. }
  6354. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6355. std::string data(1024 * 1024 * 2, '&');
  6356. std::stringstream buffer;
  6357. buffer << data;
  6358. Client cli("https://localhost:8080");
  6359. MultipartFormDataItems items{
  6360. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6361. {"hello", "world", "", ""},
  6362. };
  6363. for (const char &c : " \t\r\n") {
  6364. auto res =
  6365. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6366. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6367. ASSERT_FALSE(res);
  6368. }
  6369. }
  6370. TEST(MultipartFormDataTest, PutFormData) {
  6371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6372. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6373. const ContentReader &content_reader) {
  6374. if (req.is_multipart_form_data()) {
  6375. MultipartFormDataItems files;
  6376. content_reader(
  6377. [&](const MultipartFormData &file) {
  6378. files.push_back(file);
  6379. return true;
  6380. },
  6381. [&](const char *data, size_t data_length) {
  6382. files.back().content.append(data, data_length);
  6383. return true;
  6384. });
  6385. EXPECT_TRUE(std::string(files[0].name) == "document");
  6386. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6387. EXPECT_TRUE(files[0].filename == "2MB_data");
  6388. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6389. EXPECT_TRUE(files[1].name == "hello");
  6390. EXPECT_TRUE(files[1].content == "world");
  6391. EXPECT_TRUE(files[1].filename == "");
  6392. EXPECT_TRUE(files[1].content_type == "");
  6393. } else {
  6394. std::string body;
  6395. content_reader([&](const char *data, size_t data_length) {
  6396. body.append(data, data_length);
  6397. return true;
  6398. });
  6399. }
  6400. });
  6401. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6402. auto se = detail::scope_exit([&] {
  6403. svr.stop();
  6404. t.join();
  6405. ASSERT_FALSE(svr.is_running());
  6406. });
  6407. svr.wait_until_ready();
  6408. {
  6409. std::string data(1024 * 1024 * 2, '&');
  6410. std::stringstream buffer;
  6411. buffer << data;
  6412. Client cli("https://localhost:8080");
  6413. cli.enable_server_certificate_verification(false);
  6414. MultipartFormDataItems items{
  6415. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6416. {"hello", "world", "", ""},
  6417. };
  6418. auto res = cli.Put("/put", items);
  6419. ASSERT_TRUE(res);
  6420. ASSERT_EQ(StatusCode::OK_200, res->status);
  6421. }
  6422. }
  6423. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6425. svr.Put("/put_customboundary",
  6426. [&](const Request &req, const Response & /*res*/,
  6427. const ContentReader &content_reader) {
  6428. if (req.is_multipart_form_data()) {
  6429. MultipartFormDataItems files;
  6430. content_reader(
  6431. [&](const MultipartFormData &file) {
  6432. files.push_back(file);
  6433. return true;
  6434. },
  6435. [&](const char *data, size_t data_length) {
  6436. files.back().content.append(data, data_length);
  6437. return true;
  6438. });
  6439. EXPECT_TRUE(std::string(files[0].name) == "document");
  6440. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6441. EXPECT_TRUE(files[0].filename == "2MB_data");
  6442. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6443. EXPECT_TRUE(files[1].name == "hello");
  6444. EXPECT_TRUE(files[1].content == "world");
  6445. EXPECT_TRUE(files[1].filename == "");
  6446. EXPECT_TRUE(files[1].content_type == "");
  6447. } else {
  6448. std::string body;
  6449. content_reader([&](const char *data, size_t data_length) {
  6450. body.append(data, data_length);
  6451. return true;
  6452. });
  6453. }
  6454. });
  6455. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. t.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. {
  6463. std::string data(1024 * 1024 * 2, '&');
  6464. std::stringstream buffer;
  6465. buffer << data;
  6466. Client cli("https://localhost:8080");
  6467. cli.enable_server_certificate_verification(false);
  6468. MultipartFormDataItems items{
  6469. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6470. {"hello", "world", "", ""},
  6471. };
  6472. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6473. ASSERT_TRUE(res);
  6474. ASSERT_EQ(StatusCode::OK_200, res->status);
  6475. }
  6476. }
  6477. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6478. std::string data(1024 * 1024 * 2, '&');
  6479. std::stringstream buffer;
  6480. buffer << data;
  6481. Client cli("https://localhost:8080");
  6482. cli.enable_server_certificate_verification(false);
  6483. MultipartFormDataItems items{
  6484. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6485. {"hello", "world", "", ""},
  6486. };
  6487. for (const char &c : " \t\r\n") {
  6488. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6489. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6490. ASSERT_FALSE(res);
  6491. }
  6492. }
  6493. TEST(MultipartFormDataTest, AlternateFilename) {
  6494. auto handled = false;
  6495. Server svr;
  6496. svr.Post("/test", [&](const Request &req, Response &res) {
  6497. ASSERT_EQ(3u, req.files.size());
  6498. auto it = req.files.begin();
  6499. ASSERT_EQ("file1", it->second.name);
  6500. ASSERT_EQ("A.txt", it->second.filename);
  6501. ASSERT_EQ("text/plain", it->second.content_type);
  6502. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6503. ++it;
  6504. ASSERT_EQ("file2", it->second.name);
  6505. ASSERT_EQ("a.html", it->second.filename);
  6506. ASSERT_EQ("text/html", it->second.content_type);
  6507. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6508. it->second.content);
  6509. ++it;
  6510. ASSERT_EQ("text", it->second.name);
  6511. ASSERT_EQ("", it->second.filename);
  6512. ASSERT_EQ("", it->second.content_type);
  6513. ASSERT_EQ("text default", it->second.content);
  6514. res.set_content("ok", "text/plain");
  6515. handled = true;
  6516. });
  6517. thread t = thread([&] { svr.listen(HOST, PORT); });
  6518. auto se = detail::scope_exit([&] {
  6519. svr.stop();
  6520. t.join();
  6521. ASSERT_FALSE(svr.is_running());
  6522. ASSERT_TRUE(handled);
  6523. });
  6524. svr.wait_until_ready();
  6525. auto req = "POST /test HTTP/1.1\r\n"
  6526. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6527. "Content-Length: 399\r\n"
  6528. "\r\n"
  6529. "----------\r\n"
  6530. "Content-Disposition: form-data; name=\"text\"\r\n"
  6531. "\r\n"
  6532. "text default\r\n"
  6533. "----------\r\n"
  6534. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6535. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6536. "Content-Type: text/plain\r\n"
  6537. "\r\n"
  6538. "Content of a.txt.\r\n"
  6539. "\r\n"
  6540. "----------\r\n"
  6541. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6542. "\"a.html\"\r\n"
  6543. "Content-Type: text/html\r\n"
  6544. "\r\n"
  6545. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6546. "\r\n"
  6547. "------------\r\n";
  6548. ASSERT_TRUE(send_request(1, req));
  6549. }
  6550. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6551. auto handled = false;
  6552. Server svr;
  6553. svr.Post("/test", [&](const Request &req, Response &) {
  6554. ASSERT_EQ(2u, req.files.size());
  6555. auto it = req.files.begin();
  6556. ASSERT_EQ("text1", it->second.name);
  6557. ASSERT_EQ("text1", it->second.content);
  6558. ++it;
  6559. ASSERT_EQ("text2", it->second.name);
  6560. ASSERT_EQ("text2", it->second.content);
  6561. handled = true;
  6562. });
  6563. thread t = thread([&] { svr.listen(HOST, PORT); });
  6564. auto se = detail::scope_exit([&] {
  6565. svr.stop();
  6566. t.join();
  6567. ASSERT_FALSE(svr.is_running());
  6568. ASSERT_TRUE(handled);
  6569. });
  6570. svr.wait_until_ready();
  6571. auto req = "POST /test HTTP/1.1\r\n"
  6572. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6573. "Content-Length: 146\r\n"
  6574. "\r\n----------\r\n"
  6575. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6576. "\r\n"
  6577. "text1"
  6578. "\r\n----------\r\n"
  6579. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6580. "\r\n"
  6581. "text2"
  6582. "\r\n------------";
  6583. std::string response;
  6584. ASSERT_TRUE(send_request(1, req, &response));
  6585. ASSERT_EQ("200", response.substr(9, 3));
  6586. }
  6587. TEST(MultipartFormDataTest, ContentLength) {
  6588. auto handled = false;
  6589. Server svr;
  6590. svr.Post("/test", [&](const Request &req, Response &) {
  6591. ASSERT_EQ(2u, req.files.size());
  6592. auto it = req.files.begin();
  6593. ASSERT_EQ("text1", it->second.name);
  6594. ASSERT_EQ("text1", it->second.content);
  6595. ++it;
  6596. ASSERT_EQ("text2", it->second.name);
  6597. ASSERT_EQ("text2", it->second.content);
  6598. handled = true;
  6599. });
  6600. thread t = thread([&] { svr.listen(HOST, PORT); });
  6601. auto se = detail::scope_exit([&] {
  6602. svr.stop();
  6603. t.join();
  6604. ASSERT_FALSE(svr.is_running());
  6605. ASSERT_TRUE(handled);
  6606. });
  6607. svr.wait_until_ready();
  6608. auto req = "POST /test HTTP/1.1\r\n"
  6609. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6610. "Content-Length: 167\r\n"
  6611. "\r\n----------\r\n"
  6612. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6613. "Content-Length: 5\r\n"
  6614. "\r\n"
  6615. "text1"
  6616. "\r\n----------\r\n"
  6617. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6618. "\r\n"
  6619. "text2"
  6620. "\r\n------------\r\n";
  6621. std::string response;
  6622. ASSERT_TRUE(send_request(1, req, &response));
  6623. ASSERT_EQ("200", response.substr(9, 3));
  6624. }
  6625. #endif
  6626. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6627. static constexpr unsigned int number_of_tasks{1000000};
  6628. std::atomic_uint count{0};
  6629. std::unique_ptr<TaskQueue> task_queue{
  6630. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6631. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6632. auto queued = task_queue->enqueue(
  6633. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6634. EXPECT_TRUE(queued);
  6635. }
  6636. EXPECT_NO_THROW(task_queue->shutdown());
  6637. EXPECT_EQ(number_of_tasks, count.load());
  6638. }
  6639. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6640. static constexpr unsigned int number_of_tasks{1000000};
  6641. static constexpr unsigned int qlimit{2};
  6642. unsigned int queued_count{0};
  6643. std::atomic_uint count{0};
  6644. std::unique_ptr<TaskQueue> task_queue{
  6645. new ThreadPool{/*num_threads=*/1, qlimit}};
  6646. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6647. if (task_queue->enqueue(
  6648. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6649. queued_count++;
  6650. }
  6651. }
  6652. EXPECT_NO_THROW(task_queue->shutdown());
  6653. EXPECT_EQ(queued_count, count.load());
  6654. EXPECT_TRUE(queued_count <= number_of_tasks);
  6655. EXPECT_TRUE(queued_count >= qlimit);
  6656. }
  6657. TEST(TaskQueueTest, MaxQueuedRequests) {
  6658. static constexpr unsigned int qlimit{3};
  6659. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6660. std::condition_variable sem_cv;
  6661. std::mutex sem_mtx;
  6662. int credits = 0;
  6663. bool queued;
  6664. /* Fill up the queue with tasks that will block until we give them credits to
  6665. * complete. */
  6666. for (unsigned int n = 0; n <= qlimit;) {
  6667. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6668. std::unique_lock<std::mutex> lock(sem_mtx);
  6669. while (credits <= 0) {
  6670. sem_cv.wait(lock);
  6671. }
  6672. /* Consume the credit and signal the test code if they are all gone. */
  6673. if (--credits == 0) { sem_cv.notify_one(); }
  6674. });
  6675. if (n < qlimit) {
  6676. /* The first qlimit enqueues must succeed. */
  6677. EXPECT_TRUE(queued);
  6678. } else {
  6679. /* The last one will succeed only when the worker thread
  6680. * starts and dequeues the first blocking task. Although
  6681. * not necessary for the correctness of this test, we sleep for
  6682. * a short while to avoid busy waiting. */
  6683. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6684. }
  6685. if (queued) { n++; }
  6686. }
  6687. /* Further enqueues must fail since the queue is full. */
  6688. for (auto i = 0; i < 4; i++) {
  6689. queued = task_queue->enqueue([] {});
  6690. EXPECT_FALSE(queued);
  6691. }
  6692. /* Give the credits to allow the previous tasks to complete. */
  6693. {
  6694. std::unique_lock<std::mutex> lock(sem_mtx);
  6695. credits += qlimit + 1;
  6696. }
  6697. sem_cv.notify_all();
  6698. /* Wait for all the credits to be consumed. */
  6699. {
  6700. std::unique_lock<std::mutex> lock(sem_mtx);
  6701. while (credits > 0) {
  6702. sem_cv.wait(lock);
  6703. }
  6704. }
  6705. /* Check that we are able again to enqueue at least qlimit tasks. */
  6706. for (unsigned int i = 0; i < qlimit; i++) {
  6707. queued = task_queue->enqueue([] {});
  6708. EXPECT_TRUE(queued);
  6709. }
  6710. EXPECT_NO_THROW(task_queue->shutdown());
  6711. }
  6712. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6713. Server svr;
  6714. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6715. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6716. });
  6717. svr.Get("/hello", [](const Request &req, Response &res) {
  6718. res.set_content(req.get_param_value("key"), "text/plain");
  6719. });
  6720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6721. auto se = detail::scope_exit([&] {
  6722. svr.stop();
  6723. thread.join();
  6724. ASSERT_FALSE(svr.is_running());
  6725. });
  6726. svr.wait_until_ready();
  6727. {
  6728. Client cli(HOST, PORT);
  6729. cli.set_follow_location(true);
  6730. auto res = cli.Get("/");
  6731. ASSERT_TRUE(res);
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("val&key2=val2", res->body);
  6734. }
  6735. }
  6736. TEST(VulnerabilityTest, CRLFInjection) {
  6737. Server svr;
  6738. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6739. res.set_content("Hello 1", "text/plain");
  6740. });
  6741. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6742. res.set_content("Hello 2", "text/plain");
  6743. });
  6744. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6745. res.set_content("Hello 3", "text/plain");
  6746. });
  6747. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6748. res.set_content("Hello 4", "text/plain");
  6749. });
  6750. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6751. for (const auto &x : req.headers) {
  6752. auto key = x.first;
  6753. EXPECT_STRNE("evil", key.c_str());
  6754. }
  6755. });
  6756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6757. auto se = detail::scope_exit([&] {
  6758. svr.stop();
  6759. thread.join();
  6760. ASSERT_FALSE(svr.is_running());
  6761. });
  6762. svr.wait_until_ready();
  6763. {
  6764. Client cli(HOST, PORT);
  6765. cli.Post("/test1", "A=B",
  6766. "application/x-www-form-urlencoded\r\nevil: hello1");
  6767. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6768. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6769. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6770. }
  6771. }
  6772. TEST(PathParamsTest, StaticMatch) {
  6773. const auto pattern = "/users/all";
  6774. detail::PathParamsMatcher matcher(pattern);
  6775. Request request;
  6776. request.path = "/users/all";
  6777. ASSERT_TRUE(matcher.match(request));
  6778. std::unordered_map<std::string, std::string> expected_params = {};
  6779. EXPECT_EQ(request.path_params, expected_params);
  6780. }
  6781. TEST(PathParamsTest, StaticMismatch) {
  6782. const auto pattern = "/users/all";
  6783. detail::PathParamsMatcher matcher(pattern);
  6784. Request request;
  6785. request.path = "/users/1";
  6786. ASSERT_FALSE(matcher.match(request));
  6787. }
  6788. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6789. const auto pattern = "/users/:id/subscriptions";
  6790. detail::PathParamsMatcher matcher(pattern);
  6791. Request request;
  6792. request.path = "/users/42/subscriptions";
  6793. ASSERT_TRUE(matcher.match(request));
  6794. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6795. EXPECT_EQ(request.path_params, expected_params);
  6796. }
  6797. TEST(PathParamsTest, SingleParamInTheEnd) {
  6798. const auto pattern = "/users/:id";
  6799. detail::PathParamsMatcher matcher(pattern);
  6800. Request request;
  6801. request.path = "/users/24";
  6802. ASSERT_TRUE(matcher.match(request));
  6803. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6804. EXPECT_EQ(request.path_params, expected_params);
  6805. }
  6806. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6807. const auto pattern = "/users/:id/";
  6808. detail::PathParamsMatcher matcher(pattern);
  6809. Request request;
  6810. request.path = "/users/42/";
  6811. ASSERT_TRUE(matcher.match(request));
  6812. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6813. EXPECT_EQ(request.path_params, expected_params);
  6814. }
  6815. TEST(PathParamsTest, EmptyParam) {
  6816. const auto pattern = "/users/:id/";
  6817. detail::PathParamsMatcher matcher(pattern);
  6818. Request request;
  6819. request.path = "/users//";
  6820. ASSERT_TRUE(matcher.match(request));
  6821. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6822. EXPECT_EQ(request.path_params, expected_params);
  6823. }
  6824. TEST(PathParamsTest, FragmentMismatch) {
  6825. const auto pattern = "/users/:id/";
  6826. detail::PathParamsMatcher matcher(pattern);
  6827. Request request;
  6828. request.path = "/admins/24/";
  6829. ASSERT_FALSE(matcher.match(request));
  6830. }
  6831. TEST(PathParamsTest, ExtraFragments) {
  6832. const auto pattern = "/users/:id";
  6833. detail::PathParamsMatcher matcher(pattern);
  6834. Request request;
  6835. request.path = "/users/42/subscriptions";
  6836. ASSERT_FALSE(matcher.match(request));
  6837. }
  6838. TEST(PathParamsTest, MissingTrailingParam) {
  6839. const auto pattern = "/users/:id";
  6840. detail::PathParamsMatcher matcher(pattern);
  6841. Request request;
  6842. request.path = "/users";
  6843. ASSERT_FALSE(matcher.match(request));
  6844. }
  6845. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6846. const auto pattern = "/users/:id/subscriptions";
  6847. detail::PathParamsMatcher matcher(pattern);
  6848. Request request;
  6849. request.path = "/users/subscriptions";
  6850. ASSERT_FALSE(matcher.match(request));
  6851. }
  6852. TEST(PathParamsTest, MultipleParams) {
  6853. const auto pattern = "/users/:userid/subscriptions/:subid";
  6854. detail::PathParamsMatcher matcher(pattern);
  6855. Request request;
  6856. request.path = "/users/42/subscriptions/2";
  6857. ASSERT_TRUE(matcher.match(request));
  6858. std::unordered_map<std::string, std::string> expected_params = {
  6859. {"userid", "42"}, {"subid", "2"}};
  6860. EXPECT_EQ(request.path_params, expected_params);
  6861. }
  6862. TEST(PathParamsTest, SequenceOfParams) {
  6863. const auto pattern = "/values/:x/:y/:z";
  6864. detail::PathParamsMatcher matcher(pattern);
  6865. Request request;
  6866. request.path = "/values/1/2/3";
  6867. ASSERT_TRUE(matcher.match(request));
  6868. std::unordered_map<std::string, std::string> expected_params = {
  6869. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6870. EXPECT_EQ(request.path_params, expected_params);
  6871. }
  6872. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6873. const auto pattern = "/prefix:suffix";
  6874. detail::PathParamsMatcher matcher(pattern);
  6875. Request request;
  6876. request.path = "/prefix:suffix";
  6877. ASSERT_TRUE(matcher.match(request));
  6878. const std::unordered_map<std::string, std::string> expected_params = {};
  6879. EXPECT_EQ(request.path_params, expected_params);
  6880. }
  6881. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6882. // If ipv6 regex working, regex match codepath is taken.
  6883. // else port will default to 80 in Client impl
  6884. int clientImplMagicPort = 80;
  6885. int port = 4321;
  6886. // above ports must be different to avoid false negative
  6887. EXPECT_NE(clientImplMagicPort, port);
  6888. std::string ipV6TestURL = "http://[ff06::c3]";
  6889. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6890. CLIENT_PRIVATE_KEY_FILE);
  6891. EXPECT_EQ(cli.port(), port);
  6892. }
  6893. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6894. auto file_path = "./www/dir/index.html";
  6895. auto dir_path = "./www/dir";
  6896. detail::FileStat stat_file(file_path);
  6897. EXPECT_TRUE(stat_file.is_file());
  6898. EXPECT_FALSE(stat_file.is_dir());
  6899. detail::FileStat stat_dir(dir_path);
  6900. EXPECT_FALSE(stat_dir.is_file());
  6901. EXPECT_TRUE(stat_dir.is_dir());
  6902. }
  6903. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6904. Server svr;
  6905. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6906. EXPECT_EQ(res.status, 400);
  6907. });
  6908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6909. auto se = detail::scope_exit([&] {
  6910. svr.stop();
  6911. thread.join();
  6912. ASSERT_FALSE(svr.is_running());
  6913. });
  6914. svr.wait_until_ready();
  6915. Client cli(HOST, PORT);
  6916. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6917. }
  6918. TEST(InvalidHeaderCharsTest, is_field_name) {
  6919. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  6920. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  6921. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  6922. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  6923. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  6924. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  6925. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  6926. EXPECT_FALSE(detail::fields::is_field_name(""));
  6927. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  6928. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  6929. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  6930. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  6931. }
  6932. TEST(InvalidHeaderCharsTest, is_field_value) {
  6933. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  6934. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  6935. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  6936. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  6937. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  6938. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  6939. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  6940. EXPECT_TRUE(detail::fields::is_field_value(""));
  6941. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  6942. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  6943. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  6944. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  6945. EXPECT_TRUE(detail::fields::is_field_value("0"));
  6946. }
  6947. TEST(InvalidHeaderCharsTest, OnServer) {
  6948. Server svr;
  6949. svr.Get("/test_name", [&](const Request &req, Response &res) {
  6950. std::string header = "Not Set";
  6951. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6952. res.set_header(header, "value");
  6953. res.set_content("Page Content Page Content", "text/plain");
  6954. });
  6955. svr.Get("/test_value", [&](const Request &req, Response &res) {
  6956. std::string header = "Not Set";
  6957. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6958. res.set_header("X-Test", header);
  6959. res.set_content("Page Content Page Content", "text/plain");
  6960. });
  6961. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6962. auto se = detail::scope_exit([&] {
  6963. svr.stop();
  6964. thread.join();
  6965. ASSERT_FALSE(svr.is_running());
  6966. });
  6967. svr.wait_until_ready();
  6968. Client cli(HOST, PORT);
  6969. {
  6970. auto res = cli.Get(
  6971. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6972. ASSERT_TRUE(res);
  6973. EXPECT_EQ("Page Content Page Content", res->body);
  6974. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6975. }
  6976. {
  6977. auto res = cli.Get(
  6978. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6979. ASSERT_TRUE(res);
  6980. EXPECT_EQ("Page Content Page Content", res->body);
  6981. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6982. }
  6983. }
  6984. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  6985. auto handled = false;
  6986. Server svr;
  6987. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  6988. thread t = thread([&] { svr.listen(HOST, PORT); });
  6989. auto se = detail::scope_exit([&] {
  6990. svr.stop();
  6991. t.join();
  6992. ASSERT_FALSE(svr.is_running());
  6993. ASSERT_FALSE(handled);
  6994. });
  6995. svr.wait_until_ready();
  6996. auto req = "POST /test HTTP/1.1\r\n"
  6997. "Content-Length: x\r\n"
  6998. "\r\n";
  6999. std::string response;
  7000. ASSERT_TRUE(send_request(1, req, &response));
  7001. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7002. response.substr(0, response.find("\r\n")));
  7003. }
  7004. #ifndef _WIN32
  7005. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7006. static constexpr char reject[] = "Unauthorized";
  7007. static constexpr char accept[] = "Upload accepted";
  7008. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7009. Server svr;
  7010. svr.set_expect_100_continue_handler(
  7011. [](const Request & /*req*/, Response &res) {
  7012. res.status = StatusCode::Unauthorized_401;
  7013. res.set_content(reject, "text/plain");
  7014. return res.status;
  7015. });
  7016. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7017. res.set_content(accept, "text/plain");
  7018. });
  7019. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7020. auto se = detail::scope_exit([&] {
  7021. svr.stop();
  7022. thread.join();
  7023. ASSERT_FALSE(svr.is_running());
  7024. });
  7025. svr.wait_until_ready();
  7026. {
  7027. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7028. curl_easy_init(), &curl_easy_cleanup};
  7029. ASSERT_NE(curl, nullptr);
  7030. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7031. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7032. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7033. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7034. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7035. &curl_slist_free_all};
  7036. ASSERT_NE(list, nullptr);
  7037. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7038. struct read_data {
  7039. size_t read_size;
  7040. size_t total_size;
  7041. } data = {0, total_size};
  7042. using read_callback_t =
  7043. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7044. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7045. void *userdata) -> size_t {
  7046. read_data *data = (read_data *)userdata;
  7047. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7048. std::fill_n(ptr, size * nmemb, 'A');
  7049. data->read_size += size * nmemb;
  7050. return size * nmemb;
  7051. };
  7052. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7053. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7054. std::vector<char> buffer;
  7055. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7056. using write_callback_t =
  7057. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7058. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7059. void *userdata) -> size_t {
  7060. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7061. buffer->reserve(buffer->size() + size * nmemb + 1);
  7062. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7063. return size * nmemb;
  7064. };
  7065. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7066. {
  7067. const auto res = curl_easy_perform(curl.get());
  7068. ASSERT_EQ(res, CURLE_OK);
  7069. }
  7070. {
  7071. auto response_code = long{};
  7072. const auto res =
  7073. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7074. ASSERT_EQ(res, CURLE_OK);
  7075. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7076. }
  7077. {
  7078. auto dl = curl_off_t{};
  7079. const auto res =
  7080. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7081. ASSERT_EQ(res, CURLE_OK);
  7082. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7083. }
  7084. {
  7085. buffer.push_back('\0');
  7086. ASSERT_STRCASEEQ(buffer.data(), reject);
  7087. }
  7088. }
  7089. }
  7090. #endif
  7091. template <typename S, typename C>
  7092. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7093. svr.Get("/stream", [&](const Request &, Response &res) {
  7094. auto data = new std::string("01234567890123456789");
  7095. res.set_content_provider(
  7096. data->size(), "text/plain",
  7097. [&, data](size_t offset, size_t length, DataSink &sink) {
  7098. const size_t DATA_CHUNK_SIZE = 4;
  7099. const auto &d = *data;
  7100. std::this_thread::sleep_for(std::chrono::seconds(1));
  7101. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7102. return true;
  7103. },
  7104. [data](bool success) {
  7105. EXPECT_FALSE(success);
  7106. delete data;
  7107. });
  7108. });
  7109. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7110. auto i = new size_t(0);
  7111. res.set_content_provider(
  7112. "text/plain",
  7113. [i](size_t, DataSink &sink) {
  7114. if (*i < 5) {
  7115. std::this_thread::sleep_for(std::chrono::seconds(1));
  7116. sink.write("abcd", 4);
  7117. (*i)++;
  7118. } else {
  7119. sink.done();
  7120. }
  7121. return true;
  7122. },
  7123. [i](bool success) {
  7124. EXPECT_FALSE(success);
  7125. delete i;
  7126. });
  7127. });
  7128. svr.Get("/chunked", [&](const Request &, Response &res) {
  7129. auto i = new size_t(0);
  7130. res.set_chunked_content_provider(
  7131. "text/plain",
  7132. [i](size_t, DataSink &sink) {
  7133. if (*i < 5) {
  7134. std::this_thread::sleep_for(std::chrono::seconds(1));
  7135. sink.os << "abcd";
  7136. (*i)++;
  7137. } else {
  7138. sink.done();
  7139. }
  7140. return true;
  7141. },
  7142. [i](bool success) {
  7143. EXPECT_FALSE(success);
  7144. delete i;
  7145. });
  7146. });
  7147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7148. auto se = detail::scope_exit([&] {
  7149. svr.stop();
  7150. listen_thread.join();
  7151. ASSERT_FALSE(svr.is_running());
  7152. });
  7153. svr.wait_until_ready();
  7154. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7155. {
  7156. auto start = std::chrono::steady_clock::now();
  7157. auto res = cli.Get("/stream");
  7158. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7159. std::chrono::steady_clock::now() - start)
  7160. .count();
  7161. ASSERT_FALSE(res);
  7162. EXPECT_EQ(Error::Read, res.error());
  7163. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7164. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7165. }
  7166. {
  7167. auto start = std::chrono::steady_clock::now();
  7168. auto res = cli.Get("/stream_without_length");
  7169. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7170. std::chrono::steady_clock::now() - start)
  7171. .count();
  7172. ASSERT_FALSE(res);
  7173. EXPECT_EQ(Error::Read, res.error());
  7174. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7175. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7176. }
  7177. {
  7178. auto start = std::chrono::steady_clock::now();
  7179. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  7180. EXPECT_EQ("abcd", string(data, data_length));
  7181. return true;
  7182. });
  7183. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7184. std::chrono::steady_clock::now() - start)
  7185. .count();
  7186. ASSERT_FALSE(res);
  7187. EXPECT_EQ(Error::Read, res.error());
  7188. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7189. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7190. }
  7191. }
  7192. TEST(MaxTimeoutTest, ContentStream) {
  7193. time_t timeout = 2000;
  7194. time_t threshold = 200;
  7195. Server svr;
  7196. Client cli("localhost", PORT);
  7197. max_timeout_test(svr, cli, timeout, threshold);
  7198. }
  7199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7200. TEST(MaxTimeoutTest, ContentStreamSSL) {
  7201. time_t timeout = 2000;
  7202. time_t threshold = 500; // SSL_shutdown is slow on some operating systems.
  7203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7204. SSLClient cli("localhost", PORT);
  7205. cli.enable_server_certificate_verification(false);
  7206. max_timeout_test(svr, cli, timeout, threshold);
  7207. }
  7208. #endif
  7209. class EventDispatcher {
  7210. public:
  7211. EventDispatcher() {}
  7212. void wait_event(DataSink *sink) {
  7213. unique_lock<mutex> lk(m_);
  7214. int id = id_;
  7215. cv_.wait(lk, [&] { return cid_ == id; });
  7216. sink->write(message_.data(), message_.size());
  7217. }
  7218. void send_event(const string &message) {
  7219. lock_guard<mutex> lk(m_);
  7220. cid_ = id_++;
  7221. message_ = message;
  7222. cv_.notify_all();
  7223. }
  7224. private:
  7225. mutex m_;
  7226. condition_variable cv_;
  7227. atomic_int id_{0};
  7228. atomic_int cid_{-1};
  7229. string message_;
  7230. };
  7231. TEST(ClientInThreadTest, Issue2068) {
  7232. EventDispatcher ed;
  7233. Server svr;
  7234. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  7235. res.set_chunked_content_provider("text/event-stream",
  7236. [&](size_t /*offset*/, DataSink &sink) {
  7237. ed.wait_event(&sink);
  7238. return true;
  7239. });
  7240. });
  7241. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7242. svr.wait_until_ready();
  7243. thread event_thread([&] {
  7244. int id = 0;
  7245. while (svr.is_running()) {
  7246. this_thread::sleep_for(chrono::milliseconds(500));
  7247. std::stringstream ss;
  7248. ss << "data: " << id << "\n\n";
  7249. ed.send_event(ss.str());
  7250. id++;
  7251. }
  7252. });
  7253. auto se = detail::scope_exit([&] {
  7254. svr.stop();
  7255. listen_thread.join();
  7256. event_thread.join();
  7257. ASSERT_FALSE(svr.is_running());
  7258. });
  7259. {
  7260. auto client = detail::make_unique<Client>(HOST, PORT);
  7261. client->set_read_timeout(std::chrono::minutes(10));
  7262. std::atomic<bool> stop{false};
  7263. std::thread t([&] {
  7264. client->Get("/event1",
  7265. [&](const char *, size_t) -> bool { return !stop; });
  7266. });
  7267. std::this_thread::sleep_for(std::chrono::seconds(2));
  7268. stop = true;
  7269. client->stop();
  7270. client.reset();
  7271. t.join();
  7272. }
  7273. }