test.cc 263 KB

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