test.cc 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid multipart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  136. string content_type = "multipart/form-data; boundary=something";
  137. string boundary;
  138. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  139. EXPECT_TRUE(ret);
  140. EXPECT_EQ(boundary, "something");
  141. }
  142. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  143. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  144. string boundary;
  145. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  148. }
  149. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  150. string content_type =
  151. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  152. string boundary;
  153. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  154. EXPECT_TRUE(ret);
  155. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  156. }
  157. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  158. string content_type =
  159. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  160. string boundary;
  161. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  162. EXPECT_TRUE(ret);
  163. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  164. }
  165. TEST(GetHeaderValueTest, DefaultValue) {
  166. Headers headers = {{"Dummy", "Dummy"}};
  167. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  168. EXPECT_STREQ("text/plain", val);
  169. }
  170. TEST(GetHeaderValueTest, DefaultValueInt) {
  171. Headers headers = {{"Dummy", "Dummy"}};
  172. auto val =
  173. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  174. EXPECT_EQ(100ull, val);
  175. }
  176. TEST(GetHeaderValueTest, RegularValue) {
  177. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  178. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  179. EXPECT_STREQ("text/html", val);
  180. }
  181. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  182. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  183. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  184. EXPECT_STREQ("text/html", val);
  185. }
  186. TEST(GetHeaderValueTest, SetContent) {
  187. Response res;
  188. res.set_content("html", "text/html");
  189. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  190. res.set_content("text", "text/plain");
  191. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  192. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  193. }
  194. TEST(GetHeaderValueTest, RegularValueInt) {
  195. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  196. auto val =
  197. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  198. EXPECT_EQ(100ull, val);
  199. }
  200. TEST(GetHeaderValueTest, Range) {
  201. {
  202. Headers headers = {make_range_header({{1, -1}})};
  203. auto val = detail::get_header_value(headers, "Range", 0, 0);
  204. EXPECT_STREQ("bytes=1-", val);
  205. }
  206. {
  207. Headers headers = {make_range_header({{-1, 1}})};
  208. auto val = detail::get_header_value(headers, "Range", 0, 0);
  209. EXPECT_STREQ("bytes=-1", val);
  210. }
  211. {
  212. Headers headers = {make_range_header({{1, 10}})};
  213. auto val = detail::get_header_value(headers, "Range", 0, 0);
  214. EXPECT_STREQ("bytes=1-10", val);
  215. }
  216. {
  217. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  218. auto val = detail::get_header_value(headers, "Range", 0, 0);
  219. EXPECT_STREQ("bytes=1-10, 100-", val);
  220. }
  221. {
  222. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  223. auto val = detail::get_header_value(headers, "Range", 0, 0);
  224. EXPECT_STREQ("bytes=1-10, 100-200", val);
  225. }
  226. {
  227. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  228. auto val = detail::get_header_value(headers, "Range", 0, 0);
  229. EXPECT_STREQ("bytes=0-0, -1", val);
  230. }
  231. }
  232. TEST(ParseHeaderValueTest, Range) {
  233. {
  234. Ranges ranges;
  235. auto ret = detail::parse_range_header("bytes=1-", ranges);
  236. EXPECT_TRUE(ret);
  237. EXPECT_EQ(1u, ranges.size());
  238. EXPECT_EQ(1u, ranges[0].first);
  239. EXPECT_EQ(-1, ranges[0].second);
  240. }
  241. {
  242. Ranges ranges;
  243. auto ret = detail::parse_range_header("bytes=-1", ranges);
  244. EXPECT_TRUE(ret);
  245. EXPECT_EQ(1u, ranges.size());
  246. EXPECT_EQ(-1, ranges[0].first);
  247. EXPECT_EQ(1u, ranges[0].second);
  248. }
  249. {
  250. Ranges ranges;
  251. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  252. EXPECT_TRUE(ret);
  253. EXPECT_EQ(1u, ranges.size());
  254. EXPECT_EQ(1u, ranges[0].first);
  255. EXPECT_EQ(10u, ranges[0].second);
  256. }
  257. {
  258. Ranges ranges;
  259. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  260. EXPECT_FALSE(ret);
  261. }
  262. {
  263. Ranges ranges;
  264. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  265. EXPECT_TRUE(ret);
  266. EXPECT_EQ(2u, ranges.size());
  267. EXPECT_EQ(1u, ranges[0].first);
  268. EXPECT_EQ(10u, ranges[0].second);
  269. EXPECT_EQ(100u, ranges[1].first);
  270. EXPECT_EQ(-1, ranges[1].second);
  271. }
  272. {
  273. Ranges ranges;
  274. auto ret =
  275. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  276. EXPECT_TRUE(ret);
  277. EXPECT_EQ(3u, ranges.size());
  278. EXPECT_EQ(1u, ranges[0].first);
  279. EXPECT_EQ(10u, ranges[0].second);
  280. EXPECT_EQ(100u, ranges[1].first);
  281. EXPECT_EQ(200u, ranges[1].second);
  282. EXPECT_EQ(300u, ranges[2].first);
  283. EXPECT_EQ(400u, ranges[2].second);
  284. }
  285. }
  286. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  287. Request req;
  288. req.set_header("Accept-Encoding", "gzip");
  289. Response res;
  290. res.set_header("Content-Type", "text/plain");
  291. auto ret = detail::encoding_type(req, res);
  292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  293. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  294. #else
  295. EXPECT_TRUE(ret == detail::EncodingType::None);
  296. #endif
  297. }
  298. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  299. Request req;
  300. req.set_header("Accept-Encoding", "gzip, deflate, br");
  301. Response res;
  302. res.set_header("Content-Type", "text/plain");
  303. auto ret = detail::encoding_type(req, res);
  304. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  305. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  306. #elif CPPHTTPLIB_ZLIB_SUPPORT
  307. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  308. #else
  309. EXPECT_TRUE(ret == detail::EncodingType::None);
  310. #endif
  311. }
  312. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  313. Request req;
  314. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  315. Response res;
  316. res.set_header("Content-Type", "text/plain");
  317. auto ret = detail::encoding_type(req, res);
  318. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  319. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  320. #elif CPPHTTPLIB_ZLIB_SUPPORT
  321. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  322. #else
  323. EXPECT_TRUE(ret == detail::EncodingType::None);
  324. #endif
  325. }
  326. TEST(BufferStreamTest, read) {
  327. detail::BufferStream strm1;
  328. Stream &strm = strm1;
  329. EXPECT_EQ(5, strm.write("hello"));
  330. char buf[512];
  331. EXPECT_EQ(2, strm.read(buf, 2));
  332. EXPECT_EQ('h', buf[0]);
  333. EXPECT_EQ('e', buf[1]);
  334. EXPECT_EQ(2, strm.read(buf, 2));
  335. EXPECT_EQ('l', buf[0]);
  336. EXPECT_EQ('l', buf[1]);
  337. EXPECT_EQ(1, strm.read(buf, 1));
  338. EXPECT_EQ('o', buf[0]);
  339. EXPECT_EQ(0, strm.read(buf, 1));
  340. }
  341. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  342. auto host = "www.httpwatch.com";
  343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  344. auto port = 443;
  345. SSLClient cli(host, port);
  346. #else
  347. auto port = 80;
  348. Client cli(host, port);
  349. #endif
  350. cli.set_connection_timeout(2);
  351. auto res =
  352. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  353. ASSERT_TRUE(res);
  354. std::string out;
  355. detail::read_file("./image.jpg", out);
  356. EXPECT_EQ(200, res->status);
  357. EXPECT_EQ(out, res->body);
  358. }
  359. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  360. auto host = "www.httpwatch.com";
  361. auto ip = hosted_at(host);
  362. EXPECT_EQ("191.236.16.12", ip);
  363. std::vector<std::string> addrs;
  364. hosted_at(host, addrs);
  365. EXPECT_EQ(1u, addrs.size());
  366. }
  367. #if 0 // It depends on each test environment...
  368. TEST(HostnameToIPConversionTest, YouTube_Online) {
  369. auto host = "www.youtube.com";
  370. std::vector<std::string> addrs;
  371. hosted_at(host, addrs);
  372. EXPECT_EQ(20u, addrs.size());
  373. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  374. EXPECT_TRUE(it != addrs.end());
  375. }
  376. #endif
  377. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  378. auto host = "www.httpwatch.com";
  379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  380. auto port = 443;
  381. SSLClient cli(host, port);
  382. #else
  383. auto port = 80;
  384. Client cli(host, port);
  385. #endif
  386. cli.set_connection_timeout(2);
  387. std::string body;
  388. auto res =
  389. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  390. [&](const char *data, size_t data_length) {
  391. body.append(data, data_length);
  392. return true;
  393. });
  394. ASSERT_TRUE(res);
  395. std::string out;
  396. detail::read_file("./image.jpg", out);
  397. EXPECT_EQ(200, res->status);
  398. EXPECT_EQ(out, body);
  399. }
  400. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  401. auto host = "www.httpwatch.com";
  402. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  403. auto port = 443;
  404. SSLClient cli(host, port);
  405. #else
  406. auto port = 80;
  407. Client cli(host, port);
  408. #endif
  409. cli.set_connection_timeout(2);
  410. std::string body;
  411. auto res = cli.Get(
  412. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  413. [&](const Response &response) {
  414. EXPECT_EQ(200, response.status);
  415. return true;
  416. },
  417. [&](const char *data, size_t data_length) {
  418. body.append(data, data_length);
  419. return true;
  420. });
  421. ASSERT_TRUE(res);
  422. std::string out;
  423. detail::read_file("./image.jpg", out);
  424. EXPECT_EQ(200, res->status);
  425. EXPECT_EQ(out, body);
  426. }
  427. TEST(RangeTest, FromHTTPBin_Online) {
  428. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  429. auto host = "httpbin.org";
  430. auto path = std::string{"/range/32"};
  431. #else
  432. auto host = "nghttp2.org";
  433. auto path = std::string{"/httpbin/range/32"};
  434. #endif
  435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  436. auto port = 443;
  437. SSLClient cli(host, port);
  438. #else
  439. auto port = 80;
  440. Client cli(host, port);
  441. #endif
  442. cli.set_connection_timeout(5);
  443. {
  444. auto res = cli.Get(path);
  445. ASSERT_TRUE(res);
  446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  447. EXPECT_EQ(200, res->status);
  448. }
  449. {
  450. Headers headers = {make_range_header({{1, -1}})};
  451. auto res = cli.Get(path, headers);
  452. ASSERT_TRUE(res);
  453. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  454. EXPECT_EQ(206, res->status);
  455. }
  456. {
  457. Headers headers = {make_range_header({{1, 10}})};
  458. auto res = cli.Get(path, headers);
  459. ASSERT_TRUE(res);
  460. EXPECT_EQ("bcdefghijk", res->body);
  461. EXPECT_EQ(206, res->status);
  462. }
  463. {
  464. Headers headers = {make_range_header({{0, 31}})};
  465. auto res = cli.Get(path, headers);
  466. ASSERT_TRUE(res);
  467. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  468. EXPECT_EQ(200, res->status);
  469. }
  470. {
  471. Headers headers = {make_range_header({{0, -1}})};
  472. auto res = cli.Get(path, headers);
  473. ASSERT_TRUE(res);
  474. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  475. EXPECT_EQ(200, res->status);
  476. }
  477. {
  478. Headers headers = {make_range_header({{0, 32}})};
  479. auto res = cli.Get(path, headers);
  480. ASSERT_TRUE(res);
  481. EXPECT_EQ(416, res->status);
  482. }
  483. }
  484. TEST(ConnectionErrorTest, InvalidHost) {
  485. auto host = "-abcde.com";
  486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  487. auto port = 443;
  488. SSLClient cli(host, port);
  489. #else
  490. auto port = 80;
  491. Client cli(host, port);
  492. #endif
  493. cli.set_connection_timeout(std::chrono::seconds(2));
  494. auto res = cli.Get("/");
  495. ASSERT_TRUE(!res);
  496. EXPECT_EQ(Error::Connection, res.error());
  497. }
  498. TEST(ConnectionErrorTest, InvalidHost2) {
  499. auto host = "httpbin.org/";
  500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  501. SSLClient cli(host);
  502. #else
  503. Client cli(host);
  504. #endif
  505. cli.set_connection_timeout(std::chrono::seconds(2));
  506. auto res = cli.Get("/");
  507. ASSERT_TRUE(!res);
  508. EXPECT_EQ(Error::Connection, res.error());
  509. }
  510. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  511. auto host = "httpbin.org/";
  512. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  513. SSLClient cli(host);
  514. #else
  515. Client cli(host);
  516. #endif
  517. cli.set_connection_timeout(std::chrono::seconds(2));
  518. auto res = cli.Get("/");
  519. ASSERT_TRUE(!res);
  520. stringstream s;
  521. s << "error code: " << res.error();
  522. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  523. }
  524. TEST(ConnectionErrorTest, InvalidPort) {
  525. auto host = "localhost";
  526. auto port = 44380;
  527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  528. SSLClient cli(host, port);
  529. #else
  530. Client cli(host, port);
  531. #endif
  532. cli.set_connection_timeout(std::chrono::seconds(2));
  533. auto res = cli.Get("/");
  534. ASSERT_TRUE(!res);
  535. EXPECT_TRUE(Error::Connection == res.error() ||
  536. Error::ConnectionTimeout == res.error());
  537. }
  538. TEST(ConnectionErrorTest, Timeout_Online) {
  539. auto host = "google.com";
  540. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  541. auto port = 44380;
  542. SSLClient cli(host, port);
  543. #else
  544. auto port = 8080;
  545. Client cli(host, port);
  546. #endif
  547. cli.set_connection_timeout(std::chrono::seconds(2));
  548. // only probe one address type so that the error reason
  549. // correlates to the timed-out IPv4, not the unsupported
  550. // IPv6 connection attempt
  551. cli.set_address_family(AF_INET);
  552. auto res = cli.Get("/");
  553. ASSERT_TRUE(!res);
  554. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  555. }
  556. TEST(CancelTest, NoCancel_Online) {
  557. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  558. auto host = "httpbin.org";
  559. auto path = std::string{"/range/32"};
  560. #else
  561. auto host = "nghttp2.org";
  562. auto path = std::string{"/httpbin/range/32"};
  563. #endif
  564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  565. auto port = 443;
  566. SSLClient cli(host, port);
  567. #else
  568. auto port = 80;
  569. Client cli(host, port);
  570. #endif
  571. cli.set_connection_timeout(std::chrono::seconds(5));
  572. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  573. ASSERT_TRUE(res);
  574. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  575. EXPECT_EQ(200, res->status);
  576. }
  577. TEST(CancelTest, WithCancelSmallPayload_Online) {
  578. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  579. auto host = "httpbin.org";
  580. auto path = std::string{"/range/32"};
  581. #else
  582. auto host = "nghttp2.org";
  583. auto path = std::string{"/httpbin/range/32"};
  584. #endif
  585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  586. auto port = 443;
  587. SSLClient cli(host, port);
  588. #else
  589. auto port = 80;
  590. Client cli(host, port);
  591. #endif
  592. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  593. cli.set_connection_timeout(std::chrono::seconds(5));
  594. ASSERT_TRUE(!res);
  595. EXPECT_EQ(Error::Canceled, res.error());
  596. }
  597. TEST(CancelTest, WithCancelLargePayload_Online) {
  598. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  599. auto host = "httpbin.org";
  600. auto path = std::string{"/range/65536"};
  601. #else
  602. auto host = "nghttp2.org";
  603. auto path = std::string{"/httpbin/range/65536"};
  604. #endif
  605. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  606. auto port = 443;
  607. SSLClient cli(host, port);
  608. #else
  609. auto port = 80;
  610. Client cli(host, port);
  611. #endif
  612. cli.set_connection_timeout(std::chrono::seconds(5));
  613. uint32_t count = 0;
  614. auto res =
  615. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  616. ASSERT_TRUE(!res);
  617. EXPECT_EQ(Error::Canceled, res.error());
  618. }
  619. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  620. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  621. auto host = "httpbin.org";
  622. auto path = std::string{"/basic-auth/hello/world"};
  623. #else
  624. auto host = "nghttp2.org";
  625. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  626. #endif
  627. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  628. auto port = 443;
  629. SSLClient cli(host, port);
  630. #else
  631. auto port = 80;
  632. Client cli(host, port);
  633. #endif
  634. {
  635. auto res = cli.Get(path);
  636. ASSERT_TRUE(res);
  637. EXPECT_EQ(401, res->status);
  638. }
  639. {
  640. auto res =
  641. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  642. ASSERT_TRUE(res);
  643. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  644. res->body);
  645. EXPECT_EQ(200, res->status);
  646. }
  647. {
  648. cli.set_basic_auth("hello", "world");
  649. auto res = cli.Get(path);
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  652. res->body);
  653. EXPECT_EQ(200, res->status);
  654. }
  655. {
  656. cli.set_basic_auth("hello", "bad");
  657. auto res = cli.Get(path);
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ(401, res->status);
  660. }
  661. {
  662. cli.set_basic_auth("bad", "world");
  663. auto res = cli.Get(path);
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(401, res->status);
  666. }
  667. }
  668. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  669. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  670. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  671. auto host = "httpbin.org";
  672. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  673. auto paths = std::vector<std::string>{
  674. "/digest-auth/auth/hello/world/MD5",
  675. "/digest-auth/auth/hello/world/SHA-256",
  676. "/digest-auth/auth/hello/world/SHA-512",
  677. "/digest-auth/auth-int/hello/world/MD5",
  678. };
  679. #else
  680. auto host = "nghttp2.org";
  681. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  682. auto paths = std::vector<std::string>{
  683. "/httpbin/digest-auth/auth/hello/world/MD5",
  684. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  685. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  686. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  687. };
  688. #endif
  689. auto port = 443;
  690. SSLClient cli(host, port);
  691. {
  692. auto res = cli.Get(unauth_path);
  693. ASSERT_TRUE(res);
  694. EXPECT_EQ(401, res->status);
  695. }
  696. {
  697. cli.set_digest_auth("hello", "world");
  698. for (const auto &path : paths) {
  699. auto res = cli.Get(path.c_str());
  700. ASSERT_TRUE(res);
  701. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  702. res->body);
  703. EXPECT_EQ(200, res->status);
  704. }
  705. cli.set_digest_auth("hello", "bad");
  706. for (const auto &path : paths) {
  707. auto res = cli.Get(path.c_str());
  708. ASSERT_TRUE(res);
  709. EXPECT_EQ(401, res->status);
  710. }
  711. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  712. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  713. // cli.set_digest_auth("bad", "world");
  714. // for (const auto& path : paths) {
  715. // auto res = cli.Get(path.c_str());
  716. // ASSERT_TRUE(res);
  717. // EXPECT_EQ(400, res->status);
  718. // }
  719. }
  720. }
  721. #endif
  722. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  723. auto host = "google.com";
  724. auto another_host = "example.com";
  725. auto wrong_ip = "0.0.0.0";
  726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  727. SSLClient cli(host);
  728. #else
  729. Client cli(host);
  730. #endif
  731. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  732. auto res = cli.Get("/");
  733. ASSERT_TRUE(res);
  734. ASSERT_EQ(301, res->status);
  735. }
  736. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  737. auto host = "google.com";
  738. auto wrong_ip = "0.0.0.0";
  739. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  740. SSLClient cli(host);
  741. #else
  742. Client cli(host);
  743. #endif
  744. cli.set_hostname_addr_map({{host, wrong_ip}});
  745. auto res = cli.Get("/");
  746. ASSERT_TRUE(!res);
  747. EXPECT_EQ(Error::Connection, res.error());
  748. }
  749. TEST(AbsoluteRedirectTest, Redirect_Online) {
  750. auto host = "nghttp2.org";
  751. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  752. SSLClient cli(host);
  753. #else
  754. Client cli(host);
  755. #endif
  756. cli.set_follow_location(true);
  757. auto res = cli.Get("/httpbin/absolute-redirect/3");
  758. ASSERT_TRUE(res);
  759. EXPECT_EQ(200, res->status);
  760. }
  761. TEST(RedirectTest, Redirect_Online) {
  762. auto host = "nghttp2.org";
  763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  764. SSLClient cli(host);
  765. #else
  766. Client cli(host);
  767. #endif
  768. cli.set_follow_location(true);
  769. auto res = cli.Get("/httpbin/redirect/3");
  770. ASSERT_TRUE(res);
  771. EXPECT_EQ(200, res->status);
  772. }
  773. TEST(RelativeRedirectTest, Redirect_Online) {
  774. auto host = "nghttp2.org";
  775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  776. SSLClient cli(host);
  777. #else
  778. Client cli(host);
  779. #endif
  780. cli.set_follow_location(true);
  781. auto res = cli.Get("/httpbin/relative-redirect/3");
  782. ASSERT_TRUE(res);
  783. EXPECT_EQ(200, res->status);
  784. }
  785. TEST(TooManyRedirectTest, Redirect_Online) {
  786. auto host = "nghttp2.org";
  787. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  788. SSLClient cli(host);
  789. #else
  790. Client cli(host);
  791. #endif
  792. cli.set_follow_location(true);
  793. auto res = cli.Get("/httpbin/redirect/21");
  794. ASSERT_TRUE(!res);
  795. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  796. }
  797. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  798. TEST(YahooRedirectTest, Redirect_Online) {
  799. Client cli("yahoo.com");
  800. auto res = cli.Get("/");
  801. ASSERT_TRUE(res);
  802. EXPECT_EQ(301, res->status);
  803. cli.set_follow_location(true);
  804. res = cli.Get("/");
  805. ASSERT_TRUE(res);
  806. EXPECT_EQ(200, res->status);
  807. EXPECT_EQ("https://www.yahoo.com/", res->location);
  808. }
  809. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  810. SSLClient cli("nghttp2.org");
  811. cli.set_follow_location(true);
  812. auto res = cli.Get(
  813. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  814. ASSERT_TRUE(res);
  815. EXPECT_EQ(200, res->status);
  816. }
  817. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  818. SSLClient cli("nghttp2.org");
  819. cli.set_follow_location(true);
  820. Params params;
  821. params.emplace("url", "http://www.google.com");
  822. params.emplace("status_code", "302");
  823. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  824. ASSERT_TRUE(res);
  825. EXPECT_EQ(200, res->status);
  826. }
  827. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  828. SSLClient cli("nghttp2.org");
  829. cli.set_follow_location(true);
  830. Params params;
  831. params.emplace("url", "http://www.google.com");
  832. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  833. ASSERT_TRUE(res);
  834. EXPECT_EQ(200, res->status);
  835. }
  836. TEST(UrlWithSpace, Redirect_Online) {
  837. SSLClient cli("edge.forgecdn.net");
  838. cli.set_follow_location(true);
  839. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  840. ASSERT_TRUE(res);
  841. EXPECT_EQ(200, res->status);
  842. EXPECT_EQ(18527U, res->get_header_value<uint64_t>("Content-Length"));
  843. }
  844. #endif
  845. #if !defined(_WIN32) && !defined(_WIN64)
  846. TEST(ReceiveSignals, Signal) {
  847. auto setupSignalHandlers = []() {
  848. struct sigaction act;
  849. sigemptyset(&act.sa_mask);
  850. act.sa_flags = SA_SIGINFO;
  851. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  852. switch (sig) {
  853. case SIGINT:
  854. default: break;
  855. }
  856. };
  857. ::sigaction(SIGINT, &act, nullptr);
  858. };
  859. Server svr;
  860. int port = 0;
  861. auto thread = std::thread([&]() {
  862. setupSignalHandlers();
  863. port = svr.bind_to_any_port("localhost");
  864. svr.listen_after_bind();
  865. });
  866. auto se = detail::scope_exit([&] {
  867. svr.stop();
  868. thread.join();
  869. ASSERT_FALSE(svr.is_running());
  870. });
  871. svr.wait_until_ready();
  872. ASSERT_TRUE(svr.is_running());
  873. pthread_kill(thread.native_handle(), SIGINT);
  874. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  875. ASSERT_TRUE(svr.is_running());
  876. }
  877. #endif
  878. TEST(RedirectToDifferentPort, Redirect) {
  879. Server svr1;
  880. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  881. res.set_content("Hello World!", "text/plain");
  882. });
  883. int svr1_port = 0;
  884. auto thread1 = std::thread([&]() {
  885. svr1_port = svr1.bind_to_any_port("localhost");
  886. svr1.listen_after_bind();
  887. });
  888. Server svr2;
  889. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  890. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  891. });
  892. int svr2_port = 0;
  893. auto thread2 = std::thread([&]() {
  894. svr2_port = svr2.bind_to_any_port("localhost");
  895. svr2.listen_after_bind();
  896. });
  897. auto se = detail::scope_exit([&] {
  898. svr2.stop();
  899. thread2.join();
  900. svr1.stop();
  901. thread1.join();
  902. ASSERT_FALSE(svr2.is_running());
  903. ASSERT_FALSE(svr1.is_running());
  904. });
  905. while (!svr1.is_running() || !svr2.is_running()) {
  906. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  907. }
  908. // Give GET time to get a few messages.
  909. std::this_thread::sleep_for(std::chrono::seconds(1));
  910. Client cli("localhost", svr2_port);
  911. cli.set_follow_location(true);
  912. auto res = cli.Get("/2");
  913. ASSERT_TRUE(res);
  914. EXPECT_EQ(200, res->status);
  915. EXPECT_EQ("Hello World!", res->body);
  916. }
  917. TEST(RedirectFromPageWithContent, Redirect) {
  918. Server svr;
  919. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  920. res.set_content("___", "text/plain");
  921. res.set_redirect("/2");
  922. });
  923. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  924. res.set_content("Hello World!", "text/plain");
  925. });
  926. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  927. auto se = detail::scope_exit([&] {
  928. svr.stop();
  929. th.join();
  930. ASSERT_FALSE(svr.is_running());
  931. });
  932. svr.wait_until_ready();
  933. // Give GET time to get a few messages.
  934. std::this_thread::sleep_for(std::chrono::seconds(1));
  935. {
  936. Client cli("localhost", PORT);
  937. cli.set_follow_location(true);
  938. std::string body;
  939. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  940. body.append(data, data_length);
  941. return true;
  942. });
  943. ASSERT_TRUE(res);
  944. EXPECT_EQ(200, res->status);
  945. EXPECT_EQ("Hello World!", body);
  946. }
  947. {
  948. Client cli("localhost", PORT);
  949. std::string body;
  950. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  951. body.append(data, data_length);
  952. return true;
  953. });
  954. ASSERT_TRUE(res);
  955. EXPECT_EQ(302, res->status);
  956. EXPECT_EQ("___", body);
  957. }
  958. }
  959. TEST(RedirectFromPageWithContentIP6, Redirect) {
  960. Server svr;
  961. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  962. res.set_content("___", "text/plain");
  963. // res.set_redirect("/2");
  964. res.set_redirect("http://[::1]:1234/2");
  965. });
  966. svr.Get("/2", [&](const Request &req, Response &res) {
  967. auto host_header = req.headers.find("Host");
  968. ASSERT_TRUE(host_header != req.headers.end());
  969. EXPECT_EQ("[::1]:1234", host_header->second);
  970. res.set_content("Hello World!", "text/plain");
  971. });
  972. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  973. auto se = detail::scope_exit([&] {
  974. svr.stop();
  975. th.join();
  976. ASSERT_FALSE(svr.is_running());
  977. });
  978. // When IPV6 support isn't available svr.listen("::1", 1234) never
  979. // actually starts anything, so the condition !svr.is_running() will
  980. // always remain true, and the loop never stops.
  981. // This basically counts how many milliseconds have passed since the
  982. // call to svr.listen(), and if after 5 seconds nothing started yet
  983. // aborts the test.
  984. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  985. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  986. ASSERT_LT(milliseconds, 5000U);
  987. }
  988. // Give GET time to get a few messages.
  989. std::this_thread::sleep_for(std::chrono::seconds(1));
  990. {
  991. Client cli("http://[::1]:1234");
  992. cli.set_follow_location(true);
  993. std::string body;
  994. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  995. body.append(data, data_length);
  996. return true;
  997. });
  998. ASSERT_TRUE(res);
  999. EXPECT_EQ(200, res->status);
  1000. EXPECT_EQ("Hello World!", body);
  1001. }
  1002. {
  1003. Client cli("http://[::1]:1234");
  1004. std::string body;
  1005. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1006. body.append(data, data_length);
  1007. return true;
  1008. });
  1009. ASSERT_TRUE(res);
  1010. EXPECT_EQ(302, res->status);
  1011. EXPECT_EQ("___", body);
  1012. }
  1013. }
  1014. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1015. Server svr;
  1016. svr.Get("/foo", [](const Request &req, Response &res) {
  1017. auto a = req.params.find("a");
  1018. if (a != req.params.end()) {
  1019. res.set_content((*a).second, "text/plain");
  1020. res.status = 200;
  1021. } else {
  1022. res.status = 400;
  1023. }
  1024. });
  1025. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1026. auto se = detail::scope_exit([&] {
  1027. svr.stop();
  1028. thread.join();
  1029. ASSERT_FALSE(svr.is_running());
  1030. });
  1031. // Give GET time to get a few messages.
  1032. std::this_thread::sleep_for(std::chrono::seconds(1));
  1033. {
  1034. Client cli(HOST, PORT);
  1035. cli.set_url_encode(false);
  1036. auto res = cli.Get("/foo?a=explicitly+encoded");
  1037. ASSERT_TRUE(res);
  1038. EXPECT_EQ(200, res->status);
  1039. // This expects it back with a space, as the `+` won't have been
  1040. // url-encoded, and server-side the params get decoded turning `+`
  1041. // into spaces.
  1042. EXPECT_EQ("explicitly encoded", res->body);
  1043. }
  1044. }
  1045. TEST(BindServerTest, DISABLED_BindDualStack) {
  1046. Server svr;
  1047. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1048. res.set_content("Hello World!", "text/plain");
  1049. });
  1050. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1051. auto se = detail::scope_exit([&] {
  1052. svr.stop();
  1053. thread.join();
  1054. ASSERT_FALSE(svr.is_running());
  1055. });
  1056. // Give GET time to get a few messages.
  1057. std::this_thread::sleep_for(std::chrono::seconds(1));
  1058. {
  1059. Client cli("127.0.0.1", PORT);
  1060. auto res = cli.Get("/1");
  1061. ASSERT_TRUE(res);
  1062. EXPECT_EQ(200, res->status);
  1063. EXPECT_EQ("Hello World!", res->body);
  1064. }
  1065. {
  1066. Client cli("::1", PORT);
  1067. auto res = cli.Get("/1");
  1068. ASSERT_TRUE(res);
  1069. EXPECT_EQ(200, res->status);
  1070. EXPECT_EQ("Hello World!", res->body);
  1071. }
  1072. }
  1073. TEST(BindServerTest, BindAndListenSeparately) {
  1074. Server svr;
  1075. int port = svr.bind_to_any_port("0.0.0.0");
  1076. ASSERT_TRUE(svr.is_valid());
  1077. ASSERT_TRUE(port > 0);
  1078. svr.stop();
  1079. }
  1080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1081. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1083. CLIENT_CA_CERT_DIR);
  1084. int port = svr.bind_to_any_port("0.0.0.0");
  1085. ASSERT_TRUE(svr.is_valid());
  1086. ASSERT_TRUE(port > 0);
  1087. svr.stop();
  1088. }
  1089. #endif
  1090. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1091. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1092. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1093. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1094. int port = svr.bind_to_any_port("0.0.0.0");
  1095. ASSERT_TRUE(svr.is_valid());
  1096. ASSERT_TRUE(port > 0);
  1097. svr.stop();
  1098. }
  1099. #endif
  1100. TEST(ErrorHandlerTest, ContentLength) {
  1101. Server svr;
  1102. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1103. res.status = 200;
  1104. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1105. "text/html"); // <= Content-Length still 13
  1106. });
  1107. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1108. res.set_content("Hello World!\n", "text/plain");
  1109. res.status = 524;
  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. // Give GET time to get a few messages.
  1118. std::this_thread::sleep_for(std::chrono::seconds(1));
  1119. {
  1120. Client cli(HOST, PORT);
  1121. auto res = cli.Get("/hi");
  1122. ASSERT_TRUE(res);
  1123. EXPECT_EQ(200, res->status);
  1124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1127. }
  1128. }
  1129. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1130. TEST(ExceptionHandlerTest, ContentLength) {
  1131. Server svr;
  1132. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1133. std::exception_ptr ep) {
  1134. EXPECT_FALSE(ep == nullptr);
  1135. try {
  1136. std::rethrow_exception(ep);
  1137. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1138. res.status = 500;
  1139. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1140. "text/html"); // <= Content-Length still 13 at this point
  1141. });
  1142. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1143. res.set_content("Hello World!\n", "text/plain");
  1144. throw std::runtime_error("abc");
  1145. });
  1146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1147. auto se = detail::scope_exit([&] {
  1148. svr.stop();
  1149. thread.join();
  1150. ASSERT_FALSE(svr.is_running());
  1151. });
  1152. // Give GET time to get a few messages.
  1153. std::this_thread::sleep_for(std::chrono::seconds(1));
  1154. for (size_t i = 0; i < 10; i++) {
  1155. Client cli(HOST, PORT);
  1156. for (size_t j = 0; j < 100; j++) {
  1157. auto res = cli.Get("/hi");
  1158. ASSERT_TRUE(res);
  1159. EXPECT_EQ(500, res->status);
  1160. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1161. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1162. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1163. }
  1164. cli.set_keep_alive(true);
  1165. for (size_t j = 0; j < 100; j++) {
  1166. auto res = cli.Get("/hi");
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ(500, res->status);
  1169. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1170. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1171. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1172. }
  1173. }
  1174. }
  1175. #endif
  1176. TEST(NoContentTest, ContentLength) {
  1177. Server svr;
  1178. svr.Get("/hi",
  1179. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1181. auto se = detail::scope_exit([&] {
  1182. svr.stop();
  1183. thread.join();
  1184. ASSERT_FALSE(svr.is_running());
  1185. });
  1186. // Give GET time to get a few messages.
  1187. std::this_thread::sleep_for(std::chrono::seconds(1));
  1188. {
  1189. Client cli(HOST, PORT);
  1190. auto res = cli.Get("/hi");
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ(204, res->status);
  1193. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1194. }
  1195. }
  1196. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1199. ASSERT_TRUE(svr.is_valid());
  1200. #else
  1201. Server svr;
  1202. #endif
  1203. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1204. if (req.path == "/routing_handler") {
  1205. res.set_header("PRE_ROUTING", "on");
  1206. res.set_content("Routing Handler", "text/plain");
  1207. return httplib::Server::HandlerResponse::Handled;
  1208. }
  1209. return httplib::Server::HandlerResponse::Unhandled;
  1210. });
  1211. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1212. res.set_content("Error", "text/html");
  1213. });
  1214. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1215. if (req.path == "/routing_handler") {
  1216. res.set_header("POST_ROUTING", "on");
  1217. }
  1218. });
  1219. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1220. res.set_content("Hello World!\n", "text/plain");
  1221. });
  1222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1223. auto se = detail::scope_exit([&] {
  1224. svr.stop();
  1225. thread.join();
  1226. ASSERT_FALSE(svr.is_running());
  1227. });
  1228. // Give GET time to get a few messages.
  1229. std::this_thread::sleep_for(std::chrono::seconds(1));
  1230. {
  1231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1232. SSLClient cli(HOST, PORT);
  1233. cli.enable_server_certificate_verification(false);
  1234. #else
  1235. Client cli(HOST, PORT);
  1236. #endif
  1237. auto res = cli.Get("/routing_handler");
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ(200, res->status);
  1240. EXPECT_EQ("Routing Handler", res->body);
  1241. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1242. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1243. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1244. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1245. }
  1246. {
  1247. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1248. SSLClient cli(HOST, PORT);
  1249. cli.enable_server_certificate_verification(false);
  1250. #else
  1251. Client cli(HOST, PORT);
  1252. #endif
  1253. auto res = cli.Get("/hi");
  1254. ASSERT_TRUE(res);
  1255. EXPECT_EQ(200, res->status);
  1256. EXPECT_EQ("Hello World!\n", res->body);
  1257. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1258. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1259. }
  1260. {
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. SSLClient cli(HOST, PORT);
  1263. cli.enable_server_certificate_verification(false);
  1264. #else
  1265. Client cli(HOST, PORT);
  1266. #endif
  1267. auto res = cli.Get("/aaa");
  1268. ASSERT_TRUE(res);
  1269. EXPECT_EQ(404, res->status);
  1270. EXPECT_EQ("Error", res->body);
  1271. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1272. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1273. }
  1274. }
  1275. TEST(InvalidFormatTest, StatusCode) {
  1276. Server svr;
  1277. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1278. res.set_content("Hello World!\n", "text/plain");
  1279. res.status = 9999; // Status should be a three-digit code...
  1280. });
  1281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1282. auto se = detail::scope_exit([&] {
  1283. svr.stop();
  1284. thread.join();
  1285. ASSERT_FALSE(svr.is_running());
  1286. });
  1287. // Give GET time to get a few messages.
  1288. std::this_thread::sleep_for(std::chrono::seconds(1));
  1289. {
  1290. Client cli(HOST, PORT);
  1291. auto res = cli.Get("/hi");
  1292. ASSERT_FALSE(res);
  1293. }
  1294. }
  1295. TEST(URLFragmentTest, WithFragment) {
  1296. Server svr;
  1297. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1298. EXPECT_TRUE(req.target == "/hi");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. std::this_thread::sleep_for(std::chrono::seconds(1));
  1307. {
  1308. Client cli(HOST, PORT);
  1309. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1310. EXPECT_TRUE(res);
  1311. EXPECT_EQ(200, res->status);
  1312. res = cli.Get("/hi%23key1=val1=key2=val2");
  1313. EXPECT_TRUE(res);
  1314. EXPECT_EQ(404, res->status);
  1315. }
  1316. }
  1317. class ServerTest : public ::testing::Test {
  1318. protected:
  1319. ServerTest()
  1320. : cli_(HOST, PORT)
  1321. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1322. ,
  1323. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1324. #endif
  1325. {
  1326. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1327. cli_.enable_server_certificate_verification(false);
  1328. #endif
  1329. }
  1330. virtual void SetUp() {
  1331. svr_.set_mount_point("/", "./www");
  1332. svr_.set_mount_point("/mount", "./www2");
  1333. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1334. svr_.Get("/hi",
  1335. [&](const Request & /*req*/, Response &res) {
  1336. res.set_content("Hello World!", "text/plain");
  1337. })
  1338. .Get("/http_response_splitting",
  1339. [&](const Request & /*req*/, Response &res) {
  1340. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1341. EXPECT_EQ(0U, res.headers.size());
  1342. EXPECT_FALSE(res.has_header("a"));
  1343. res.set_header("a", "1\nSet-Cookie: a=1");
  1344. EXPECT_EQ(0U, res.headers.size());
  1345. EXPECT_FALSE(res.has_header("a"));
  1346. res.set_header("a", "1\rSet-Cookie: a=1");
  1347. EXPECT_EQ(0U, res.headers.size());
  1348. EXPECT_FALSE(res.has_header("a"));
  1349. res.set_header("a\r\nb", "0");
  1350. EXPECT_EQ(0U, res.headers.size());
  1351. EXPECT_FALSE(res.has_header("a"));
  1352. res.set_header("a\rb", "0");
  1353. EXPECT_EQ(0U, res.headers.size());
  1354. EXPECT_FALSE(res.has_header("a"));
  1355. res.set_header("a\nb", "0");
  1356. EXPECT_EQ(0U, res.headers.size());
  1357. EXPECT_FALSE(res.has_header("a"));
  1358. res.set_redirect("1\r\nSet-Cookie: a=1");
  1359. EXPECT_EQ(0U, res.headers.size());
  1360. EXPECT_FALSE(res.has_header("Location"));
  1361. })
  1362. .Get("/slow",
  1363. [&](const Request & /*req*/, Response &res) {
  1364. std::this_thread::sleep_for(std::chrono::seconds(2));
  1365. res.set_content("slow", "text/plain");
  1366. })
  1367. #if 0
  1368. .Post("/slowpost",
  1369. [&](const Request & /*req*/, Response &res) {
  1370. std::this_thread::sleep_for(std::chrono::seconds(2));
  1371. res.set_content("slow", "text/plain");
  1372. })
  1373. #endif
  1374. .Get("/remote_addr",
  1375. [&](const Request &req, Response &res) {
  1376. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1377. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1378. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1379. EXPECT_EQ(req.remote_port,
  1380. std::stoi(req.get_header_value("REMOTE_PORT")));
  1381. res.set_content(remote_addr.c_str(), "text/plain");
  1382. })
  1383. .Get("/local_addr",
  1384. [&](const Request &req, Response &res) {
  1385. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1386. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1387. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1388. auto local_port = req.get_header_value("LOCAL_PORT");
  1389. EXPECT_EQ(req.local_addr, local_addr);
  1390. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1391. res.set_content(local_addr.append(":").append(local_port),
  1392. "text/plain");
  1393. })
  1394. .Get("/endwith%",
  1395. [&](const Request & /*req*/, Response &res) {
  1396. res.set_content("Hello World!", "text/plain");
  1397. })
  1398. .Get("/a\\+\\+b",
  1399. [&](const Request &req, Response &res) {
  1400. ASSERT_TRUE(req.has_param("a +b"));
  1401. auto val = req.get_param_value("a +b");
  1402. res.set_content(val, "text/plain");
  1403. })
  1404. .Get("/", [&](const Request & /*req*/,
  1405. Response &res) { res.set_redirect("/hi"); })
  1406. .Post("/1", [](const Request & /*req*/,
  1407. Response &res) { res.set_redirect("/2", 303); })
  1408. .Get("/2",
  1409. [](const Request & /*req*/, Response &res) {
  1410. res.set_content("redirected.", "text/plain");
  1411. res.status = 200;
  1412. })
  1413. .Post("/person",
  1414. [&](const Request &req, Response &res) {
  1415. if (req.has_param("name") && req.has_param("note")) {
  1416. persons_[req.get_param_value("name")] =
  1417. req.get_param_value("note");
  1418. } else {
  1419. res.status = 400;
  1420. }
  1421. })
  1422. .Put("/person",
  1423. [&](const Request &req, Response &res) {
  1424. if (req.has_param("name") && req.has_param("note")) {
  1425. persons_[req.get_param_value("name")] =
  1426. req.get_param_value("note");
  1427. } else {
  1428. res.status = 400;
  1429. }
  1430. })
  1431. .Get("/person/(.*)",
  1432. [&](const Request &req, Response &res) {
  1433. string name = req.matches[1];
  1434. if (persons_.find(name) != persons_.end()) {
  1435. auto note = persons_[name];
  1436. res.set_content(note, "text/plain");
  1437. } else {
  1438. res.status = 404;
  1439. }
  1440. })
  1441. .Post("/x-www-form-urlencoded-json",
  1442. [&](const Request &req, Response &res) {
  1443. auto json = req.get_param_value("json");
  1444. ASSERT_EQ(JSON_DATA, json);
  1445. res.set_content(json, "appliation/json");
  1446. res.status = 200;
  1447. })
  1448. .Get("/streamed-chunked",
  1449. [&](const Request & /*req*/, Response &res) {
  1450. res.set_chunked_content_provider(
  1451. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1452. sink.os << "123";
  1453. sink.os << "456";
  1454. sink.os << "789";
  1455. sink.done();
  1456. return true;
  1457. });
  1458. })
  1459. .Get("/streamed-chunked2",
  1460. [&](const Request & /*req*/, Response &res) {
  1461. auto i = new int(0);
  1462. res.set_chunked_content_provider(
  1463. "text/plain",
  1464. [i](size_t /*offset*/, DataSink &sink) {
  1465. switch (*i) {
  1466. case 0: sink.os << "123"; break;
  1467. case 1: sink.os << "456"; break;
  1468. case 2: sink.os << "789"; break;
  1469. case 3: sink.done(); break;
  1470. }
  1471. (*i)++;
  1472. return true;
  1473. },
  1474. [i](bool success) {
  1475. EXPECT_TRUE(success);
  1476. delete i;
  1477. });
  1478. })
  1479. .Get("/streamed-chunked-with-trailer",
  1480. [&](const Request & /*req*/, Response &res) {
  1481. auto i = new int(0);
  1482. res.set_header("Trailer", "Dummy1, Dummy2");
  1483. res.set_chunked_content_provider(
  1484. "text/plain",
  1485. [i](size_t /*offset*/, DataSink &sink) {
  1486. switch (*i) {
  1487. case 0: sink.os << "123"; break;
  1488. case 1: sink.os << "456"; break;
  1489. case 2: sink.os << "789"; break;
  1490. case 3: {
  1491. sink.done_with_trailer(
  1492. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  1493. } break;
  1494. }
  1495. (*i)++;
  1496. return true;
  1497. },
  1498. [i](bool success) {
  1499. EXPECT_TRUE(success);
  1500. delete i;
  1501. });
  1502. })
  1503. .Get("/streamed",
  1504. [&](const Request & /*req*/, Response &res) {
  1505. res.set_content_provider(
  1506. 6, "text/plain",
  1507. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1508. sink.os << (offset < 3 ? "a" : "b");
  1509. return true;
  1510. });
  1511. })
  1512. .Get("/streamed-with-range",
  1513. [&](const Request & /*req*/, Response &res) {
  1514. auto data = new std::string("abcdefg");
  1515. res.set_content_provider(
  1516. data->size(), "text/plain",
  1517. [data](size_t offset, size_t length, DataSink &sink) {
  1518. size_t DATA_CHUNK_SIZE = 4;
  1519. const auto &d = *data;
  1520. auto out_len =
  1521. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1522. auto ret =
  1523. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1524. EXPECT_TRUE(ret);
  1525. return true;
  1526. },
  1527. [data](bool success) {
  1528. EXPECT_TRUE(success);
  1529. delete data;
  1530. });
  1531. })
  1532. .Get("/streamed-cancel",
  1533. [&](const Request & /*req*/, Response &res) {
  1534. res.set_content_provider(
  1535. size_t(-1), "text/plain",
  1536. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1537. sink.os << "data_chunk";
  1538. return true;
  1539. });
  1540. })
  1541. .Get("/with-range",
  1542. [&](const Request & /*req*/, Response &res) {
  1543. res.set_content("abcdefg", "text/plain");
  1544. })
  1545. .Post("/chunked",
  1546. [&](const Request &req, Response & /*res*/) {
  1547. EXPECT_EQ(req.body, "dechunked post body");
  1548. })
  1549. .Post("/large-chunked",
  1550. [&](const Request &req, Response & /*res*/) {
  1551. std::string expected(6 * 30 * 1024u, 'a');
  1552. EXPECT_EQ(req.body, expected);
  1553. })
  1554. .Post("/multipart",
  1555. [&](const Request &req, Response & /*res*/) {
  1556. EXPECT_EQ(6u, req.files.size());
  1557. ASSERT_TRUE(!req.has_file("???"));
  1558. ASSERT_TRUE(req.body.empty());
  1559. {
  1560. const auto &file = req.get_file_value("text1");
  1561. EXPECT_TRUE(file.filename.empty());
  1562. EXPECT_EQ("text default", file.content);
  1563. }
  1564. {
  1565. const auto &file = req.get_file_value("text2");
  1566. EXPECT_TRUE(file.filename.empty());
  1567. EXPECT_EQ("aωb", file.content);
  1568. }
  1569. {
  1570. const auto &file = req.get_file_value("file1");
  1571. EXPECT_EQ("hello.txt", file.filename);
  1572. EXPECT_EQ("text/plain", file.content_type);
  1573. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1574. }
  1575. {
  1576. const auto &file = req.get_file_value("file3");
  1577. EXPECT_TRUE(file.filename.empty());
  1578. EXPECT_EQ("application/octet-stream", file.content_type);
  1579. EXPECT_EQ(0u, file.content.size());
  1580. }
  1581. {
  1582. const auto &file = req.get_file_value("file4");
  1583. EXPECT_TRUE(file.filename.empty());
  1584. EXPECT_EQ(0u, file.content.size());
  1585. EXPECT_EQ("application/json tmp-string", file.content_type);
  1586. }
  1587. })
  1588. .Post("/multipart/multi_file_values",
  1589. [&](const Request &req, Response & /*res*/) {
  1590. EXPECT_EQ(5u, req.files.size());
  1591. ASSERT_TRUE(!req.has_file("???"));
  1592. ASSERT_TRUE(req.body.empty());
  1593. {
  1594. const auto &text_value = req.get_file_values("text");
  1595. EXPECT_EQ(1u, text_value.size());
  1596. auto &text = text_value[0];
  1597. EXPECT_TRUE(text.filename.empty());
  1598. EXPECT_EQ("default text", text.content);
  1599. }
  1600. {
  1601. const auto &text1_values = req.get_file_values("multi_text1");
  1602. EXPECT_EQ(2u, text1_values.size());
  1603. EXPECT_EQ("aaaaa", text1_values[0].content);
  1604. EXPECT_EQ("bbbbb", text1_values[1].content);
  1605. }
  1606. {
  1607. const auto &file1_values = req.get_file_values("multi_file1");
  1608. EXPECT_EQ(2u, file1_values.size());
  1609. auto file1 = file1_values[0];
  1610. EXPECT_EQ(file1.filename, "hello.txt");
  1611. EXPECT_EQ(file1.content_type, "text/plain");
  1612. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1613. auto file2 = file1_values[1];
  1614. EXPECT_EQ(file2.filename, "world.json");
  1615. EXPECT_EQ(file2.content_type, "application/json");
  1616. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1617. }
  1618. })
  1619. .Post("/empty",
  1620. [&](const Request &req, Response &res) {
  1621. EXPECT_EQ(req.body, "");
  1622. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1623. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1624. res.set_content("empty", "text/plain");
  1625. })
  1626. .Post("/empty-no-content-type",
  1627. [&](const Request &req, Response &res) {
  1628. EXPECT_EQ(req.body, "");
  1629. EXPECT_FALSE(req.has_header("Content-Type"));
  1630. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1631. res.set_content("empty-no-content-type", "text/plain");
  1632. })
  1633. .Post("/path-only",
  1634. [&](const Request &req, Response &res) {
  1635. EXPECT_EQ(req.body, "");
  1636. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1637. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1638. res.set_content("path-only", "text/plain");
  1639. })
  1640. .Post("/path-headers-only",
  1641. [&](const Request &req, Response &res) {
  1642. EXPECT_EQ(req.body, "");
  1643. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1644. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1645. EXPECT_EQ("world", req.get_header_value("hello"));
  1646. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1647. res.set_content("path-headers-only", "text/plain");
  1648. })
  1649. .Post("/post-large",
  1650. [&](const Request &req, Response &res) {
  1651. EXPECT_EQ(req.body, LARGE_DATA);
  1652. res.set_content(req.body, "text/plain");
  1653. })
  1654. .Put("/empty-no-content-type",
  1655. [&](const Request &req, Response &res) {
  1656. EXPECT_EQ(req.body, "");
  1657. EXPECT_FALSE(req.has_header("Content-Type"));
  1658. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1659. res.set_content("empty-no-content-type", "text/plain");
  1660. })
  1661. .Put("/put",
  1662. [&](const Request &req, Response &res) {
  1663. EXPECT_EQ(req.body, "PUT");
  1664. res.set_content(req.body, "text/plain");
  1665. })
  1666. .Put("/put-large",
  1667. [&](const Request &req, Response &res) {
  1668. EXPECT_EQ(req.body, LARGE_DATA);
  1669. res.set_content(req.body, "text/plain");
  1670. })
  1671. .Patch("/patch",
  1672. [&](const Request &req, Response &res) {
  1673. EXPECT_EQ(req.body, "PATCH");
  1674. res.set_content(req.body, "text/plain");
  1675. })
  1676. .Delete("/delete",
  1677. [&](const Request & /*req*/, Response &res) {
  1678. res.set_content("DELETE", "text/plain");
  1679. })
  1680. .Delete("/delete-body",
  1681. [&](const Request &req, Response &res) {
  1682. EXPECT_EQ(req.body, "content");
  1683. res.set_content(req.body, "text/plain");
  1684. })
  1685. .Options(R"(\*)",
  1686. [&](const Request & /*req*/, Response &res) {
  1687. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1688. })
  1689. .Get("/request-target",
  1690. [&](const Request &req, Response & /*res*/) {
  1691. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1692. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1693. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1694. })
  1695. .Get("/long-query-value",
  1696. [&](const Request &req, Response & /*res*/) {
  1697. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1698. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1699. })
  1700. .Get("/array-param",
  1701. [&](const Request &req, Response & /*res*/) {
  1702. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1703. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1704. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1705. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1706. })
  1707. .Post("/validate-no-multiple-headers",
  1708. [&](const Request &req, Response & /*res*/) {
  1709. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1710. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1711. })
  1712. .Post("/content_receiver",
  1713. [&](const Request &req, Response &res,
  1714. const ContentReader &content_reader) {
  1715. if (req.is_multipart_form_data()) {
  1716. MultipartFormDataItems files;
  1717. content_reader(
  1718. [&](const MultipartFormData &file) {
  1719. files.push_back(file);
  1720. return true;
  1721. },
  1722. [&](const char *data, size_t data_length) {
  1723. files.back().content.append(data, data_length);
  1724. return true;
  1725. });
  1726. EXPECT_EQ(5u, files.size());
  1727. {
  1728. const auto &file = get_file_value(files, "text1");
  1729. EXPECT_TRUE(file.filename.empty());
  1730. EXPECT_EQ("text default", file.content);
  1731. }
  1732. {
  1733. const auto &file = get_file_value(files, "text2");
  1734. EXPECT_TRUE(file.filename.empty());
  1735. EXPECT_EQ("aωb", file.content);
  1736. }
  1737. {
  1738. const auto &file = get_file_value(files, "file1");
  1739. EXPECT_EQ("hello.txt", file.filename);
  1740. EXPECT_EQ("text/plain", file.content_type);
  1741. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1742. }
  1743. {
  1744. const auto &file = get_file_value(files, "file3");
  1745. EXPECT_TRUE(file.filename.empty());
  1746. EXPECT_EQ("application/octet-stream", file.content_type);
  1747. EXPECT_EQ(0u, file.content.size());
  1748. }
  1749. } else {
  1750. std::string body;
  1751. content_reader([&](const char *data, size_t data_length) {
  1752. EXPECT_EQ(7U, data_length);
  1753. body.append(data, data_length);
  1754. return true;
  1755. });
  1756. EXPECT_EQ(body, "content");
  1757. res.set_content(body, "text/plain");
  1758. }
  1759. })
  1760. .Put("/content_receiver",
  1761. [&](const Request & /*req*/, Response &res,
  1762. const ContentReader &content_reader) {
  1763. std::string body;
  1764. content_reader([&](const char *data, size_t data_length) {
  1765. body.append(data, data_length);
  1766. return true;
  1767. });
  1768. EXPECT_EQ(body, "content");
  1769. res.set_content(body, "text/plain");
  1770. })
  1771. .Patch("/content_receiver",
  1772. [&](const Request & /*req*/, Response &res,
  1773. const ContentReader &content_reader) {
  1774. std::string body;
  1775. content_reader([&](const char *data, size_t data_length) {
  1776. body.append(data, data_length);
  1777. return true;
  1778. });
  1779. EXPECT_EQ(body, "content");
  1780. res.set_content(body, "text/plain");
  1781. })
  1782. .Post("/query-string-and-body",
  1783. [&](const Request &req, Response & /*res*/) {
  1784. ASSERT_TRUE(req.has_param("key"));
  1785. EXPECT_EQ(req.get_param_value("key"), "value");
  1786. EXPECT_EQ(req.body, "content");
  1787. })
  1788. .Get("/last-request",
  1789. [&](const Request &req, Response & /*res*/) {
  1790. EXPECT_EQ("close", req.get_header_value("Connection"));
  1791. })
  1792. .Get(R"(/redirect/(\d+))",
  1793. [&](const Request &req, Response &res) {
  1794. auto num = std::stoi(req.matches[1]) + 1;
  1795. std::string url = "/redirect/" + std::to_string(num);
  1796. res.set_redirect(url);
  1797. })
  1798. .Post("/binary",
  1799. [&](const Request &req, Response &res) {
  1800. EXPECT_EQ(4U, req.body.size());
  1801. EXPECT_EQ("application/octet-stream",
  1802. req.get_header_value("Content-Type"));
  1803. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1804. res.set_content(req.body, "application/octet-stream");
  1805. })
  1806. .Put("/binary",
  1807. [&](const Request &req, Response &res) {
  1808. EXPECT_EQ(4U, req.body.size());
  1809. EXPECT_EQ("application/octet-stream",
  1810. req.get_header_value("Content-Type"));
  1811. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1812. res.set_content(req.body, "application/octet-stream");
  1813. })
  1814. .Patch("/binary",
  1815. [&](const Request &req, Response &res) {
  1816. EXPECT_EQ(4U, req.body.size());
  1817. EXPECT_EQ("application/octet-stream",
  1818. req.get_header_value("Content-Type"));
  1819. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1820. res.set_content(req.body, "application/octet-stream");
  1821. })
  1822. .Delete("/binary",
  1823. [&](const Request &req, Response &res) {
  1824. EXPECT_EQ(4U, req.body.size());
  1825. EXPECT_EQ("application/octet-stream",
  1826. req.get_header_value("Content-Type"));
  1827. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1828. res.set_content(req.body, "application/octet-stream");
  1829. })
  1830. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1831. .Get("/compress",
  1832. [&](const Request & /*req*/, Response &res) {
  1833. res.set_content(
  1834. "12345678901234567890123456789012345678901234567890123456789"
  1835. "01234567890123456789012345678901234567890",
  1836. "text/plain");
  1837. })
  1838. .Get("/nocompress",
  1839. [&](const Request & /*req*/, Response &res) {
  1840. res.set_content(
  1841. "12345678901234567890123456789012345678901234567890123456789"
  1842. "01234567890123456789012345678901234567890",
  1843. "application/octet-stream");
  1844. })
  1845. .Post("/compress-multipart",
  1846. [&](const Request &req, Response & /*res*/) {
  1847. EXPECT_EQ(2u, req.files.size());
  1848. ASSERT_TRUE(!req.has_file("???"));
  1849. {
  1850. const auto &file = req.get_file_value("key1");
  1851. EXPECT_TRUE(file.filename.empty());
  1852. EXPECT_EQ("test", file.content);
  1853. }
  1854. {
  1855. const auto &file = req.get_file_value("key2");
  1856. EXPECT_TRUE(file.filename.empty());
  1857. EXPECT_EQ("--abcdefg123", file.content);
  1858. }
  1859. })
  1860. #endif
  1861. ;
  1862. persons_["john"] = "programmer";
  1863. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1864. while (!svr_.is_running()) {
  1865. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1866. }
  1867. }
  1868. virtual void TearDown() {
  1869. svr_.stop();
  1870. if (!request_threads_.empty()) {
  1871. std::this_thread::sleep_for(std::chrono::seconds(1));
  1872. for (auto &t : request_threads_) {
  1873. t.join();
  1874. }
  1875. }
  1876. t_.join();
  1877. }
  1878. map<string, string> persons_;
  1879. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1880. SSLClient cli_;
  1881. SSLServer svr_;
  1882. #else
  1883. Client cli_;
  1884. Server svr_;
  1885. #endif
  1886. thread t_;
  1887. std::vector<thread> request_threads_;
  1888. };
  1889. TEST_F(ServerTest, GetMethod200) {
  1890. auto res = cli_.Get("/hi");
  1891. ASSERT_TRUE(res);
  1892. EXPECT_EQ("HTTP/1.1", res->version);
  1893. EXPECT_EQ(200, res->status);
  1894. EXPECT_EQ("OK", res->reason);
  1895. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1896. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1897. EXPECT_EQ("Hello World!", res->body);
  1898. }
  1899. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1900. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1901. ASSERT_TRUE(res);
  1902. EXPECT_EQ("HTTP/1.1", res->version);
  1903. EXPECT_EQ(200, res->status);
  1904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1905. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1906. EXPECT_EQ("Hello World!", res->body);
  1907. }
  1908. TEST_F(ServerTest, GetMethod302) {
  1909. auto res = cli_.Get("/");
  1910. ASSERT_TRUE(res);
  1911. EXPECT_EQ(302, res->status);
  1912. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1913. }
  1914. TEST_F(ServerTest, GetMethod302Redirect) {
  1915. cli_.set_follow_location(true);
  1916. auto res = cli_.Get("/");
  1917. ASSERT_TRUE(res);
  1918. EXPECT_EQ(200, res->status);
  1919. EXPECT_EQ("Hello World!", res->body);
  1920. EXPECT_EQ("/hi", res->location);
  1921. }
  1922. TEST_F(ServerTest, GetMethod404) {
  1923. auto res = cli_.Get("/invalid");
  1924. ASSERT_TRUE(res);
  1925. EXPECT_EQ(404, res->status);
  1926. }
  1927. TEST_F(ServerTest, HeadMethod200) {
  1928. auto res = cli_.Head("/hi");
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(200, res->status);
  1931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1932. EXPECT_TRUE(res->body.empty());
  1933. }
  1934. TEST_F(ServerTest, HeadMethod200Static) {
  1935. auto res = cli_.Head("/mount/dir/index.html");
  1936. ASSERT_TRUE(res);
  1937. EXPECT_EQ(200, res->status);
  1938. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1939. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1940. EXPECT_TRUE(res->body.empty());
  1941. }
  1942. TEST_F(ServerTest, HeadMethod404) {
  1943. auto res = cli_.Head("/invalid");
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(404, res->status);
  1946. EXPECT_TRUE(res->body.empty());
  1947. }
  1948. TEST_F(ServerTest, GetMethodPersonJohn) {
  1949. auto res = cli_.Get("/person/john");
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(200, res->status);
  1952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1953. EXPECT_EQ("programmer", res->body);
  1954. }
  1955. TEST_F(ServerTest, PostMethod1) {
  1956. auto res = cli_.Get("/person/john1");
  1957. ASSERT_TRUE(res);
  1958. ASSERT_EQ(404, res->status);
  1959. res = cli_.Post("/person", "name=john1&note=coder",
  1960. "application/x-www-form-urlencoded");
  1961. ASSERT_TRUE(res);
  1962. ASSERT_EQ(200, res->status);
  1963. res = cli_.Get("/person/john1");
  1964. ASSERT_TRUE(res);
  1965. ASSERT_EQ(200, res->status);
  1966. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1967. ASSERT_EQ("coder", res->body);
  1968. }
  1969. TEST_F(ServerTest, PostMethod2) {
  1970. auto res = cli_.Get("/person/john2");
  1971. ASSERT_TRUE(res);
  1972. ASSERT_EQ(404, res->status);
  1973. Params params;
  1974. params.emplace("name", "john2");
  1975. params.emplace("note", "coder");
  1976. res = cli_.Post("/person", params);
  1977. ASSERT_TRUE(res);
  1978. ASSERT_EQ(200, res->status);
  1979. res = cli_.Get("/person/john2");
  1980. ASSERT_TRUE(res);
  1981. ASSERT_EQ(200, res->status);
  1982. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1983. ASSERT_EQ("coder", res->body);
  1984. }
  1985. TEST_F(ServerTest, PutMethod3) {
  1986. auto res = cli_.Get("/person/john3");
  1987. ASSERT_TRUE(res);
  1988. ASSERT_EQ(404, res->status);
  1989. Params params;
  1990. params.emplace("name", "john3");
  1991. params.emplace("note", "coder");
  1992. res = cli_.Put("/person", params);
  1993. ASSERT_TRUE(res);
  1994. ASSERT_EQ(200, res->status);
  1995. res = cli_.Get("/person/john3");
  1996. ASSERT_TRUE(res);
  1997. ASSERT_EQ(200, res->status);
  1998. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1999. ASSERT_EQ("coder", res->body);
  2000. }
  2001. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2002. Params params;
  2003. params.emplace("json", JSON_DATA);
  2004. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2005. ASSERT_TRUE(res);
  2006. ASSERT_EQ(200, res->status);
  2007. ASSERT_EQ(JSON_DATA, res->body);
  2008. }
  2009. TEST_F(ServerTest, PostEmptyContent) {
  2010. auto res = cli_.Post("/empty", "", "text/plain");
  2011. ASSERT_TRUE(res);
  2012. ASSERT_EQ(200, res->status);
  2013. ASSERT_EQ("empty", res->body);
  2014. }
  2015. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2016. auto res = cli_.Post("/empty-no-content-type");
  2017. ASSERT_TRUE(res);
  2018. ASSERT_EQ(200, res->status);
  2019. ASSERT_EQ("empty-no-content-type", res->body);
  2020. }
  2021. TEST_F(ServerTest, PostPathOnly) {
  2022. auto res = cli_.Post("/path-only");
  2023. ASSERT_TRUE(res);
  2024. ASSERT_EQ(200, res->status);
  2025. ASSERT_EQ("path-only", res->body);
  2026. }
  2027. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2028. auto res = cli_.Post("/path-headers-only",
  2029. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2030. ASSERT_TRUE(res);
  2031. ASSERT_EQ(200, res->status);
  2032. ASSERT_EQ("path-headers-only", res->body);
  2033. }
  2034. TEST_F(ServerTest, PostLarge) {
  2035. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2036. ASSERT_TRUE(res);
  2037. ASSERT_EQ(200, res->status);
  2038. EXPECT_EQ(LARGE_DATA, res->body);
  2039. }
  2040. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2041. auto res = cli_.Put("/empty-no-content-type");
  2042. ASSERT_TRUE(res);
  2043. ASSERT_EQ(200, res->status);
  2044. ASSERT_EQ("empty-no-content-type", res->body);
  2045. }
  2046. TEST_F(ServerTest, GetMethodDir) {
  2047. auto res = cli_.Get("/dir/");
  2048. ASSERT_TRUE(res);
  2049. EXPECT_EQ(200, res->status);
  2050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2051. auto body = R"(<html>
  2052. <head>
  2053. </head>
  2054. <body>
  2055. <a href="/dir/test.html">Test</a>
  2056. <a href="/hi">hi</a>
  2057. </body>
  2058. </html>
  2059. )";
  2060. EXPECT_EQ(body, res->body);
  2061. }
  2062. TEST_F(ServerTest, GetMethodDirTest) {
  2063. auto res = cli_.Get("/dir/test.html");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(200, res->status);
  2066. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2067. EXPECT_EQ("test.html", res->body);
  2068. }
  2069. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2070. auto res = cli_.Get("/dir/../dir/test.html");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(200, res->status);
  2073. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2074. EXPECT_EQ("test.html", res->body);
  2075. }
  2076. TEST_F(ServerTest, GetMethodInvalidPath) {
  2077. auto res = cli_.Get("/dir/../test.html");
  2078. ASSERT_TRUE(res);
  2079. EXPECT_EQ(404, res->status);
  2080. }
  2081. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2082. auto res = cli_.Get("/../www/dir/test.html");
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(404, res->status);
  2085. }
  2086. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2087. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(404, res->status);
  2090. }
  2091. TEST_F(ServerTest, GetMethodDirMountTest) {
  2092. auto res = cli_.Get("/mount/dir/test.html");
  2093. ASSERT_TRUE(res);
  2094. EXPECT_EQ(200, res->status);
  2095. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2096. EXPECT_EQ("test.html", res->body);
  2097. }
  2098. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2099. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2100. ASSERT_TRUE(res);
  2101. EXPECT_EQ(200, res->status);
  2102. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2103. EXPECT_EQ("test.html", res->body);
  2104. }
  2105. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2106. auto res = cli_.Get("/mount/dir/../test.html");
  2107. ASSERT_TRUE(res);
  2108. EXPECT_EQ(404, res->status);
  2109. }
  2110. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2111. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2112. ASSERT_TRUE(res);
  2113. EXPECT_EQ(404, res->status);
  2114. }
  2115. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2116. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(404, res->status);
  2119. }
  2120. TEST_F(ServerTest, PostMethod303) {
  2121. auto res = cli_.Post("/1", "body", "text/plain");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(303, res->status);
  2124. EXPECT_EQ("/2", res->get_header_value("Location"));
  2125. }
  2126. TEST_F(ServerTest, PostMethod303Redirect) {
  2127. cli_.set_follow_location(true);
  2128. auto res = cli_.Post("/1", "body", "text/plain");
  2129. ASSERT_TRUE(res);
  2130. EXPECT_EQ(200, res->status);
  2131. EXPECT_EQ("redirected.", res->body);
  2132. EXPECT_EQ("/2", res->location);
  2133. }
  2134. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2135. auto res = cli_.Get("/dir/test.abcde");
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(200, res->status);
  2138. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2139. EXPECT_EQ("abcde", res->body);
  2140. }
  2141. TEST_F(ServerTest, StaticFileRange) {
  2142. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2143. ASSERT_TRUE(res);
  2144. EXPECT_EQ(206, res->status);
  2145. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2146. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2147. EXPECT_EQ(true, res->has_header("Content-Range"));
  2148. EXPECT_EQ(std::string("cd"), res->body);
  2149. }
  2150. TEST_F(ServerTest, StaticFileRanges) {
  2151. auto res =
  2152. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2153. ASSERT_TRUE(res);
  2154. EXPECT_EQ(206, res->status);
  2155. EXPECT_TRUE(
  2156. res->get_header_value("Content-Type")
  2157. .find(
  2158. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2159. 0);
  2160. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2161. }
  2162. TEST_F(ServerTest, InvalidBaseDirMount) {
  2163. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2164. }
  2165. TEST_F(ServerTest, Binary) {
  2166. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2167. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2168. "application/octet-stream");
  2169. ASSERT_TRUE(res);
  2170. ASSERT_EQ(200, res->status);
  2171. ASSERT_EQ(4U, res->body.size());
  2172. res = cli_.Put("/binary", binary.data(), binary.size(),
  2173. "application/octet-stream");
  2174. ASSERT_TRUE(res);
  2175. ASSERT_EQ(200, res->status);
  2176. ASSERT_EQ(4U, res->body.size());
  2177. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2178. "application/octet-stream");
  2179. ASSERT_TRUE(res);
  2180. ASSERT_EQ(200, res->status);
  2181. ASSERT_EQ(4U, res->body.size());
  2182. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2183. "application/octet-stream");
  2184. ASSERT_TRUE(res);
  2185. ASSERT_EQ(200, res->status);
  2186. ASSERT_EQ(4U, res->body.size());
  2187. }
  2188. TEST_F(ServerTest, BinaryString) {
  2189. auto binary = std::string("\x00\x01\x02\x03", 4);
  2190. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2191. ASSERT_TRUE(res);
  2192. ASSERT_EQ(200, res->status);
  2193. ASSERT_EQ(4U, res->body.size());
  2194. res = cli_.Put("/binary", binary, "application/octet-stream");
  2195. ASSERT_TRUE(res);
  2196. ASSERT_EQ(200, res->status);
  2197. ASSERT_EQ(4U, res->body.size());
  2198. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2199. ASSERT_TRUE(res);
  2200. ASSERT_EQ(200, res->status);
  2201. ASSERT_EQ(4U, res->body.size());
  2202. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2203. ASSERT_TRUE(res);
  2204. ASSERT_EQ(200, res->status);
  2205. ASSERT_EQ(4U, res->body.size());
  2206. }
  2207. TEST_F(ServerTest, EmptyRequest) {
  2208. auto res = cli_.Get("");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Connection, res.error());
  2211. }
  2212. TEST_F(ServerTest, LongRequest) {
  2213. std::string request;
  2214. for (size_t i = 0; i < 545; i++) {
  2215. request += "/TooLongRequest";
  2216. }
  2217. request += "OK";
  2218. auto res = cli_.Get(request.c_str());
  2219. ASSERT_TRUE(res);
  2220. EXPECT_EQ(404, res->status);
  2221. }
  2222. TEST_F(ServerTest, TooLongRequest) {
  2223. std::string request;
  2224. for (size_t i = 0; i < 545; i++) {
  2225. request += "/TooLongRequest";
  2226. }
  2227. request += "_NG";
  2228. auto res = cli_.Get(request.c_str());
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(414, res->status);
  2231. }
  2232. TEST_F(ServerTest, LongHeader) {
  2233. Request req;
  2234. req.method = "GET";
  2235. req.path = "/hi";
  2236. std::string host_and_port;
  2237. host_and_port += HOST;
  2238. host_and_port += ":";
  2239. host_and_port += std::to_string(PORT);
  2240. req.headers.emplace("Host", host_and_port.c_str());
  2241. req.headers.emplace("Accept", "*/*");
  2242. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2243. req.headers.emplace(
  2244. "Header-Name",
  2245. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2246. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2273. "@@@@@@@@@@@@@@@@");
  2274. auto res = std::make_shared<Response>();
  2275. auto error = Error::Success;
  2276. auto ret = cli_.send(req, *res, error);
  2277. ASSERT_TRUE(ret);
  2278. EXPECT_EQ(200, res->status);
  2279. }
  2280. TEST_F(ServerTest, LongQueryValue) {
  2281. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(414, res->status);
  2284. }
  2285. TEST_F(ServerTest, TooLongHeader) {
  2286. Request req;
  2287. req.method = "GET";
  2288. req.path = "/hi";
  2289. std::string host_and_port;
  2290. host_and_port += HOST;
  2291. host_and_port += ":";
  2292. host_and_port += std::to_string(PORT);
  2293. req.headers.emplace("Host", host_and_port.c_str());
  2294. req.headers.emplace("Accept", "*/*");
  2295. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2296. req.headers.emplace(
  2297. "Header-Name",
  2298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2326. "@@@@@@@@@@@@@@@@@");
  2327. auto res = std::make_shared<Response>();
  2328. auto error = Error::Success;
  2329. auto ret = cli_.send(req, *res, error);
  2330. ASSERT_TRUE(ret);
  2331. EXPECT_EQ(200, res->status);
  2332. }
  2333. TEST_F(ServerTest, PercentEncoding) {
  2334. auto res = cli_.Get("/e%6edwith%");
  2335. ASSERT_TRUE(res);
  2336. EXPECT_EQ(200, res->status);
  2337. }
  2338. TEST_F(ServerTest, PercentEncodingUnicode) {
  2339. auto res = cli_.Get("/e%u006edwith%");
  2340. ASSERT_TRUE(res);
  2341. EXPECT_EQ(200, res->status);
  2342. }
  2343. TEST_F(ServerTest, InvalidPercentEncoding) {
  2344. auto res = cli_.Get("/%endwith%");
  2345. ASSERT_TRUE(res);
  2346. EXPECT_EQ(404, res->status);
  2347. }
  2348. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2349. auto res = cli_.Get("/%uendwith%");
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(404, res->status);
  2352. }
  2353. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2354. auto res = cli_.Get("/hello?aaa=bbb%");
  2355. ASSERT_TRUE(res);
  2356. EXPECT_EQ(404, res->status);
  2357. }
  2358. TEST_F(ServerTest, PlusSignEncoding) {
  2359. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(200, res->status);
  2362. EXPECT_EQ("a +b", res->body);
  2363. }
  2364. TEST_F(ServerTest, MultipartFormData) {
  2365. MultipartFormDataItems items = {
  2366. {"text1", "text default", "", ""},
  2367. {"text2", "aωb", "", ""},
  2368. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2369. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2370. {"file3", "", "", "application/octet-stream"},
  2371. {"file4", "", "", " application/json tmp-string "}};
  2372. auto res = cli_.Post("/multipart", items);
  2373. ASSERT_TRUE(res);
  2374. EXPECT_EQ(200, res->status);
  2375. }
  2376. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2377. MultipartFormDataItems items = {
  2378. {"text", "default text", "", ""},
  2379. {"multi_text1", "aaaaa", "", ""},
  2380. {"multi_text1", "bbbbb", "", ""},
  2381. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2382. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2383. "application/json"},
  2384. };
  2385. auto res = cli_.Post("/multipart/multi_file_values", items);
  2386. ASSERT_TRUE(res);
  2387. EXPECT_EQ(200, res->status);
  2388. }
  2389. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2390. auto res = cli_.Get("/hi");
  2391. ASSERT_TRUE(res);
  2392. EXPECT_EQ(200, res->status);
  2393. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2394. EXPECT_EQ("Hello World!", res->body);
  2395. }
  2396. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2397. Request req;
  2398. req.method = "POST";
  2399. req.path = "/chunked";
  2400. std::string host_and_port;
  2401. host_and_port += HOST;
  2402. host_and_port += ":";
  2403. host_and_port += std::to_string(PORT);
  2404. req.headers.emplace("Host", host_and_port.c_str());
  2405. req.headers.emplace("Accept", "*/*");
  2406. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2407. req.headers.emplace("Content-Type", "text/plain");
  2408. req.headers.emplace("Content-Length", "0");
  2409. req.headers.emplace(
  2410. "Transfer-Encoding",
  2411. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2412. // Client does not chunk, so make a chunked body manually.
  2413. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2414. auto res = std::make_shared<Response>();
  2415. auto error = Error::Success;
  2416. auto ret = cli_.send(req, *res, error);
  2417. ASSERT_TRUE(ret);
  2418. EXPECT_EQ(200, res->status);
  2419. }
  2420. TEST_F(ServerTest, GetStreamed2) {
  2421. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(206, res->status);
  2424. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2425. EXPECT_EQ(std::string("ab"), res->body);
  2426. }
  2427. TEST_F(ServerTest, GetStreamed) {
  2428. auto res = cli_.Get("/streamed");
  2429. ASSERT_TRUE(res);
  2430. EXPECT_EQ(200, res->status);
  2431. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2432. EXPECT_EQ(std::string("aaabbb"), res->body);
  2433. }
  2434. TEST_F(ServerTest, GetStreamedWithRange1) {
  2435. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2436. ASSERT_TRUE(res);
  2437. EXPECT_EQ(206, res->status);
  2438. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2439. EXPECT_EQ(true, res->has_header("Content-Range"));
  2440. EXPECT_EQ(std::string("def"), res->body);
  2441. }
  2442. TEST_F(ServerTest, GetStreamedWithRange2) {
  2443. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(206, res->status);
  2446. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2447. EXPECT_EQ(true, res->has_header("Content-Range"));
  2448. EXPECT_EQ(std::string("bcdefg"), res->body);
  2449. }
  2450. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2451. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(206, res->status);
  2454. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2455. EXPECT_EQ(true, res->has_header("Content-Range"));
  2456. EXPECT_EQ(std::string("efg"), res->body);
  2457. }
  2458. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2459. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2460. ASSERT_TRUE(res);
  2461. EXPECT_EQ(206, res->status);
  2462. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ(true, res->has_header("Content-Range"));
  2464. EXPECT_EQ(std::string("abcdefg"), res->body);
  2465. }
  2466. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2467. auto res = cli_.Get("/streamed-with-range",
  2468. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2469. "92233720368547758079223372036854775807"}});
  2470. ASSERT_TRUE(res);
  2471. EXPECT_EQ(416, res->status);
  2472. }
  2473. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2474. auto res =
  2475. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2476. EXPECT_EQ(206, res->status);
  2477. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2478. EXPECT_EQ(true, res->has_header("Content-Range"));
  2479. EXPECT_EQ(std::string("abcdefg"), res->body);
  2480. }
  2481. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2482. auto res =
  2483. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2484. ASSERT_TRUE(res);
  2485. EXPECT_EQ(206, res->status);
  2486. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2487. EXPECT_EQ(false, res->has_header("Content-Range"));
  2488. EXPECT_EQ(267U, res->body.size());
  2489. }
  2490. TEST_F(ServerTest, GetStreamedEndless) {
  2491. uint64_t offset = 0;
  2492. auto res = cli_.Get("/streamed-cancel",
  2493. [&](const char * /*data*/, uint64_t data_length) {
  2494. if (offset < 100) {
  2495. offset += data_length;
  2496. return true;
  2497. }
  2498. return false;
  2499. });
  2500. ASSERT_TRUE(!res);
  2501. EXPECT_EQ(Error::Canceled, res.error());
  2502. }
  2503. TEST_F(ServerTest, ClientStop) {
  2504. std::atomic_size_t count{4};
  2505. std::vector<std::thread> threads;
  2506. for (auto i = count.load(); i != 0; --i) {
  2507. threads.emplace_back([&]() {
  2508. auto res = cli_.Get("/streamed-cancel",
  2509. [&](const char *, uint64_t) { return true; });
  2510. --count;
  2511. ASSERT_TRUE(!res);
  2512. EXPECT_TRUE(res.error() == Error::Canceled ||
  2513. res.error() == Error::Read || res.error() == Error::Write);
  2514. });
  2515. }
  2516. std::this_thread::sleep_for(std::chrono::seconds(2));
  2517. while (count != 0) {
  2518. cli_.stop();
  2519. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2520. }
  2521. for (auto &t : threads) {
  2522. t.join();
  2523. }
  2524. }
  2525. TEST_F(ServerTest, GetWithRange1) {
  2526. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2527. ASSERT_TRUE(res);
  2528. EXPECT_EQ(206, res->status);
  2529. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2530. EXPECT_EQ(true, res->has_header("Content-Range"));
  2531. EXPECT_EQ(std::string("def"), res->body);
  2532. }
  2533. TEST_F(ServerTest, GetWithRange2) {
  2534. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2535. ASSERT_TRUE(res);
  2536. EXPECT_EQ(206, res->status);
  2537. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2538. EXPECT_EQ(true, res->has_header("Content-Range"));
  2539. EXPECT_EQ(std::string("bcdefg"), res->body);
  2540. }
  2541. TEST_F(ServerTest, GetWithRange3) {
  2542. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2543. ASSERT_TRUE(res);
  2544. EXPECT_EQ(206, res->status);
  2545. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2546. EXPECT_EQ(true, res->has_header("Content-Range"));
  2547. EXPECT_EQ(std::string("a"), res->body);
  2548. }
  2549. TEST_F(ServerTest, GetWithRange4) {
  2550. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2551. ASSERT_TRUE(res);
  2552. EXPECT_EQ(206, res->status);
  2553. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2554. EXPECT_EQ(true, res->has_header("Content-Range"));
  2555. EXPECT_EQ(std::string("fg"), res->body);
  2556. }
  2557. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2558. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2559. ASSERT_TRUE(res);
  2560. EXPECT_EQ(416, res->status);
  2561. }
  2562. TEST_F(ServerTest, GetWithRangeMultipart) {
  2563. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2564. ASSERT_TRUE(res);
  2565. EXPECT_EQ(206, res->status);
  2566. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2567. EXPECT_EQ(false, res->has_header("Content-Range"));
  2568. EXPECT_EQ(267U, res->body.size());
  2569. }
  2570. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2571. auto res =
  2572. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2573. ASSERT_TRUE(res);
  2574. EXPECT_EQ(416, res->status);
  2575. }
  2576. TEST_F(ServerTest, GetStreamedChunked) {
  2577. auto res = cli_.Get("/streamed-chunked");
  2578. ASSERT_TRUE(res);
  2579. EXPECT_EQ(200, res->status);
  2580. EXPECT_EQ(std::string("123456789"), res->body);
  2581. }
  2582. TEST_F(ServerTest, GetStreamedChunked2) {
  2583. auto res = cli_.Get("/streamed-chunked2");
  2584. ASSERT_TRUE(res);
  2585. EXPECT_EQ(200, res->status);
  2586. EXPECT_EQ(std::string("123456789"), res->body);
  2587. }
  2588. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2589. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2590. ASSERT_TRUE(res);
  2591. EXPECT_EQ(200, res->status);
  2592. EXPECT_EQ(std::string("123456789"), res->body);
  2593. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2594. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2595. }
  2596. TEST_F(ServerTest, LargeChunkedPost) {
  2597. Request req;
  2598. req.method = "POST";
  2599. req.path = "/large-chunked";
  2600. std::string host_and_port;
  2601. host_and_port += HOST;
  2602. host_and_port += ":";
  2603. host_and_port += std::to_string(PORT);
  2604. req.headers.emplace("Host", host_and_port.c_str());
  2605. req.headers.emplace("Accept", "*/*");
  2606. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2607. req.headers.emplace("Content-Type", "text/plain");
  2608. req.headers.emplace("Content-Length", "0");
  2609. req.headers.emplace("Transfer-Encoding", "chunked");
  2610. std::string long_string(30 * 1024u, 'a');
  2611. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2612. // Attempt to make a large enough post to exceed OS buffers, to test that
  2613. // the server handles short reads if the full chunk data isn't available.
  2614. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2615. auto res = std::make_shared<Response>();
  2616. auto error = Error::Success;
  2617. auto ret = cli_.send(req, *res, error);
  2618. ASSERT_TRUE(ret);
  2619. EXPECT_EQ(200, res->status);
  2620. }
  2621. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2622. auto res = cli_.Get("/remote_addr");
  2623. ASSERT_TRUE(res);
  2624. EXPECT_EQ(200, res->status);
  2625. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2626. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2627. }
  2628. TEST_F(ServerTest, GetMethodLocalAddr) {
  2629. auto res = cli_.Get("/local_addr");
  2630. ASSERT_TRUE(res);
  2631. EXPECT_EQ(200, res->status);
  2632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2633. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2634. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2635. }
  2636. TEST_F(ServerTest, HTTPResponseSplitting) {
  2637. auto res = cli_.Get("/http_response_splitting");
  2638. ASSERT_TRUE(res);
  2639. EXPECT_EQ(200, res->status);
  2640. }
  2641. TEST_F(ServerTest, SlowRequest) {
  2642. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2643. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2644. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2645. }
  2646. #if 0
  2647. TEST_F(ServerTest, SlowPost) {
  2648. char buffer[64 * 1024];
  2649. memset(buffer, 0x42, sizeof(buffer));
  2650. auto res = cli_.Post(
  2651. "/slowpost", 64 * 1024 * 1024,
  2652. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2653. auto ret = sink.write(buffer, sizeof(buffer));
  2654. EXPECT_TRUE(ret);
  2655. return true;
  2656. },
  2657. "text/plain");
  2658. ASSERT_TRUE(res);
  2659. EXPECT_EQ(200, res->status);
  2660. }
  2661. TEST_F(ServerTest, SlowPostFail) {
  2662. char buffer[64 * 1024];
  2663. memset(buffer, 0x42, sizeof(buffer));
  2664. cli_.set_write_timeout(std::chrono::seconds(0));
  2665. auto res = cli_.Post(
  2666. "/slowpost", 64 * 1024 * 1024,
  2667. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2668. sink.write(buffer, sizeof(buffer));
  2669. return true;
  2670. },
  2671. "text/plain");
  2672. ASSERT_TRUE(!res);
  2673. EXPECT_EQ(Error::Write, res.error());
  2674. }
  2675. #endif
  2676. TEST_F(ServerTest, Put) {
  2677. auto res = cli_.Put("/put", "PUT", "text/plain");
  2678. ASSERT_TRUE(res);
  2679. EXPECT_EQ(200, res->status);
  2680. EXPECT_EQ("PUT", res->body);
  2681. }
  2682. TEST_F(ServerTest, PutWithContentProvider) {
  2683. auto res = cli_.Put(
  2684. "/put", 3,
  2685. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2686. sink.os << "PUT";
  2687. return true;
  2688. },
  2689. "text/plain");
  2690. ASSERT_TRUE(res);
  2691. EXPECT_EQ(200, res->status);
  2692. EXPECT_EQ("PUT", res->body);
  2693. }
  2694. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2695. auto res = cli_.Post(
  2696. "/post", 42,
  2697. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2698. return false;
  2699. },
  2700. "text/plain");
  2701. ASSERT_TRUE(!res);
  2702. EXPECT_EQ(Error::Canceled, res.error());
  2703. }
  2704. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2705. auto res = cli_.Put(
  2706. "/put",
  2707. [](size_t /*offset*/, DataSink &sink) {
  2708. sink.os << "PUT";
  2709. sink.done();
  2710. return true;
  2711. },
  2712. "text/plain");
  2713. ASSERT_TRUE(res);
  2714. EXPECT_EQ(200, res->status);
  2715. EXPECT_EQ("PUT", res->body);
  2716. }
  2717. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2718. auto res = cli_.Post(
  2719. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2720. "text/plain");
  2721. ASSERT_TRUE(!res);
  2722. EXPECT_EQ(Error::Canceled, res.error());
  2723. }
  2724. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2725. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2726. cli_.set_compress(true);
  2727. auto res = cli_.Put(
  2728. "/put", 3,
  2729. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2730. sink.os << "PUT";
  2731. return true;
  2732. },
  2733. "text/plain");
  2734. ASSERT_TRUE(res);
  2735. EXPECT_EQ(200, res->status);
  2736. EXPECT_EQ("PUT", res->body);
  2737. }
  2738. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2739. cli_.set_compress(true);
  2740. auto res = cli_.Post(
  2741. "/post", 42,
  2742. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2743. return false;
  2744. },
  2745. "text/plain");
  2746. ASSERT_TRUE(!res);
  2747. EXPECT_EQ(Error::Canceled, res.error());
  2748. }
  2749. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2750. cli_.set_compress(true);
  2751. auto res = cli_.Put(
  2752. "/put",
  2753. [](size_t /*offset*/, DataSink &sink) {
  2754. sink.os << "PUT";
  2755. sink.done();
  2756. return true;
  2757. },
  2758. "text/plain");
  2759. ASSERT_TRUE(res);
  2760. EXPECT_EQ(200, res->status);
  2761. EXPECT_EQ("PUT", res->body);
  2762. }
  2763. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2764. cli_.set_compress(true);
  2765. auto res = cli_.Post(
  2766. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2767. "text/plain");
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2772. cli_.set_compress(true);
  2773. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2774. ASSERT_TRUE(res);
  2775. EXPECT_EQ(200, res->status);
  2776. EXPECT_EQ(LARGE_DATA, res->body);
  2777. }
  2778. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2779. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2780. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2781. Client cli(s.c_str());
  2782. cli.enable_server_certificate_verification(false);
  2783. #else
  2784. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2785. Client cli(s.c_str());
  2786. #endif
  2787. cli.set_compress(true);
  2788. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2789. ASSERT_TRUE(res);
  2790. EXPECT_EQ(200, res->status);
  2791. EXPECT_EQ(LARGE_DATA, res->body);
  2792. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2793. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2794. }
  2795. TEST_F(ServerTest, PutContentWithDeflate) {
  2796. cli_.set_compress(false);
  2797. Headers headers;
  2798. headers.emplace("Content-Encoding", "deflate");
  2799. // PUT in deflate format:
  2800. auto res = cli_.Put("/put", headers,
  2801. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2802. ASSERT_TRUE(res);
  2803. EXPECT_EQ(200, res->status);
  2804. EXPECT_EQ("PUT", res->body);
  2805. }
  2806. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2807. Headers headers;
  2808. headers.emplace("Accept-Encoding", "gzip, deflate");
  2809. auto res = cli_.Get("/streamed-chunked", headers);
  2810. ASSERT_TRUE(res);
  2811. EXPECT_EQ(200, res->status);
  2812. EXPECT_EQ(std::string("123456789"), res->body);
  2813. }
  2814. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2815. Headers headers;
  2816. headers.emplace("Accept-Encoding", "gzip, deflate");
  2817. auto res = cli_.Get("/streamed-chunked2", headers);
  2818. ASSERT_TRUE(res);
  2819. EXPECT_EQ(200, res->status);
  2820. EXPECT_EQ(std::string("123456789"), res->body);
  2821. }
  2822. TEST(GzipDecompressor, ChunkedDecompression) {
  2823. std::string data;
  2824. for (size_t i = 0; i < 32 * 1024; ++i) {
  2825. data.push_back(static_cast<char>('a' + i % 26));
  2826. }
  2827. std::string compressed_data;
  2828. {
  2829. httplib::detail::gzip_compressor compressor;
  2830. bool result = compressor.compress(
  2831. data.data(), data.size(),
  2832. /*last=*/true,
  2833. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2834. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2835. compressed_data_size);
  2836. return true;
  2837. });
  2838. ASSERT_TRUE(result);
  2839. }
  2840. std::string decompressed_data;
  2841. {
  2842. httplib::detail::gzip_decompressor decompressor;
  2843. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2844. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2845. size_t chunk_size = 130;
  2846. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2847. chunk_begin += chunk_size) {
  2848. size_t current_chunk_size =
  2849. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2850. bool result = decompressor.decompress(
  2851. compressed_data.data() + chunk_begin, current_chunk_size,
  2852. [&](const char *decompressed_data_chunk,
  2853. size_t decompressed_data_chunk_size) {
  2854. decompressed_data.insert(decompressed_data.size(),
  2855. decompressed_data_chunk,
  2856. decompressed_data_chunk_size);
  2857. return true;
  2858. });
  2859. ASSERT_TRUE(result);
  2860. }
  2861. }
  2862. ASSERT_EQ(data, decompressed_data);
  2863. }
  2864. TEST(GzipDecompressor, DeflateDecompression) {
  2865. std::string original_text = "Raw deflate without gzip";
  2866. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2867. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2868. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2869. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  2870. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2871. std::string decompressed_data;
  2872. {
  2873. httplib::detail::gzip_decompressor decompressor;
  2874. bool result = decompressor.decompress(
  2875. compressed_data.data(), compressed_data.size(),
  2876. [&](const char *decompressed_data_chunk,
  2877. size_t decompressed_data_chunk_size) {
  2878. decompressed_data.insert(decompressed_data.size(),
  2879. decompressed_data_chunk,
  2880. decompressed_data_chunk_size);
  2881. return true;
  2882. });
  2883. ASSERT_TRUE(result);
  2884. }
  2885. ASSERT_EQ(original_text, decompressed_data);
  2886. }
  2887. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  2888. std::string original_text = "Raw deflate without gzip";
  2889. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2890. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2891. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2892. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  2893. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  2894. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2895. std::string decompressed_data;
  2896. {
  2897. httplib::detail::gzip_decompressor decompressor;
  2898. bool result = decompressor.decompress(
  2899. compressed_data.data(), compressed_data.size(),
  2900. [&](const char *decompressed_data_chunk,
  2901. size_t decompressed_data_chunk_size) {
  2902. decompressed_data.insert(decompressed_data.size(),
  2903. decompressed_data_chunk,
  2904. decompressed_data_chunk_size);
  2905. return true;
  2906. });
  2907. ASSERT_TRUE(result);
  2908. }
  2909. ASSERT_EQ(original_text, decompressed_data);
  2910. }
  2911. #ifdef _WIN32
  2912. TEST(GzipDecompressor, LargeRandomData) {
  2913. // prepare large random data that is difficult to be compressed and is
  2914. // expected to have large size even when compressed
  2915. std::random_device seed_gen;
  2916. std::mt19937 random(seed_gen());
  2917. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2918. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2919. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2920. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2921. // compress data over 4GiB
  2922. std::string compressed_data;
  2923. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2924. httplib::detail::gzip_compressor compressor;
  2925. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2926. data.size() * sizeof(std::uint32_t), true,
  2927. [&](const char *data, size_t size) {
  2928. compressed_data.insert(
  2929. compressed_data.size(), data, size);
  2930. return true;
  2931. });
  2932. ASSERT_TRUE(result);
  2933. // FIXME: compressed data size is expected to be greater than 4GiB,
  2934. // but there is no guarantee
  2935. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2936. // decompress data over 4GiB
  2937. std::string decompressed_data;
  2938. decompressed_data.reserve(data_size);
  2939. httplib::detail::gzip_decompressor decompressor;
  2940. result = decompressor.decompress(
  2941. compressed_data.data(), compressed_data.size(),
  2942. [&](const char *data, size_t size) {
  2943. decompressed_data.insert(decompressed_data.size(), data, size);
  2944. return true;
  2945. });
  2946. ASSERT_TRUE(result);
  2947. // compare
  2948. ASSERT_EQ(data_size, decompressed_data.size());
  2949. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2950. 0);
  2951. }
  2952. #endif
  2953. #endif
  2954. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2955. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2956. Headers headers;
  2957. headers.emplace("Accept-Encoding", "br");
  2958. auto res = cli_.Get("/streamed-chunked", headers);
  2959. ASSERT_TRUE(res);
  2960. EXPECT_EQ(200, res->status);
  2961. EXPECT_EQ(std::string("123456789"), res->body);
  2962. }
  2963. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2964. Headers headers;
  2965. headers.emplace("Accept-Encoding", "br");
  2966. auto res = cli_.Get("/streamed-chunked2", headers);
  2967. ASSERT_TRUE(res);
  2968. EXPECT_EQ(200, res->status);
  2969. EXPECT_EQ(std::string("123456789"), res->body);
  2970. }
  2971. #endif
  2972. TEST_F(ServerTest, Patch) {
  2973. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2974. ASSERT_TRUE(res);
  2975. EXPECT_EQ(200, res->status);
  2976. EXPECT_EQ("PATCH", res->body);
  2977. }
  2978. TEST_F(ServerTest, Delete) {
  2979. auto res = cli_.Delete("/delete");
  2980. ASSERT_TRUE(res);
  2981. EXPECT_EQ(200, res->status);
  2982. EXPECT_EQ("DELETE", res->body);
  2983. }
  2984. TEST_F(ServerTest, DeleteContentReceiver) {
  2985. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2986. ASSERT_TRUE(res);
  2987. EXPECT_EQ(200, res->status);
  2988. EXPECT_EQ("content", res->body);
  2989. }
  2990. TEST_F(ServerTest, Options) {
  2991. auto res = cli_.Options("*");
  2992. ASSERT_TRUE(res);
  2993. EXPECT_EQ(200, res->status);
  2994. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2995. EXPECT_TRUE(res->body.empty());
  2996. }
  2997. TEST_F(ServerTest, URL) {
  2998. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2999. ASSERT_TRUE(res);
  3000. EXPECT_EQ(200, res->status);
  3001. }
  3002. TEST_F(ServerTest, ArrayParam) {
  3003. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3004. ASSERT_TRUE(res);
  3005. EXPECT_EQ(200, res->status);
  3006. }
  3007. TEST_F(ServerTest, NoMultipleHeaders) {
  3008. Headers headers = {{"Content-Length", "5"}};
  3009. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3010. "text/plain");
  3011. ASSERT_TRUE(res);
  3012. EXPECT_EQ(200, res->status);
  3013. }
  3014. TEST_F(ServerTest, PostContentReceiver) {
  3015. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3016. ASSERT_TRUE(res);
  3017. ASSERT_EQ(200, res->status);
  3018. ASSERT_EQ("content", res->body);
  3019. }
  3020. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3021. MultipartFormDataItems items = {
  3022. {"text1", "text default", "", ""},
  3023. {"text2", "aωb", "", ""},
  3024. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3025. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3026. {"file3", "", "", "application/octet-stream"},
  3027. };
  3028. auto res = cli_.Post("/content_receiver", items);
  3029. ASSERT_TRUE(res);
  3030. EXPECT_EQ(200, res->status);
  3031. }
  3032. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3033. MultipartFormDataItems items = {
  3034. {"text1", "text default", "", ""},
  3035. {"text2", "aωb", "", ""},
  3036. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3037. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3038. {"file3", "", "", "application/octet-stream"},
  3039. };
  3040. auto boundary = std::string("+++++");
  3041. std::string body;
  3042. for (const auto &item : items) {
  3043. body += "--" + boundary + "\r\n";
  3044. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3045. if (!item.filename.empty()) {
  3046. body += "; filename=\"" + item.filename + "\"";
  3047. }
  3048. body += "\r\n";
  3049. if (!item.content_type.empty()) {
  3050. body += "Content-Type: " + item.content_type + "\r\n";
  3051. }
  3052. body += "\r\n";
  3053. body += item.content + "\r\n";
  3054. }
  3055. body += "--" + boundary + "--\r\n";
  3056. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3057. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3058. ASSERT_TRUE(res);
  3059. EXPECT_EQ(200, res->status);
  3060. }
  3061. TEST_F(ServerTest, PostContentReceiverGzip) {
  3062. cli_.set_compress(true);
  3063. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3064. ASSERT_TRUE(res);
  3065. ASSERT_EQ(200, res->status);
  3066. ASSERT_EQ("content", res->body);
  3067. }
  3068. TEST_F(ServerTest, PutContentReceiver) {
  3069. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3070. ASSERT_TRUE(res);
  3071. ASSERT_EQ(200, res->status);
  3072. ASSERT_EQ("content", res->body);
  3073. }
  3074. TEST_F(ServerTest, PatchContentReceiver) {
  3075. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3076. ASSERT_TRUE(res);
  3077. ASSERT_EQ(200, res->status);
  3078. ASSERT_EQ("content", res->body);
  3079. }
  3080. TEST_F(ServerTest, PostQueryStringAndBody) {
  3081. auto res =
  3082. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3083. ASSERT_TRUE(res);
  3084. ASSERT_EQ(200, res->status);
  3085. }
  3086. TEST_F(ServerTest, HTTP2Magic) {
  3087. Request req;
  3088. req.method = "PRI";
  3089. req.path = "*";
  3090. req.body = "SM";
  3091. auto res = std::make_shared<Response>();
  3092. auto error = Error::Success;
  3093. auto ret = cli_.send(req, *res, error);
  3094. ASSERT_TRUE(ret);
  3095. EXPECT_EQ(400, res->status);
  3096. }
  3097. TEST_F(ServerTest, KeepAlive) {
  3098. auto res = cli_.Get("/hi");
  3099. ASSERT_TRUE(res);
  3100. EXPECT_EQ(200, res->status);
  3101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3102. EXPECT_EQ("Hello World!", res->body);
  3103. res = cli_.Get("/hi");
  3104. ASSERT_TRUE(res);
  3105. EXPECT_EQ(200, res->status);
  3106. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3107. EXPECT_EQ("Hello World!", res->body);
  3108. res = cli_.Get("/hi");
  3109. ASSERT_TRUE(res);
  3110. EXPECT_EQ(200, res->status);
  3111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3112. EXPECT_EQ("Hello World!", res->body);
  3113. res = cli_.Get("/not-exist");
  3114. ASSERT_TRUE(res);
  3115. EXPECT_EQ(404, res->status);
  3116. res = cli_.Post("/empty", "", "text/plain");
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(200, res->status);
  3119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3120. EXPECT_EQ("empty", res->body);
  3121. EXPECT_EQ("close", res->get_header_value("Connection"));
  3122. res = cli_.Post(
  3123. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3124. "text/plain");
  3125. ASSERT_TRUE(res);
  3126. EXPECT_EQ(200, res->status);
  3127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3128. EXPECT_EQ("empty", res->body);
  3129. cli_.set_keep_alive(false);
  3130. res = cli_.Get("/last-request");
  3131. ASSERT_TRUE(res);
  3132. EXPECT_EQ(200, res->status);
  3133. EXPECT_EQ("close", res->get_header_value("Connection"));
  3134. }
  3135. TEST_F(ServerTest, TooManyRedirect) {
  3136. cli_.set_follow_location(true);
  3137. auto res = cli_.Get("/redirect/0");
  3138. ASSERT_TRUE(!res);
  3139. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3140. }
  3141. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3142. TEST_F(ServerTest, Gzip) {
  3143. Headers headers;
  3144. headers.emplace("Accept-Encoding", "gzip, deflate");
  3145. auto res = cli_.Get("/compress", headers);
  3146. ASSERT_TRUE(res);
  3147. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3149. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3150. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3151. "7890123456789012345678901234567890",
  3152. res->body);
  3153. EXPECT_EQ(200, res->status);
  3154. }
  3155. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3156. auto res = cli_.Get("/compress");
  3157. ASSERT_TRUE(res);
  3158. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3160. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3161. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3162. "7890123456789012345678901234567890",
  3163. res->body);
  3164. EXPECT_EQ(200, res->status);
  3165. }
  3166. TEST_F(ServerTest, GzipWithContentReceiver) {
  3167. Headers headers;
  3168. headers.emplace("Accept-Encoding", "gzip, deflate");
  3169. std::string body;
  3170. auto res = cli_.Get("/compress", headers,
  3171. [&](const char *data, uint64_t data_length) {
  3172. EXPECT_EQ(100U, data_length);
  3173. body.append(data, data_length);
  3174. return true;
  3175. });
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3180. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3181. "7890123456789012345678901234567890",
  3182. body);
  3183. EXPECT_EQ(200, res->status);
  3184. }
  3185. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3186. Headers headers;
  3187. headers.emplace("Accept-Encoding", "gzip, deflate");
  3188. cli_.set_decompress(false);
  3189. auto res = cli_.Get("/compress", headers);
  3190. ASSERT_TRUE(res);
  3191. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3193. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3194. EXPECT_EQ(33U, res->body.size());
  3195. EXPECT_EQ(200, res->status);
  3196. }
  3197. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3198. std::string body;
  3199. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3200. EXPECT_EQ(100U, data_length);
  3201. body.append(data, data_length);
  3202. return true;
  3203. });
  3204. ASSERT_TRUE(res);
  3205. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3207. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3208. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3209. "7890123456789012345678901234567890",
  3210. body);
  3211. EXPECT_EQ(200, res->status);
  3212. }
  3213. TEST_F(ServerTest, NoGzip) {
  3214. Headers headers;
  3215. headers.emplace("Accept-Encoding", "gzip, deflate");
  3216. auto res = cli_.Get("/nocompress", headers);
  3217. ASSERT_TRUE(res);
  3218. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3219. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3220. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3221. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3222. "7890123456789012345678901234567890",
  3223. res->body);
  3224. EXPECT_EQ(200, res->status);
  3225. }
  3226. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3227. Headers headers;
  3228. headers.emplace("Accept-Encoding", "gzip, deflate");
  3229. std::string body;
  3230. auto res = cli_.Get("/nocompress", headers,
  3231. [&](const char *data, uint64_t data_length) {
  3232. EXPECT_EQ(100U, data_length);
  3233. body.append(data, data_length);
  3234. return true;
  3235. });
  3236. ASSERT_TRUE(res);
  3237. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3238. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3239. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3240. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3241. "7890123456789012345678901234567890",
  3242. body);
  3243. EXPECT_EQ(200, res->status);
  3244. }
  3245. TEST_F(ServerTest, MultipartFormDataGzip) {
  3246. MultipartFormDataItems items = {
  3247. {"key1", "test", "", ""},
  3248. {"key2", "--abcdefg123", "", ""},
  3249. };
  3250. cli_.set_compress(true);
  3251. auto res = cli_.Post("/compress-multipart", items);
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(200, res->status);
  3254. }
  3255. #endif
  3256. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3257. TEST_F(ServerTest, Brotli) {
  3258. Headers headers;
  3259. headers.emplace("Accept-Encoding", "br");
  3260. auto res = cli_.Get("/compress", headers);
  3261. ASSERT_TRUE(res);
  3262. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3263. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3264. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3265. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3266. "7890123456789012345678901234567890",
  3267. res->body);
  3268. EXPECT_EQ(200, res->status);
  3269. }
  3270. #endif
  3271. // Sends a raw request to a server listening at HOST:PORT.
  3272. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3273. std::string *resp = nullptr) {
  3274. auto error = Error::Success;
  3275. auto client_sock = detail::create_client_socket(
  3276. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3277. /*connection_timeout_sec=*/5, 0,
  3278. /*read_timeout_sec=*/5, 0,
  3279. /*write_timeout_sec=*/5, 0, std::string(), error);
  3280. if (client_sock == INVALID_SOCKET) { return false; }
  3281. auto ret = detail::process_client_socket(
  3282. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3283. if (req.size() !=
  3284. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3285. return false;
  3286. }
  3287. char buf[512];
  3288. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3289. while (line_reader.getline()) {
  3290. if (resp) { *resp += line_reader.ptr(); }
  3291. }
  3292. return true;
  3293. });
  3294. detail::close_socket(client_sock);
  3295. return ret;
  3296. }
  3297. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3298. Server svr;
  3299. std::string header_value;
  3300. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3301. header_value = req.get_header_value("foo");
  3302. res.set_content("ok", "text/plain");
  3303. });
  3304. thread t = thread([&] { svr.listen(HOST, PORT); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. t.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3312. // like characters are not treated the same - use vertical tab and escape.
  3313. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3314. "foo: \t \v bar \x1B\t \r\n"
  3315. "Connection: close\r\n"
  3316. "\r\n";
  3317. ASSERT_TRUE(send_request(5, req));
  3318. EXPECT_EQ(header_value, "\v bar \x1B");
  3319. }
  3320. // Sends a raw request and verifies that there isn't a crash or exception.
  3321. static void test_raw_request(const std::string &req,
  3322. std::string *out = nullptr) {
  3323. Server svr;
  3324. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3325. res.set_content("ok", "text/plain");
  3326. });
  3327. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3328. res.set_content("ok", "text/plain");
  3329. });
  3330. // Server read timeout must be longer than the client read timeout for the
  3331. // bug to reproduce, probably to force the server to process a request
  3332. // without a trailing blank line.
  3333. const time_t client_read_timeout_sec = 1;
  3334. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3335. bool listen_thread_ok = false;
  3336. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3337. auto se = detail::scope_exit([&] {
  3338. svr.stop();
  3339. t.join();
  3340. ASSERT_FALSE(svr.is_running());
  3341. EXPECT_TRUE(listen_thread_ok);
  3342. });
  3343. svr.wait_until_ready();
  3344. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3345. }
  3346. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3347. // A certain header line causes an exception if the header property is parsed
  3348. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3349. test_raw_request(
  3350. "GET /hi HTTP/1.1\r\n"
  3351. " : "
  3352. " "
  3353. " ");
  3354. }
  3355. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3356. // A certain header line causes an exception if the header property *name* is
  3357. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3358. // greedy matcher and requires backtracking when there are a lot of ":"
  3359. // characters.
  3360. // This occurs with libc++ but not libstdc++.
  3361. test_raw_request(
  3362. "GET /hi HTTP/1.1\r\n"
  3363. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3364. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3365. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3366. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3367. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3368. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3369. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3370. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3371. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3372. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3373. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3374. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3375. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3376. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3377. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3378. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3379. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3380. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3381. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3382. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3383. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3384. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3385. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3386. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3387. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3388. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3389. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3390. "&&&%%%");
  3391. }
  3392. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3393. // Make sure this doesn't crash the server.
  3394. // In a previous version of the header line regex, the "\r" rendered the line
  3395. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3396. // a new position where the leading white space ended and the field value
  3397. // began.
  3398. // The crash occurs with libc++ but not libstdc++.
  3399. test_raw_request("GET /hi HTTP/1.1\r\n"
  3400. "a:" +
  3401. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3402. "\r\n"
  3403. "\r\n");
  3404. }
  3405. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3406. std::string out;
  3407. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3408. "Content-Type: text/plain\r\n"
  3409. "Transfer-Encoding: chunked\r\n"
  3410. "\r\n"
  3411. "nothex\r\n",
  3412. &out);
  3413. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3414. }
  3415. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3416. std::string out;
  3417. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3418. "Content-Type: text/plain\r\n"
  3419. "Transfer-Encoding: chunked\r\n"
  3420. "\r\n"
  3421. "3\r\n"
  3422. "xyz\r\n"
  3423. "NaN\r\n",
  3424. &out);
  3425. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3426. }
  3427. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3428. std::string out;
  3429. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3430. "Content-Type: text/plain\r\n"
  3431. "Transfer-Encoding: chunked\r\n"
  3432. "\r\n"
  3433. // Length is too large for 64 bits.
  3434. "1ffffffffffffffff\r\n"
  3435. "xyz\r\n",
  3436. &out);
  3437. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3438. }
  3439. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3440. test_raw_request("GET /hi HTTP/1.1\r\n"
  3441. "Content-Type: text/plain\r\n\r");
  3442. }
  3443. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3444. std::string out;
  3445. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3446. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3447. }
  3448. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3449. Server svr;
  3450. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3451. res.set_header("Cache-Control", "no-cache");
  3452. res.set_chunked_content_provider(
  3453. "text/event-stream", [](size_t offset, DataSink &sink) {
  3454. std::string s = "data:";
  3455. s += std::to_string(offset);
  3456. s += "\n\n";
  3457. auto ret = sink.write(s.data(), s.size());
  3458. EXPECT_TRUE(ret);
  3459. std::this_thread::sleep_for(std::chrono::seconds(1));
  3460. return true;
  3461. });
  3462. });
  3463. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3464. svr.wait_until_ready();
  3465. Client client(HOST, PORT);
  3466. const Headers headers = {{"Accept", "text/event-stream"}};
  3467. auto get_thread = std::thread([&client, &headers]() {
  3468. auto res = client.Get(
  3469. "/events", headers,
  3470. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3471. });
  3472. auto se = detail::scope_exit([&] {
  3473. svr.stop();
  3474. get_thread.join();
  3475. listen_thread.join();
  3476. ASSERT_FALSE(svr.is_running());
  3477. });
  3478. // Give GET time to get a few messages.
  3479. std::this_thread::sleep_for(std::chrono::seconds(2));
  3480. }
  3481. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3482. httplib::Server svr;
  3483. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3484. httplib::Response &res) { res.status = 200; });
  3485. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3486. svr.wait_until_ready();
  3487. Client cli(HOST, PORT);
  3488. auto res = cli.Post("/hi", "data", "text/plain");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(200, res->status);
  3491. svr.stop();
  3492. thread.join();
  3493. ASSERT_FALSE(svr.is_running());
  3494. res = cli.Post("/hi", "data", "text/plain");
  3495. ASSERT_FALSE(res);
  3496. }
  3497. TEST(ServerStopTest, ListenFailure) {
  3498. Server svr;
  3499. auto t = thread([&]() {
  3500. auto ret = svr.listen("????", PORT);
  3501. EXPECT_FALSE(ret);
  3502. });
  3503. svr.wait_until_ready();
  3504. svr.stop();
  3505. t.join();
  3506. }
  3507. TEST(StreamingTest, NoContentLengthStreaming) {
  3508. Server svr;
  3509. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3510. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3511. if (offset < 6) {
  3512. sink.os << (offset < 3 ? "a" : "b");
  3513. } else {
  3514. sink.done();
  3515. }
  3516. return true;
  3517. });
  3518. });
  3519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3520. auto listen_se = detail::scope_exit([&] {
  3521. svr.stop();
  3522. listen_thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. });
  3525. svr.wait_until_ready();
  3526. Client client(HOST, PORT);
  3527. auto get_thread = std::thread([&client]() {
  3528. std::string s;
  3529. auto res =
  3530. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3531. s += std::string(data, len);
  3532. return true;
  3533. });
  3534. EXPECT_EQ("aaabbb", s);
  3535. });
  3536. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3537. // Give GET time to get a few messages.
  3538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3539. }
  3540. TEST(MountTest, Unmount) {
  3541. Server svr;
  3542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. listen_thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. // Give GET time to get a few messages.
  3550. std::this_thread::sleep_for(std::chrono::seconds(1));
  3551. Client cli("localhost", PORT);
  3552. svr.set_mount_point("/mount2", "./www2");
  3553. auto res = cli.Get("/");
  3554. ASSERT_TRUE(res);
  3555. EXPECT_EQ(404, res->status);
  3556. res = cli.Get("/mount2/dir/test.html");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(200, res->status);
  3559. svr.set_mount_point("/", "./www");
  3560. res = cli.Get("/dir/");
  3561. ASSERT_TRUE(res);
  3562. EXPECT_EQ(200, res->status);
  3563. svr.remove_mount_point("/");
  3564. res = cli.Get("/dir/");
  3565. ASSERT_TRUE(res);
  3566. EXPECT_EQ(404, res->status);
  3567. svr.remove_mount_point("/mount2");
  3568. res = cli.Get("/mount2/dir/test.html");
  3569. ASSERT_TRUE(res);
  3570. EXPECT_EQ(404, res->status);
  3571. }
  3572. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3573. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3574. Server svr;
  3575. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3576. throw std::runtime_error("exception...");
  3577. });
  3578. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3579. throw std::runtime_error("exception\r\n...");
  3580. });
  3581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. listen_thread.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. // Give GET time to get a few messages.
  3589. std::this_thread::sleep_for(std::chrono::seconds(1));
  3590. Client cli("localhost", PORT);
  3591. {
  3592. auto res = cli.Get("/exception");
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(500, res->status);
  3595. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3596. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3597. }
  3598. {
  3599. auto res = cli.Get("/unknown");
  3600. ASSERT_TRUE(res);
  3601. EXPECT_EQ(500, res->status);
  3602. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3603. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3604. }
  3605. }
  3606. #endif
  3607. TEST(KeepAliveTest, ReadTimeout) {
  3608. Server svr;
  3609. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3610. std::this_thread::sleep_for(std::chrono::seconds(2));
  3611. res.set_content("a", "text/plain");
  3612. });
  3613. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3614. res.set_content("b", "text/plain");
  3615. });
  3616. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3617. auto se = detail::scope_exit([&] {
  3618. svr.stop();
  3619. listen_thread.join();
  3620. ASSERT_FALSE(svr.is_running());
  3621. });
  3622. svr.wait_until_ready();
  3623. // Give GET time to get a few messages.
  3624. std::this_thread::sleep_for(std::chrono::seconds(1));
  3625. Client cli("localhost", PORT);
  3626. cli.set_keep_alive(true);
  3627. cli.set_read_timeout(std::chrono::seconds(1));
  3628. auto resa = cli.Get("/a");
  3629. ASSERT_FALSE(resa);
  3630. EXPECT_EQ(Error::Read, resa.error());
  3631. auto resb = cli.Get("/b");
  3632. ASSERT_TRUE(resb);
  3633. EXPECT_EQ(200, resb->status);
  3634. EXPECT_EQ("b", resb->body);
  3635. }
  3636. TEST(KeepAliveTest, Issue1041) {
  3637. Server svr;
  3638. svr.set_keep_alive_timeout(3);
  3639. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3640. res.set_content("Hello World!", "text/plain");
  3641. });
  3642. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3643. auto se = detail::scope_exit([&] {
  3644. svr.stop();
  3645. listen_thread.join();
  3646. ASSERT_FALSE(svr.is_running());
  3647. });
  3648. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3649. Client cli(HOST, PORT);
  3650. cli.set_keep_alive(true);
  3651. auto result = cli.Get("/hi");
  3652. ASSERT_TRUE(result);
  3653. EXPECT_EQ(200, result->status);
  3654. std::this_thread::sleep_for(std::chrono::seconds(5));
  3655. result = cli.Get("/hi");
  3656. ASSERT_TRUE(result);
  3657. EXPECT_EQ(200, result->status);
  3658. }
  3659. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3660. TEST(KeepAliveTest, SSLClientReconnection) {
  3661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3662. ASSERT_TRUE(svr.is_valid());
  3663. svr.set_keep_alive_timeout(1);
  3664. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3665. res.set_content("Hello World!", "text/plain");
  3666. });
  3667. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3668. auto se = detail::scope_exit([&] {
  3669. svr.stop();
  3670. listen_thread.join();
  3671. ASSERT_FALSE(svr.is_running());
  3672. });
  3673. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3674. SSLClient cli(HOST, PORT);
  3675. cli.enable_server_certificate_verification(false);
  3676. cli.set_keep_alive(true);
  3677. auto result = cli.Get("/hi");
  3678. ASSERT_TRUE(result);
  3679. EXPECT_EQ(200, result->status);
  3680. result = cli.Get("/hi");
  3681. ASSERT_TRUE(result);
  3682. EXPECT_EQ(200, result->status);
  3683. std::this_thread::sleep_for(std::chrono::seconds(2));
  3684. // Recoonect
  3685. result = cli.Get("/hi");
  3686. ASSERT_TRUE(result);
  3687. EXPECT_EQ(200, result->status);
  3688. result = cli.Get("/hi");
  3689. ASSERT_TRUE(result);
  3690. EXPECT_EQ(200, result->status);
  3691. }
  3692. #endif
  3693. TEST(ClientProblemDetectionTest, ContentProvider) {
  3694. Server svr;
  3695. size_t content_length = 1024 * 1024;
  3696. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3697. res.set_content_provider(
  3698. content_length, "text/plain",
  3699. [&](size_t offset, size_t length, DataSink &sink) {
  3700. auto out_len = std::min(length, static_cast<size_t>(1024));
  3701. std::string out(out_len, '@');
  3702. sink.write(out.data(), out_len);
  3703. return offset < 4096;
  3704. },
  3705. [](bool success) { ASSERT_FALSE(success); });
  3706. });
  3707. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3708. res.set_content_provider(
  3709. 0, "text/plain",
  3710. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3711. EXPECT_TRUE(false);
  3712. return true;
  3713. },
  3714. [](bool success) { ASSERT_FALSE(success); });
  3715. });
  3716. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3717. auto se = detail::scope_exit([&] {
  3718. svr.stop();
  3719. listen_thread.join();
  3720. ASSERT_FALSE(svr.is_running());
  3721. });
  3722. svr.wait_until_ready();
  3723. // Give GET time to get a few messages.
  3724. std::this_thread::sleep_for(std::chrono::seconds(1));
  3725. Client cli("localhost", PORT);
  3726. {
  3727. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3728. size_t /*data_length*/) { return false; });
  3729. ASSERT_FALSE(res);
  3730. }
  3731. {
  3732. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3733. size_t /*data_length*/) { return false; });
  3734. ASSERT_TRUE(res);
  3735. }
  3736. }
  3737. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3738. Server svr;
  3739. svr.set_error_handler([](Request const &, Response &res) -> void {
  3740. res.set_chunked_content_provider(
  3741. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3742. sink.os << "hello";
  3743. sink.os << "world";
  3744. sink.done();
  3745. return true;
  3746. });
  3747. });
  3748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. listen_thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. // Give GET time to get a few messages.
  3756. std::this_thread::sleep_for(std::chrono::seconds(1));
  3757. Client cli("localhost", PORT);
  3758. auto res = cli.Get("/");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(404, res->status);
  3761. EXPECT_EQ("helloworld", res->body);
  3762. }
  3763. TEST(GetWithParametersTest, GetWithParameters) {
  3764. Server svr;
  3765. svr.Get("/", [&](const Request &req, Response &) {
  3766. EXPECT_EQ("world", req.get_param_value("hello"));
  3767. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3768. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3769. });
  3770. svr.Get("/params", [&](const Request &req, Response &) {
  3771. EXPECT_EQ("world", req.get_param_value("hello"));
  3772. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3773. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3774. });
  3775. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3776. EXPECT_EQ("resource-id", req.matches[1]);
  3777. EXPECT_EQ("foo", req.get_param_value("param1"));
  3778. EXPECT_EQ("bar", req.get_param_value("param2"));
  3779. });
  3780. svr.Get("/users/:id", [&](const Request &req, Response &) {
  3781. EXPECT_EQ("user-id", req.path_params.at("id"));
  3782. EXPECT_EQ("foo", req.get_param_value("param1"));
  3783. EXPECT_EQ("bar", req.get_param_value("param2"));
  3784. });
  3785. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. listen_thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. std::this_thread::sleep_for(std::chrono::seconds(1));
  3793. {
  3794. Client cli(HOST, PORT);
  3795. Params params;
  3796. params.emplace("hello", "world");
  3797. params.emplace("hello2", "world2");
  3798. params.emplace("hello3", "world3");
  3799. auto res = cli.Get("/", params, Headers{});
  3800. ASSERT_TRUE(res);
  3801. EXPECT_EQ(200, res->status);
  3802. }
  3803. {
  3804. Client cli(HOST, PORT);
  3805. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3806. ASSERT_TRUE(res);
  3807. EXPECT_EQ(200, res->status);
  3808. }
  3809. {
  3810. Client cli(HOST, PORT);
  3811. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(200, res->status);
  3814. }
  3815. {
  3816. Client cli(HOST, PORT);
  3817. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  3818. ASSERT_TRUE(res);
  3819. EXPECT_EQ(200, res->status);
  3820. }
  3821. }
  3822. TEST(GetWithParametersTest, GetWithParameters2) {
  3823. Server svr;
  3824. svr.Get("/", [&](const Request &req, Response &res) {
  3825. auto text = req.get_param_value("hello");
  3826. res.set_content(text, "text/plain");
  3827. });
  3828. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. listen_thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. std::this_thread::sleep_for(std::chrono::seconds(1));
  3836. Client cli("localhost", PORT);
  3837. Params params;
  3838. params.emplace("hello", "world");
  3839. std::string body;
  3840. auto res = cli.Get("/", params, Headers{},
  3841. [&](const char *data, size_t data_length) {
  3842. body.append(data, data_length);
  3843. return true;
  3844. });
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(200, res->status);
  3847. EXPECT_EQ("world", body);
  3848. }
  3849. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3850. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  3851. auto host = "httpbin.org";
  3852. auto path = std::string{"/range/32"};
  3853. #else
  3854. auto host = "nghttp2.org";
  3855. auto path = std::string{"/httpbin/range/32"};
  3856. #endif
  3857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3858. SSLClient cli(host);
  3859. #else
  3860. Client cli(host);
  3861. #endif
  3862. cli.set_default_headers({make_range_header({{1, 10}})});
  3863. cli.set_connection_timeout(5);
  3864. {
  3865. auto res = cli.Get(path);
  3866. ASSERT_TRUE(res);
  3867. EXPECT_EQ("bcdefghijk", res->body);
  3868. EXPECT_EQ(206, res->status);
  3869. }
  3870. {
  3871. auto res = cli.Get(path);
  3872. ASSERT_TRUE(res);
  3873. EXPECT_EQ("bcdefghijk", res->body);
  3874. EXPECT_EQ(206, res->status);
  3875. }
  3876. }
  3877. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3878. Server svr;
  3879. svr.set_default_headers({{"Hello", "World"}});
  3880. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3881. res.set_content("ok", "text/plain");
  3882. });
  3883. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3884. auto se = detail::scope_exit([&] {
  3885. svr.stop();
  3886. listen_thread.join();
  3887. ASSERT_FALSE(svr.is_running());
  3888. });
  3889. svr.wait_until_ready();
  3890. std::this_thread::sleep_for(std::chrono::seconds(1));
  3891. Client cli("localhost", PORT);
  3892. auto res = cli.Get("/");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(200, res->status);
  3895. EXPECT_EQ("ok", res->body);
  3896. EXPECT_EQ("World", res->get_header_value("Hello"));
  3897. }
  3898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3899. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3901. ASSERT_TRUE(svr.is_valid());
  3902. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3903. std::this_thread::sleep_for(std::chrono::seconds(2));
  3904. res.set_content("a", "text/plain");
  3905. });
  3906. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3907. res.set_content("b", "text/plain");
  3908. });
  3909. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3910. auto se = detail::scope_exit([&] {
  3911. svr.stop();
  3912. listen_thread.join();
  3913. ASSERT_FALSE(svr.is_running());
  3914. });
  3915. svr.wait_until_ready();
  3916. // Give GET time to get a few messages.
  3917. std::this_thread::sleep_for(std::chrono::seconds(1));
  3918. SSLClient cli("localhost", PORT);
  3919. cli.enable_server_certificate_verification(false);
  3920. cli.set_keep_alive(true);
  3921. cli.set_read_timeout(std::chrono::seconds(1));
  3922. auto resa = cli.Get("/a");
  3923. ASSERT_TRUE(!resa);
  3924. EXPECT_EQ(Error::Read, resa.error());
  3925. auto resb = cli.Get("/b");
  3926. ASSERT_TRUE(resb);
  3927. EXPECT_EQ(200, resb->status);
  3928. EXPECT_EQ("b", resb->body);
  3929. }
  3930. #endif
  3931. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3932. protected:
  3933. ServerTestWithAI_PASSIVE()
  3934. : cli_(HOST, PORT)
  3935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3936. ,
  3937. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3938. #endif
  3939. {
  3940. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3941. cli_.enable_server_certificate_verification(false);
  3942. #endif
  3943. }
  3944. virtual void SetUp() {
  3945. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3946. res.set_content("Hello World!", "text/plain");
  3947. });
  3948. t_ = thread(
  3949. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3950. while (!svr_.is_running()) {
  3951. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3952. }
  3953. }
  3954. virtual void TearDown() {
  3955. svr_.stop();
  3956. t_.join();
  3957. }
  3958. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3959. SSLClient cli_;
  3960. SSLServer svr_;
  3961. #else
  3962. Client cli_;
  3963. Server svr_;
  3964. #endif
  3965. thread t_;
  3966. };
  3967. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3968. auto res = cli_.Get("/hi");
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(200, res->status);
  3971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3972. EXPECT_EQ("Hello World!", res->body);
  3973. }
  3974. class ServerUpDownTest : public ::testing::Test {
  3975. protected:
  3976. ServerUpDownTest() : cli_(HOST, PORT) {}
  3977. virtual void SetUp() {
  3978. t_ = thread([&]() {
  3979. svr_.bind_to_any_port(HOST);
  3980. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3981. ASSERT_TRUE(svr_.listen_after_bind());
  3982. });
  3983. while (!svr_.is_running()) {
  3984. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3985. }
  3986. }
  3987. virtual void TearDown() {
  3988. svr_.stop();
  3989. t_.join();
  3990. }
  3991. Client cli_;
  3992. Server svr_;
  3993. thread t_;
  3994. };
  3995. TEST_F(ServerUpDownTest, QuickStartStop) {
  3996. // Should not crash, especially when run with
  3997. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3998. }
  3999. class PayloadMaxLengthTest : public ::testing::Test {
  4000. protected:
  4001. PayloadMaxLengthTest()
  4002. : cli_(HOST, PORT)
  4003. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4004. ,
  4005. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4006. #endif
  4007. {
  4008. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4009. cli_.enable_server_certificate_verification(false);
  4010. #endif
  4011. }
  4012. virtual void SetUp() {
  4013. svr_.set_payload_max_length(8);
  4014. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4015. res.set_content("test", "text/plain");
  4016. });
  4017. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4018. while (!svr_.is_running()) {
  4019. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4020. }
  4021. }
  4022. virtual void TearDown() {
  4023. svr_.stop();
  4024. t_.join();
  4025. }
  4026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4027. SSLClient cli_;
  4028. SSLServer svr_;
  4029. #else
  4030. Client cli_;
  4031. Server svr_;
  4032. #endif
  4033. thread t_;
  4034. };
  4035. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4036. auto res = cli_.Post("/test", "123456789", "text/plain");
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(413, res->status);
  4039. res = cli_.Post("/test", "12345678", "text/plain");
  4040. ASSERT_TRUE(res);
  4041. EXPECT_EQ(200, res->status);
  4042. }
  4043. TEST(HostAndPortPropertiesTest, NoSSL) {
  4044. httplib::Client cli("www.google.com", 1234);
  4045. ASSERT_EQ("www.google.com", cli.host());
  4046. ASSERT_EQ(1234, cli.port());
  4047. }
  4048. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4049. httplib::Client cli("www.google.com:1234");
  4050. ASSERT_EQ("www.google.com", cli.host());
  4051. ASSERT_EQ(1234, cli.port());
  4052. }
  4053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4054. TEST(HostAndPortPropertiesTest, SSL) {
  4055. httplib::SSLClient cli("www.google.com");
  4056. ASSERT_EQ("www.google.com", cli.host());
  4057. ASSERT_EQ(443, cli.port());
  4058. }
  4059. #endif
  4060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4061. TEST(SSLClientTest, UpdateCAStore) {
  4062. httplib::SSLClient httplib_client("www.google.com");
  4063. auto ca_store_1 = X509_STORE_new();
  4064. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4065. nullptr);
  4066. httplib_client.set_ca_cert_store(ca_store_1);
  4067. auto ca_store_2 = X509_STORE_new();
  4068. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4069. nullptr);
  4070. httplib_client.set_ca_cert_store(ca_store_2);
  4071. }
  4072. TEST(SSLClientTest, ServerNameIndication_Online) {
  4073. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4074. auto host = "httpbin.org";
  4075. auto path = std::string{"/get"};
  4076. #else
  4077. auto host = "nghttp2.org";
  4078. auto path = std::string{"/httpbin/get"};
  4079. #endif
  4080. SSLClient cli(host, 443);
  4081. auto res = cli.Get(path);
  4082. ASSERT_TRUE(res);
  4083. ASSERT_EQ(200, res->status);
  4084. }
  4085. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4086. Client cli("https://google.com");
  4087. auto res = cli.Get("/");
  4088. ASSERT_TRUE(res);
  4089. ASSERT_EQ(301, res->status);
  4090. }
  4091. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4092. SSLClient cli("google.com");
  4093. cli.enable_server_certificate_verification(true);
  4094. cli.set_ca_cert_path("hello");
  4095. auto res = cli.Get("/");
  4096. ASSERT_TRUE(!res);
  4097. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4098. }
  4099. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4100. SSLClient cli("google.com");
  4101. cli.set_ca_cert_path(CA_CERT_FILE);
  4102. auto res = cli.Get("/");
  4103. ASSERT_TRUE(res);
  4104. ASSERT_EQ(301, res->status);
  4105. }
  4106. TEST(SSLClientTest, ServerCertificateVerification4) {
  4107. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4108. ASSERT_TRUE(svr.is_valid());
  4109. svr.Get("/test", [&](const Request &, Response &res) {
  4110. res.set_content("test", "text/plain");
  4111. svr.stop();
  4112. ASSERT_TRUE(true);
  4113. });
  4114. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4115. auto se = detail::scope_exit([&] {
  4116. t.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4120. SSLClient cli("127.0.0.1", PORT);
  4121. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4122. cli.enable_server_certificate_verification(true);
  4123. cli.set_connection_timeout(30);
  4124. auto res = cli.Get("/test");
  4125. ASSERT_TRUE(res);
  4126. ASSERT_EQ(200, res->status);
  4127. }
  4128. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4129. std::string cert;
  4130. detail::read_file(CA_CERT_FILE, cert);
  4131. SSLClient cli("google.com");
  4132. cli.load_ca_cert_store(cert.data(), cert.size());
  4133. const auto res = cli.Get("/");
  4134. ASSERT_TRUE(res);
  4135. ASSERT_EQ(301, res->status);
  4136. }
  4137. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4138. // clang-format off
  4139. static constexpr char cert[] =
  4140. "GlobalSign Root CA\n"
  4141. "==================\n"
  4142. "-----BEGIN CERTIFICATE-----\n"
  4143. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4144. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4145. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4146. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4147. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4148. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4149. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4150. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4151. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4152. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4153. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4154. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4155. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4156. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4157. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4158. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4159. "-----END CERTIFICATE-----\n";
  4160. // clang-format on
  4161. SSLClient cli("google.com");
  4162. cli.load_ca_cert_store(cert, sizeof(cert));
  4163. const auto res = cli.Get("/");
  4164. ASSERT_TRUE(res);
  4165. ASSERT_EQ(301, res->status);
  4166. }
  4167. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4168. SSLClient cli("www.youtube.com");
  4169. cli.set_ca_cert_path(CA_CERT_FILE);
  4170. cli.enable_server_certificate_verification(true);
  4171. cli.set_follow_location(true);
  4172. auto res = cli.Get("/");
  4173. ASSERT_TRUE(res);
  4174. ASSERT_EQ(200, res->status);
  4175. }
  4176. #if 0
  4177. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4178. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4179. ASSERT_TRUE(cli != nullptr);
  4180. cli->set_address_family(AF_INET6);
  4181. cli->set_interface("en0");
  4182. auto res = cli->Get("/get");
  4183. ASSERT_TRUE(res);
  4184. ASSERT_EQ(200, res->status);
  4185. }
  4186. #endif
  4187. TEST(SSLClientServerTest, ClientCertPresent) {
  4188. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4189. CLIENT_CA_CERT_DIR);
  4190. ASSERT_TRUE(svr.is_valid());
  4191. svr.Get("/test", [&](const Request &req, Response &res) {
  4192. res.set_content("test", "text/plain");
  4193. svr.stop();
  4194. ASSERT_TRUE(true);
  4195. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4196. ASSERT_TRUE(peer_cert != nullptr);
  4197. auto subject_name = X509_get_subject_name(peer_cert);
  4198. ASSERT_TRUE(subject_name != nullptr);
  4199. std::string common_name;
  4200. {
  4201. char name[BUFSIZ];
  4202. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4203. name, sizeof(name));
  4204. common_name.assign(name, static_cast<size_t>(name_len));
  4205. }
  4206. EXPECT_EQ("Common Name", common_name);
  4207. X509_free(peer_cert);
  4208. });
  4209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4210. auto se = detail::scope_exit([&] {
  4211. t.join();
  4212. ASSERT_FALSE(svr.is_running());
  4213. });
  4214. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4215. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4216. cli.enable_server_certificate_verification(false);
  4217. cli.set_connection_timeout(30);
  4218. auto res = cli.Get("/test");
  4219. ASSERT_TRUE(res);
  4220. ASSERT_EQ(200, res->status);
  4221. }
  4222. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4223. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4224. X509 *server_cert;
  4225. EVP_PKEY *server_private_key;
  4226. X509_STORE *client_ca_cert_store;
  4227. X509 *client_cert;
  4228. EVP_PKEY *client_private_key;
  4229. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4230. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4231. fclose(f);
  4232. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4233. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4234. fclose(f);
  4235. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4236. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4237. client_ca_cert_store = X509_STORE_new();
  4238. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4239. X509_free(client_cert);
  4240. fclose(f);
  4241. f = fopen(CLIENT_CERT_FILE, "r+");
  4242. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4243. fclose(f);
  4244. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4245. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4246. fclose(f);
  4247. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4248. ASSERT_TRUE(svr.is_valid());
  4249. svr.Get("/test", [&](const Request &req, Response &res) {
  4250. res.set_content("test", "text/plain");
  4251. svr.stop();
  4252. ASSERT_TRUE(true);
  4253. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4254. ASSERT_TRUE(peer_cert != nullptr);
  4255. auto subject_name = X509_get_subject_name(peer_cert);
  4256. ASSERT_TRUE(subject_name != nullptr);
  4257. std::string common_name;
  4258. {
  4259. char name[BUFSIZ];
  4260. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4261. name, sizeof(name));
  4262. common_name.assign(name, static_cast<size_t>(name_len));
  4263. }
  4264. EXPECT_EQ("Common Name", common_name);
  4265. X509_free(peer_cert);
  4266. });
  4267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4268. auto se = detail::scope_exit([&] {
  4269. t.join();
  4270. ASSERT_FALSE(svr.is_running());
  4271. });
  4272. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4273. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4274. cli.enable_server_certificate_verification(false);
  4275. cli.set_connection_timeout(30);
  4276. auto res = cli.Get("/test");
  4277. ASSERT_TRUE(res);
  4278. ASSERT_EQ(200, res->status);
  4279. X509_free(server_cert);
  4280. EVP_PKEY_free(server_private_key);
  4281. X509_free(client_cert);
  4282. EVP_PKEY_free(client_private_key);
  4283. }
  4284. #endif
  4285. TEST(SSLClientServerTest, ClientCertMissing) {
  4286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4287. CLIENT_CA_CERT_DIR);
  4288. ASSERT_TRUE(svr.is_valid());
  4289. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4291. auto se = detail::scope_exit([&] {
  4292. svr.stop();
  4293. t.join();
  4294. ASSERT_FALSE(svr.is_running());
  4295. });
  4296. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4297. SSLClient cli(HOST, PORT);
  4298. auto res = cli.Get("/test");
  4299. cli.set_connection_timeout(30);
  4300. ASSERT_TRUE(!res);
  4301. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4302. }
  4303. TEST(SSLClientServerTest, TrustDirOptional) {
  4304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4305. ASSERT_TRUE(svr.is_valid());
  4306. svr.Get("/test", [&](const Request &, Response &res) {
  4307. res.set_content("test", "text/plain");
  4308. svr.stop();
  4309. });
  4310. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4311. auto se = detail::scope_exit([&] {
  4312. t.join();
  4313. ASSERT_FALSE(svr.is_running());
  4314. });
  4315. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4316. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4317. cli.enable_server_certificate_verification(false);
  4318. cli.set_connection_timeout(30);
  4319. auto res = cli.Get("/test");
  4320. ASSERT_TRUE(res);
  4321. ASSERT_EQ(200, res->status);
  4322. }
  4323. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4324. class NoListenSSLServer : public SSLServer {
  4325. public:
  4326. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4327. const char *client_ca_cert_file_path,
  4328. const char *client_ca_cert_dir_path = nullptr)
  4329. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4330. client_ca_cert_dir_path),
  4331. stop_(false) {}
  4332. bool stop_;
  4333. private:
  4334. bool process_and_close_socket(socket_t /*sock*/) override {
  4335. // Don't create SSL context
  4336. while (!stop_) {
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4338. }
  4339. return true;
  4340. }
  4341. };
  4342. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4343. CLIENT_CA_CERT_FILE);
  4344. ASSERT_TRUE(svr.is_valid());
  4345. svr.Get("/test", [&](const Request &, Response &res) {
  4346. res.set_content("test", "text/plain");
  4347. });
  4348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4349. auto se = detail::scope_exit([&] {
  4350. svr.stop_ = true;
  4351. svr.stop();
  4352. t.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4356. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4357. cli.enable_server_certificate_verification(false);
  4358. cli.set_connection_timeout(1);
  4359. auto res = cli.Get("/test");
  4360. ASSERT_TRUE(!res);
  4361. EXPECT_EQ(Error::SSLConnection, res.error());
  4362. }
  4363. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4364. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4365. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4366. SSL_CTX_set_options(&ssl_ctx,
  4367. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4368. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4369. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4370. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4371. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4372. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4373. "ECDHE-DSS-AES128-SHA256:"
  4374. "ECDHE-RSA-AES256-SHA256:"
  4375. "ECDHE-DSS-AES256-SHA256:";
  4376. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4377. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4378. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4379. SSL_FILETYPE_PEM) != 1) {
  4380. return false;
  4381. }
  4382. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4383. CLIENT_CA_CERT_DIR);
  4384. SSL_CTX_set_verify(
  4385. &ssl_ctx,
  4386. SSL_VERIFY_PEER |
  4387. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4388. nullptr);
  4389. return true;
  4390. };
  4391. SSLServer svr(setup_ssl_ctx_callback);
  4392. ASSERT_TRUE(svr.is_valid());
  4393. svr.Get("/test", [&](const Request &req, Response &res) {
  4394. res.set_content("test", "text/plain");
  4395. svr.stop();
  4396. ASSERT_TRUE(true);
  4397. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4398. ASSERT_TRUE(peer_cert != nullptr);
  4399. auto subject_name = X509_get_subject_name(peer_cert);
  4400. ASSERT_TRUE(subject_name != nullptr);
  4401. std::string common_name;
  4402. {
  4403. char name[BUFSIZ];
  4404. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4405. name, sizeof(name));
  4406. common_name.assign(name, static_cast<size_t>(name_len));
  4407. }
  4408. EXPECT_EQ("Common Name", common_name);
  4409. X509_free(peer_cert);
  4410. });
  4411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4412. auto se = detail::scope_exit([&] {
  4413. t.join();
  4414. ASSERT_FALSE(svr.is_running());
  4415. });
  4416. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4417. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4418. cli.enable_server_certificate_verification(false);
  4419. cli.set_connection_timeout(30);
  4420. auto res = cli.Get("/test");
  4421. ASSERT_TRUE(res);
  4422. ASSERT_EQ(200, res->status);
  4423. }
  4424. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4425. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4426. // prepare large data
  4427. std::random_device seed_gen;
  4428. std::mt19937 random(seed_gen());
  4429. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4430. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4431. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4432. // server
  4433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4434. ASSERT_TRUE(svr.is_valid());
  4435. svr.Post("/binary", [&](const Request &req, Response &res) {
  4436. EXPECT_EQ(large_size_byte, req.body.size());
  4437. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4438. res.set_content(req.body, "application/octet-stream");
  4439. });
  4440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4441. auto se = detail::scope_exit([&] {
  4442. svr.stop();
  4443. listen_thread.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. svr.wait_until_ready();
  4447. // client POST
  4448. SSLClient cli("localhost", PORT);
  4449. cli.enable_server_certificate_verification(false);
  4450. cli.set_read_timeout(std::chrono::seconds(100));
  4451. cli.set_write_timeout(std::chrono::seconds(100));
  4452. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4453. large_size_byte, "application/octet-stream");
  4454. // compare
  4455. EXPECT_EQ(200, res->status);
  4456. EXPECT_EQ(large_size_byte, res->body.size());
  4457. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4458. }
  4459. #endif
  4460. #ifdef _WIN32
  4461. TEST(CleanupTest, WSACleanup) {
  4462. int ret = WSACleanup();
  4463. ASSERT_EQ(0, ret);
  4464. }
  4465. #endif
  4466. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4467. TEST(NoSSLSupport, SimpleInterface) {
  4468. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4469. }
  4470. #endif
  4471. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4472. TEST(InvalidScheme, SimpleInterface) {
  4473. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4474. }
  4475. #endif
  4476. TEST(NoScheme, SimpleInterface) {
  4477. Client cli("yahoo.com:80");
  4478. ASSERT_TRUE(cli.is_valid());
  4479. }
  4480. TEST(SendAPI, SimpleInterface_Online) {
  4481. Client cli("http://yahoo.com");
  4482. Request req;
  4483. req.method = "GET";
  4484. req.path = "/";
  4485. auto res = cli.send(req);
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(301, res->status);
  4488. }
  4489. TEST(ClientImplMethods, GetSocketTest) {
  4490. httplib::Server svr;
  4491. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4492. res.status = 200;
  4493. });
  4494. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4495. auto se = detail::scope_exit([&] {
  4496. svr.stop();
  4497. thread.join();
  4498. ASSERT_FALSE(svr.is_running());
  4499. });
  4500. svr.wait_until_ready();
  4501. {
  4502. httplib::Client cli("http://127.0.0.1:3333");
  4503. cli.set_keep_alive(true);
  4504. // Use the behavior of cpp-httplib of opening the connection
  4505. // only when the first request happens. If that changes,
  4506. // this test would be obsolete.
  4507. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4508. // This also implicitly tests the server. But other tests would fail much
  4509. // earlier than this one to be considered.
  4510. auto res = cli.Get("/");
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(200, res->status);
  4513. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4514. }
  4515. }
  4516. // Disabled due to out-of-memory problem on GitHub Actions
  4517. #ifdef _WIN64
  4518. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4519. // allocate content size larger than 2GB in memory
  4520. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4521. char *content = (char *)malloc(content_size);
  4522. ASSERT_TRUE(content);
  4523. Server svr;
  4524. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4525. resp.set_content(content, content_size, "application/octet-stream");
  4526. });
  4527. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4528. auto se = detail::scope_exit([&] {
  4529. svr.stop();
  4530. listen_thread.join();
  4531. if (content) free(content);
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. // Give GET time to get a few messages.
  4536. std::this_thread::sleep_for(std::chrono::seconds(1));
  4537. Client cli(HOST, PORT);
  4538. auto res = cli.Get("/foo");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(200, res->status);
  4541. EXPECT_EQ(content_size, res->body.length());
  4542. }
  4543. #endif
  4544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4545. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4546. Client cli("http://yahoo.com");
  4547. auto res = cli.Get("/");
  4548. ASSERT_TRUE(res);
  4549. EXPECT_EQ(301, res->status);
  4550. cli.set_follow_location(true);
  4551. res = cli.Get("/");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(200, res->status);
  4554. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4555. }
  4556. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4557. Client cli("https://yahoo.com");
  4558. auto res = cli.Get("/");
  4559. ASSERT_TRUE(res);
  4560. EXPECT_EQ(301, res->status);
  4561. cli.set_follow_location(true);
  4562. res = cli.Get("/");
  4563. ASSERT_TRUE(res);
  4564. EXPECT_EQ(200, res->status);
  4565. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4566. }
  4567. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4568. Client cli("https://yahoo.com");
  4569. auto res = cli.Get("/");
  4570. ASSERT_TRUE(res);
  4571. ASSERT_FALSE(!res);
  4572. ASSERT_TRUE(res);
  4573. ASSERT_FALSE(res == nullptr);
  4574. ASSERT_TRUE(res != nullptr);
  4575. EXPECT_EQ(Error::Success, res.error());
  4576. EXPECT_EQ(301, res.value().status);
  4577. EXPECT_EQ(301, (*res).status);
  4578. EXPECT_EQ(301, res->status);
  4579. cli.set_follow_location(true);
  4580. res = cli.Get("/");
  4581. ASSERT_TRUE(res);
  4582. EXPECT_EQ(Error::Success, res.error());
  4583. EXPECT_EQ(200, res.value().status);
  4584. EXPECT_EQ(200, (*res).status);
  4585. EXPECT_EQ(200, res->status);
  4586. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4587. }
  4588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4589. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4590. Client cli("https://cdnjs.cloudflare.com");
  4591. auto res =
  4592. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(200, res->status);
  4595. EXPECT_EQ(287630U, res->body.size());
  4596. EXPECT_EQ("application/javascript; charset=utf-8",
  4597. res->get_header_value("Content-Type"));
  4598. }
  4599. #endif
  4600. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4601. Client cli("https://nghttp2.org");
  4602. cli.set_follow_location(true);
  4603. auto res =
  4604. cli.Get("/httpbin/"
  4605. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(200, res->status);
  4608. }
  4609. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4610. Client cli("https://nghttp2.org");
  4611. cli.set_follow_location(true);
  4612. Params params;
  4613. params.emplace("url", "http://www.google.com");
  4614. params.emplace("status_code", "302");
  4615. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4616. ASSERT_TRUE(res);
  4617. EXPECT_EQ(200, res->status);
  4618. }
  4619. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4620. Client cli("https://nghttp2.org");
  4621. cli.set_follow_location(true);
  4622. Params params;
  4623. params.emplace("url", "http://www.google.com");
  4624. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4625. ASSERT_TRUE(res);
  4626. EXPECT_EQ(200, res->status);
  4627. }
  4628. TEST(HttpToHttpsRedirectTest, CertFile) {
  4629. Server svr;
  4630. ASSERT_TRUE(svr.is_valid());
  4631. svr.Get("/index", [&](const Request &, Response &res) {
  4632. res.set_redirect("https://127.0.0.1:1235/index");
  4633. svr.stop();
  4634. });
  4635. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4636. ASSERT_TRUE(ssl_svr.is_valid());
  4637. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4638. res.set_content("test", "text/plain");
  4639. ssl_svr.stop();
  4640. });
  4641. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4642. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4643. auto se = detail::scope_exit([&] {
  4644. t2.join();
  4645. t.join();
  4646. ASSERT_FALSE(svr.is_running());
  4647. });
  4648. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4649. Client cli("127.0.0.1", PORT);
  4650. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4651. cli.enable_server_certificate_verification(true);
  4652. cli.set_follow_location(true);
  4653. cli.set_connection_timeout(30);
  4654. auto res = cli.Get("/index");
  4655. ASSERT_TRUE(res);
  4656. ASSERT_EQ(200, res->status);
  4657. }
  4658. TEST(MultipartFormDataTest, LargeData) {
  4659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4660. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4661. const ContentReader &content_reader) {
  4662. if (req.is_multipart_form_data()) {
  4663. MultipartFormDataItems files;
  4664. content_reader(
  4665. [&](const MultipartFormData &file) {
  4666. files.push_back(file);
  4667. return true;
  4668. },
  4669. [&](const char *data, size_t data_length) {
  4670. files.back().content.append(data, data_length);
  4671. return true;
  4672. });
  4673. EXPECT_TRUE(std::string(files[0].name) == "document");
  4674. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4675. EXPECT_TRUE(files[0].filename == "2MB_data");
  4676. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4677. EXPECT_TRUE(files[1].name == "hello");
  4678. EXPECT_TRUE(files[1].content == "world");
  4679. EXPECT_TRUE(files[1].filename == "");
  4680. EXPECT_TRUE(files[1].content_type == "");
  4681. } else {
  4682. std::string body;
  4683. content_reader([&](const char *data, size_t data_length) {
  4684. body.append(data, data_length);
  4685. return true;
  4686. });
  4687. }
  4688. });
  4689. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. t.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. std::this_thread::sleep_for(std::chrono::seconds(1));
  4697. {
  4698. std::string data(1024 * 1024 * 2, '.');
  4699. std::stringstream buffer;
  4700. buffer << data;
  4701. Client cli("https://localhost:8080");
  4702. cli.enable_server_certificate_verification(false);
  4703. MultipartFormDataItems items{
  4704. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4705. {"hello", "world", "", ""},
  4706. };
  4707. auto res = cli.Post("/post", items);
  4708. ASSERT_TRUE(res);
  4709. ASSERT_EQ(200, res->status);
  4710. }
  4711. }
  4712. TEST(MultipartFormDataTest, DataProviderItems) {
  4713. std::random_device seed_gen;
  4714. std::mt19937 random(seed_gen());
  4715. std::string rand1;
  4716. rand1.resize(1000);
  4717. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4718. std::string rand2;
  4719. rand2.resize(3000);
  4720. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4722. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4723. const ContentReader &content_reader) {
  4724. ASSERT_FALSE(req.is_multipart_form_data());
  4725. std::string body;
  4726. content_reader([&](const char *data, size_t data_length) {
  4727. body.append(data, data_length);
  4728. return true;
  4729. });
  4730. EXPECT_EQ(body, "");
  4731. });
  4732. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4733. const ContentReader &content_reader) {
  4734. ASSERT_TRUE(req.is_multipart_form_data());
  4735. MultipartFormDataItems files;
  4736. content_reader(
  4737. [&](const MultipartFormData &file) {
  4738. files.push_back(file);
  4739. return true;
  4740. },
  4741. [&](const char *data, size_t data_length) {
  4742. files.back().content.append(data, data_length);
  4743. return true;
  4744. });
  4745. ASSERT_TRUE(files.size() == 2);
  4746. EXPECT_EQ(std::string(files[0].name), "name1");
  4747. EXPECT_EQ(files[0].content, "Testing123");
  4748. EXPECT_EQ(files[0].filename, "filename1");
  4749. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4750. EXPECT_EQ(files[1].name, "name2");
  4751. EXPECT_EQ(files[1].content, "Testing456");
  4752. EXPECT_EQ(files[1].filename, "");
  4753. EXPECT_EQ(files[1].content_type, "");
  4754. });
  4755. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4756. const ContentReader &content_reader) {
  4757. ASSERT_TRUE(req.is_multipart_form_data());
  4758. MultipartFormDataItems files;
  4759. content_reader(
  4760. [&](const MultipartFormData &file) {
  4761. files.push_back(file);
  4762. return true;
  4763. },
  4764. [&](const char *data, size_t data_length) {
  4765. files.back().content.append(data, data_length);
  4766. return true;
  4767. });
  4768. ASSERT_TRUE(files.size() == 2);
  4769. EXPECT_EQ(files[0].name, "name3");
  4770. EXPECT_EQ(files[0].content, rand1);
  4771. EXPECT_EQ(files[0].filename, "filename3");
  4772. EXPECT_EQ(files[0].content_type, "");
  4773. EXPECT_EQ(files[1].name, "name4");
  4774. EXPECT_EQ(files[1].content, rand2);
  4775. EXPECT_EQ(files[1].filename, "filename4");
  4776. EXPECT_EQ(files[1].content_type, "");
  4777. });
  4778. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4779. const ContentReader &content_reader) {
  4780. ASSERT_TRUE(req.is_multipart_form_data());
  4781. MultipartFormDataItems files;
  4782. content_reader(
  4783. [&](const MultipartFormData &file) {
  4784. files.push_back(file);
  4785. return true;
  4786. },
  4787. [&](const char *data, size_t data_length) {
  4788. files.back().content.append(data, data_length);
  4789. return true;
  4790. });
  4791. ASSERT_TRUE(files.size() == 4);
  4792. EXPECT_EQ(std::string(files[0].name), "name1");
  4793. EXPECT_EQ(files[0].content, "Testing123");
  4794. EXPECT_EQ(files[0].filename, "filename1");
  4795. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4796. EXPECT_EQ(files[1].name, "name2");
  4797. EXPECT_EQ(files[1].content, "Testing456");
  4798. EXPECT_EQ(files[1].filename, "");
  4799. EXPECT_EQ(files[1].content_type, "");
  4800. EXPECT_EQ(files[2].name, "name3");
  4801. EXPECT_EQ(files[2].content, rand1);
  4802. EXPECT_EQ(files[2].filename, "filename3");
  4803. EXPECT_EQ(files[2].content_type, "");
  4804. EXPECT_EQ(files[3].name, "name4");
  4805. EXPECT_EQ(files[3].content, rand2);
  4806. EXPECT_EQ(files[3].filename, "filename4");
  4807. EXPECT_EQ(files[3].content_type, "");
  4808. });
  4809. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4810. auto se = detail::scope_exit([&] {
  4811. svr.stop();
  4812. t.join();
  4813. ASSERT_FALSE(svr.is_running());
  4814. });
  4815. svr.wait_until_ready();
  4816. std::this_thread::sleep_for(std::chrono::seconds(1));
  4817. {
  4818. Client cli("https://localhost:8080");
  4819. cli.enable_server_certificate_verification(false);
  4820. MultipartFormDataItems items{
  4821. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4822. {"name2", "Testing456", "", ""}, // not a file
  4823. };
  4824. {
  4825. auto res = cli.Post("/post-none", {}, {}, {});
  4826. ASSERT_TRUE(res);
  4827. ASSERT_EQ(200, res->status);
  4828. }
  4829. MultipartFormDataProviderItems providers;
  4830. {
  4831. auto res =
  4832. cli.Post("/post-items", {}, items, providers); // empty providers
  4833. ASSERT_TRUE(res);
  4834. ASSERT_EQ(200, res->status);
  4835. }
  4836. providers.push_back({"name3",
  4837. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4838. // test the offset is given correctly at each step
  4839. if (!offset)
  4840. sink.os.write(rand1.data(), 30);
  4841. else if (offset == 30)
  4842. sink.os.write(rand1.data() + 30, 300);
  4843. else if (offset == 330)
  4844. sink.os.write(rand1.data() + 330, 670);
  4845. else if (offset == rand1.size())
  4846. sink.done();
  4847. return true;
  4848. },
  4849. "filename3",
  4850. {}});
  4851. providers.push_back({"name4",
  4852. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4853. // test the offset is given correctly at each step
  4854. if (!offset)
  4855. sink.os.write(rand2.data(), 2000);
  4856. else if (offset == 2000)
  4857. sink.os.write(rand2.data() + 2000, 1);
  4858. else if (offset == 2001)
  4859. sink.os.write(rand2.data() + 2001, 999);
  4860. else if (offset == rand2.size())
  4861. sink.done();
  4862. return true;
  4863. },
  4864. "filename4",
  4865. {}});
  4866. {
  4867. auto res = cli.Post("/post-providers", {}, {}, providers);
  4868. ASSERT_TRUE(res);
  4869. ASSERT_EQ(200, res->status);
  4870. }
  4871. {
  4872. auto res = cli.Post("/post-both", {}, items, providers);
  4873. ASSERT_TRUE(res);
  4874. ASSERT_EQ(200, res->status);
  4875. }
  4876. }
  4877. }
  4878. TEST(MultipartFormDataTest, BadHeader) {
  4879. Server svr;
  4880. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4881. res.set_content("ok", "text/plain");
  4882. });
  4883. thread t = thread([&] { svr.listen(HOST, PORT); });
  4884. auto se = detail::scope_exit([&] {
  4885. svr.stop();
  4886. t.join();
  4887. ASSERT_FALSE(svr.is_running());
  4888. });
  4889. svr.wait_until_ready();
  4890. const std::string body =
  4891. "This is the preamble. It is to be ignored, though it\r\n"
  4892. "is a handy place for composition agents to include an\r\n"
  4893. "explanatory note to non-MIME conformant readers.\r\n"
  4894. "\r\n"
  4895. "\r\n"
  4896. "--simple boundary\r\n"
  4897. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4898. ": BAD...\r\n"
  4899. "\r\n"
  4900. "value1\r\n"
  4901. "--simple boundary\r\n"
  4902. "Content-Disposition: form-data; name=\"field2\"; "
  4903. "filename=\"example.txt\"\r\n"
  4904. "\r\n"
  4905. "value2\r\n"
  4906. "--simple boundary--\r\n"
  4907. "This is the epilogue. It is also to be ignored.\r\n";
  4908. std::string content_type =
  4909. R"(multipart/form-data; boundary="simple boundary")";
  4910. Client cli(HOST, PORT);
  4911. auto res = cli.Post("/post", body, content_type.c_str());
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(400, res->status);
  4914. }
  4915. TEST(MultipartFormDataTest, WithPreamble) {
  4916. Server svr;
  4917. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4918. res.set_content("ok", "text/plain");
  4919. });
  4920. thread t = thread([&] { svr.listen(HOST, PORT); });
  4921. auto se = detail::scope_exit([&] {
  4922. svr.stop();
  4923. t.join();
  4924. ASSERT_FALSE(svr.is_running());
  4925. });
  4926. svr.wait_until_ready();
  4927. const std::string body =
  4928. "This is the preamble. It is to be ignored, though it\r\n"
  4929. "is a handy place for composition agents to include an\r\n"
  4930. "explanatory note to non-MIME conformant readers.\r\n"
  4931. "\r\n"
  4932. "\r\n"
  4933. "--simple boundary\r\n"
  4934. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4935. "\r\n"
  4936. "value1\r\n"
  4937. "--simple boundary\r\n"
  4938. "Content-Disposition: form-data; name=\"field2\"; "
  4939. "filename=\"example.txt\"\r\n"
  4940. "\r\n"
  4941. "value2\r\n"
  4942. "--simple boundary--\r\n"
  4943. "This is the epilogue. It is also to be ignored.\r\n";
  4944. std::string content_type =
  4945. R"(multipart/form-data; boundary="simple boundary")";
  4946. Client cli(HOST, PORT);
  4947. auto res = cli.Post("/post", body, content_type.c_str());
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(200, res->status);
  4950. }
  4951. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4952. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4953. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4954. const ContentReader &content_reader) {
  4955. if (req.is_multipart_form_data()) {
  4956. MultipartFormDataItems files;
  4957. content_reader(
  4958. [&](const MultipartFormData &file) {
  4959. files.push_back(file);
  4960. return true;
  4961. },
  4962. [&](const char *data, size_t data_length) {
  4963. files.back().content.append(data, data_length);
  4964. return true;
  4965. });
  4966. EXPECT_TRUE(std::string(files[0].name) == "document");
  4967. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4968. EXPECT_TRUE(files[0].filename == "2MB_data");
  4969. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4970. EXPECT_TRUE(files[1].name == "hello");
  4971. EXPECT_TRUE(files[1].content == "world");
  4972. EXPECT_TRUE(files[1].filename == "");
  4973. EXPECT_TRUE(files[1].content_type == "");
  4974. } else {
  4975. std::string body;
  4976. content_reader([&](const char *data, size_t data_length) {
  4977. body.append(data, data_length);
  4978. return true;
  4979. });
  4980. }
  4981. });
  4982. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4983. auto se = detail::scope_exit([&] {
  4984. svr.stop();
  4985. t.join();
  4986. ASSERT_FALSE(svr.is_running());
  4987. });
  4988. svr.wait_until_ready();
  4989. std::this_thread::sleep_for(std::chrono::seconds(1));
  4990. {
  4991. std::string data(1024 * 1024 * 2, '.');
  4992. std::stringstream buffer;
  4993. buffer << data;
  4994. Client cli("https://localhost:8080");
  4995. cli.enable_server_certificate_verification(false);
  4996. MultipartFormDataItems items{
  4997. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4998. {"hello", "world", "", ""},
  4999. };
  5000. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5001. ASSERT_TRUE(res);
  5002. ASSERT_EQ(200, res->status);
  5003. }
  5004. }
  5005. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5006. std::this_thread::sleep_for(std::chrono::seconds(1));
  5007. std::string data(1024 * 1024 * 2, '&');
  5008. std::stringstream buffer;
  5009. buffer << data;
  5010. Client cli("https://localhost:8080");
  5011. MultipartFormDataItems items{
  5012. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5013. {"hello", "world", "", ""},
  5014. };
  5015. for (const char &c : " \t\r\n") {
  5016. auto res =
  5017. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5018. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5019. ASSERT_FALSE(res);
  5020. }
  5021. }
  5022. TEST(MultipartFormDataTest, PutFormData) {
  5023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5024. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5025. const ContentReader &content_reader) {
  5026. if (req.is_multipart_form_data()) {
  5027. MultipartFormDataItems files;
  5028. content_reader(
  5029. [&](const MultipartFormData &file) {
  5030. files.push_back(file);
  5031. return true;
  5032. },
  5033. [&](const char *data, size_t data_length) {
  5034. files.back().content.append(data, data_length);
  5035. return true;
  5036. });
  5037. EXPECT_TRUE(std::string(files[0].name) == "document");
  5038. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5039. EXPECT_TRUE(files[0].filename == "2MB_data");
  5040. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5041. EXPECT_TRUE(files[1].name == "hello");
  5042. EXPECT_TRUE(files[1].content == "world");
  5043. EXPECT_TRUE(files[1].filename == "");
  5044. EXPECT_TRUE(files[1].content_type == "");
  5045. } else {
  5046. std::string body;
  5047. content_reader([&](const char *data, size_t data_length) {
  5048. body.append(data, data_length);
  5049. return true;
  5050. });
  5051. }
  5052. });
  5053. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5054. auto se = detail::scope_exit([&] {
  5055. svr.stop();
  5056. t.join();
  5057. ASSERT_FALSE(svr.is_running());
  5058. });
  5059. svr.wait_until_ready();
  5060. std::this_thread::sleep_for(std::chrono::seconds(1));
  5061. {
  5062. std::string data(1024 * 1024 * 2, '&');
  5063. std::stringstream buffer;
  5064. buffer << data;
  5065. Client cli("https://localhost:8080");
  5066. cli.enable_server_certificate_verification(false);
  5067. MultipartFormDataItems items{
  5068. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5069. {"hello", "world", "", ""},
  5070. };
  5071. auto res = cli.Put("/put", items);
  5072. ASSERT_TRUE(res);
  5073. ASSERT_EQ(200, res->status);
  5074. }
  5075. }
  5076. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5078. svr.Put("/put_customboundary",
  5079. [&](const Request &req, const Response & /*res*/,
  5080. const ContentReader &content_reader) {
  5081. if (req.is_multipart_form_data()) {
  5082. MultipartFormDataItems files;
  5083. content_reader(
  5084. [&](const MultipartFormData &file) {
  5085. files.push_back(file);
  5086. return true;
  5087. },
  5088. [&](const char *data, size_t data_length) {
  5089. files.back().content.append(data, data_length);
  5090. return true;
  5091. });
  5092. EXPECT_TRUE(std::string(files[0].name) == "document");
  5093. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5094. EXPECT_TRUE(files[0].filename == "2MB_data");
  5095. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5096. EXPECT_TRUE(files[1].name == "hello");
  5097. EXPECT_TRUE(files[1].content == "world");
  5098. EXPECT_TRUE(files[1].filename == "");
  5099. EXPECT_TRUE(files[1].content_type == "");
  5100. } else {
  5101. std::string body;
  5102. content_reader([&](const char *data, size_t data_length) {
  5103. body.append(data, data_length);
  5104. return true;
  5105. });
  5106. }
  5107. });
  5108. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5109. auto se = detail::scope_exit([&] {
  5110. svr.stop();
  5111. t.join();
  5112. ASSERT_FALSE(svr.is_running());
  5113. });
  5114. svr.wait_until_ready();
  5115. std::this_thread::sleep_for(std::chrono::seconds(1));
  5116. {
  5117. std::string data(1024 * 1024 * 2, '&');
  5118. std::stringstream buffer;
  5119. buffer << data;
  5120. Client cli("https://localhost:8080");
  5121. cli.enable_server_certificate_verification(false);
  5122. MultipartFormDataItems items{
  5123. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5124. {"hello", "world", "", ""},
  5125. };
  5126. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5127. ASSERT_TRUE(res);
  5128. ASSERT_EQ(200, res->status);
  5129. }
  5130. }
  5131. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5132. std::this_thread::sleep_for(std::chrono::seconds(1));
  5133. std::string data(1024 * 1024 * 2, '&');
  5134. std::stringstream buffer;
  5135. buffer << data;
  5136. Client cli("https://localhost:8080");
  5137. cli.enable_server_certificate_verification(false);
  5138. MultipartFormDataItems items{
  5139. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5140. {"hello", "world", "", ""},
  5141. };
  5142. for (const char &c : " \t\r\n") {
  5143. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5144. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5145. ASSERT_FALSE(res);
  5146. }
  5147. }
  5148. TEST(MultipartFormDataTest, AlternateFilename) {
  5149. auto handled = false;
  5150. Server svr;
  5151. svr.Post("/test", [&](const Request &req, Response &res) {
  5152. ASSERT_EQ(3u, req.files.size());
  5153. auto it = req.files.begin();
  5154. ASSERT_EQ("file1", it->second.name);
  5155. ASSERT_EQ("A.txt", it->second.filename);
  5156. ASSERT_EQ("text/plain", it->second.content_type);
  5157. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5158. ++it;
  5159. ASSERT_EQ("file2", it->second.name);
  5160. ASSERT_EQ("a.html", it->second.filename);
  5161. ASSERT_EQ("text/html", it->second.content_type);
  5162. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5163. it->second.content);
  5164. ++it;
  5165. ASSERT_EQ("text", it->second.name);
  5166. ASSERT_EQ("", it->second.filename);
  5167. ASSERT_EQ("", it->second.content_type);
  5168. ASSERT_EQ("text default", it->second.content);
  5169. res.set_content("ok", "text/plain");
  5170. handled = true;
  5171. });
  5172. thread t = thread([&] { svr.listen(HOST, PORT); });
  5173. auto se = detail::scope_exit([&] {
  5174. svr.stop();
  5175. t.join();
  5176. ASSERT_FALSE(svr.is_running());
  5177. ASSERT_TRUE(handled);
  5178. });
  5179. svr.wait_until_ready();
  5180. auto req = "POST /test HTTP/1.1\r\n"
  5181. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5182. "Content-Length: 399\r\n"
  5183. "\r\n"
  5184. "----------\r\n"
  5185. "Content-Disposition: form-data; name=\"text\"\r\n"
  5186. "\r\n"
  5187. "text default\r\n"
  5188. "----------\r\n"
  5189. "Content-Disposition: form-data; filename*=\"UTF-8''\%41.txt\"; "
  5190. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5191. "Content-Type: text/plain\r\n"
  5192. "\r\n"
  5193. "Content of a.txt.\r\n"
  5194. "\r\n"
  5195. "----------\r\n"
  5196. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5197. "\"a.html\"\r\n"
  5198. "Content-Type: text/html\r\n"
  5199. "\r\n"
  5200. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5201. "\r\n"
  5202. "------------\r\n";
  5203. ASSERT_TRUE(send_request(1, req));
  5204. }
  5205. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5206. auto handled = false;
  5207. Server svr;
  5208. svr.Post("/test", [&](const Request &req, Response &) {
  5209. ASSERT_EQ(2u, req.files.size());
  5210. auto it = req.files.begin();
  5211. ASSERT_EQ("text1", it->second.name);
  5212. ASSERT_EQ("text1", it->second.content);
  5213. ++it;
  5214. ASSERT_EQ("text2", it->second.name);
  5215. ASSERT_EQ("text2", it->second.content);
  5216. handled = true;
  5217. });
  5218. thread t = thread([&] { svr.listen(HOST, PORT); });
  5219. auto se = detail::scope_exit([&] {
  5220. svr.stop();
  5221. t.join();
  5222. ASSERT_FALSE(svr.is_running());
  5223. ASSERT_TRUE(handled);
  5224. });
  5225. svr.wait_until_ready();
  5226. auto req = "POST /test HTTP/1.1\r\n"
  5227. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5228. "Content-Length: 146\r\n"
  5229. "\r\n----------\r\n"
  5230. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5231. "\r\n"
  5232. "text1"
  5233. "\r\n----------\r\n"
  5234. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5235. "\r\n"
  5236. "text2"
  5237. "\r\n------------";
  5238. std::string resonse;
  5239. ASSERT_TRUE(send_request(1, req, &resonse));
  5240. ASSERT_EQ("200", resonse.substr(9, 3));
  5241. }
  5242. #endif
  5243. #ifndef _WIN32
  5244. class UnixSocketTest : public ::testing::Test {
  5245. protected:
  5246. void TearDown() override { std::remove(pathname_.c_str()); }
  5247. void client_GET(const std::string &addr) {
  5248. httplib::Client cli{addr};
  5249. cli.set_address_family(AF_UNIX);
  5250. ASSERT_TRUE(cli.is_valid());
  5251. const auto &result = cli.Get(pattern_);
  5252. ASSERT_TRUE(result) << "error: " << result.error();
  5253. const auto &resp = result.value();
  5254. EXPECT_EQ(resp.status, 200);
  5255. EXPECT_EQ(resp.body, content_);
  5256. }
  5257. const std::string pathname_{"./httplib-server.sock"};
  5258. const std::string pattern_{"/hi"};
  5259. const std::string content_{"Hello World!"};
  5260. };
  5261. TEST_F(UnixSocketTest, pathname) {
  5262. httplib::Server svr;
  5263. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5264. res.set_content(content_, "text/plain");
  5265. });
  5266. std::thread t{[&] {
  5267. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5268. }};
  5269. auto se = detail::scope_exit([&] {
  5270. svr.stop();
  5271. t.join();
  5272. ASSERT_FALSE(svr.is_running());
  5273. });
  5274. svr.wait_until_ready();
  5275. ASSERT_TRUE(svr.is_running());
  5276. client_GET(pathname_);
  5277. }
  5278. #if defined(__linux__) || \
  5279. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5280. TEST_F(UnixSocketTest, PeerPid) {
  5281. httplib::Server svr;
  5282. std::string remote_port_val;
  5283. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5284. res.set_content(content_, "text/plain");
  5285. remote_port_val = req.get_header_value("REMOTE_PORT");
  5286. });
  5287. std::thread t{[&] {
  5288. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5289. }};
  5290. auto se = detail::scope_exit([&] {
  5291. svr.stop();
  5292. t.join();
  5293. ASSERT_FALSE(svr.is_running());
  5294. });
  5295. svr.wait_until_ready();
  5296. ASSERT_TRUE(svr.is_running());
  5297. client_GET(pathname_);
  5298. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5299. }
  5300. #endif
  5301. #ifdef __linux__
  5302. TEST_F(UnixSocketTest, abstract) {
  5303. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5304. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5305. httplib::Server svr;
  5306. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5307. res.set_content(content_, "text/plain");
  5308. });
  5309. std::thread t{[&] {
  5310. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5311. }};
  5312. auto se = detail::scope_exit([&] {
  5313. svr.stop();
  5314. t.join();
  5315. ASSERT_FALSE(svr.is_running());
  5316. });
  5317. svr.wait_until_ready();
  5318. ASSERT_TRUE(svr.is_running());
  5319. client_GET(abstract_addr);
  5320. }
  5321. #endif
  5322. TEST(SocketStream, is_writable_UNIX) {
  5323. int fds[2];
  5324. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5325. const auto asSocketStream = [&](socket_t fd,
  5326. std::function<bool(Stream &)> func) {
  5327. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5328. };
  5329. asSocketStream(fds[0], [&](Stream &s0) {
  5330. EXPECT_EQ(s0.socket(), fds[0]);
  5331. EXPECT_TRUE(s0.is_writable());
  5332. EXPECT_EQ(0, close(fds[1]));
  5333. EXPECT_FALSE(s0.is_writable());
  5334. return true;
  5335. });
  5336. EXPECT_EQ(0, close(fds[0]));
  5337. }
  5338. TEST(SocketStream, is_writable_INET) {
  5339. sockaddr_in addr;
  5340. memset(&addr, 0, sizeof(addr));
  5341. addr.sin_family = AF_INET;
  5342. addr.sin_port = htons(PORT + 1);
  5343. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5344. int disconnected_svr_sock = -1;
  5345. std::thread svr{[&] {
  5346. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5347. ASSERT_LE(0, s);
  5348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5349. ASSERT_EQ(0, listen(s, 1));
  5350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5351. ASSERT_EQ(0, close(s));
  5352. }};
  5353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5354. std::thread cli{[&] {
  5355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5356. ASSERT_LE(0, s);
  5357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5358. ASSERT_EQ(0, close(s));
  5359. }};
  5360. cli.join();
  5361. svr.join();
  5362. ASSERT_NE(disconnected_svr_sock, -1);
  5363. const auto asSocketStream = [&](socket_t fd,
  5364. std::function<bool(Stream &)> func) {
  5365. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5366. };
  5367. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5368. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5369. EXPECT_FALSE(ss.is_writable());
  5370. return true;
  5371. });
  5372. ASSERT_EQ(0, close(disconnected_svr_sock));
  5373. }
  5374. #endif // #ifndef _WIN32
  5375. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5376. static constexpr unsigned int number_of_task{1000000};
  5377. std::atomic_uint count{0};
  5378. std::unique_ptr<TaskQueue> task_queue{
  5379. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5380. for (unsigned int i = 0; i < number_of_task; ++i) {
  5381. task_queue->enqueue(
  5382. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5383. }
  5384. EXPECT_NO_THROW(task_queue->shutdown());
  5385. EXPECT_EQ(number_of_task, count.load());
  5386. }
  5387. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5388. Server svr;
  5389. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5390. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5391. });
  5392. svr.Get("/hello", [](const Request &req, Response &res) {
  5393. res.set_content(req.get_param_value("key"), "text/plain");
  5394. });
  5395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5396. auto se = detail::scope_exit([&] {
  5397. svr.stop();
  5398. thread.join();
  5399. ASSERT_FALSE(svr.is_running());
  5400. });
  5401. std::this_thread::sleep_for(std::chrono::seconds(1));
  5402. {
  5403. Client cli(HOST, PORT);
  5404. cli.set_follow_location(true);
  5405. auto res = cli.Get("/");
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(200, res->status);
  5408. EXPECT_EQ("val&key2=val2", res->body);
  5409. }
  5410. }
  5411. TEST(VulnerabilityTest, CRLFInjection) {
  5412. Server svr;
  5413. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  5414. res.set_content("Hello 1", "text/plain");
  5415. });
  5416. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  5417. res.set_content("Hello 2", "text/plain");
  5418. });
  5419. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  5420. res.set_content("Hello 3", "text/plain");
  5421. });
  5422. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  5423. res.set_content("Hello 4", "text/plain");
  5424. });
  5425. svr.set_logger([](const Request &req, const Response & /*res*/) {
  5426. for (const auto &x : req.headers) {
  5427. auto key = x.first;
  5428. EXPECT_STRNE("evil", key.c_str());
  5429. }
  5430. });
  5431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5432. auto se = detail::scope_exit([&] {
  5433. svr.stop();
  5434. thread.join();
  5435. ASSERT_FALSE(svr.is_running());
  5436. });
  5437. std::this_thread::sleep_for(std::chrono::seconds(1));
  5438. {
  5439. Client cli(HOST, PORT);
  5440. cli.Post("/test1", "A=B",
  5441. "application/x-www-form-urlencoded\r\nevil: hello1");
  5442. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  5443. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  5444. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  5445. }
  5446. }
  5447. TEST(PathParamsTest, StaticMatch) {
  5448. const auto pattern = "/users/all";
  5449. detail::PathParamsMatcher matcher(pattern);
  5450. Request request;
  5451. request.path = "/users/all";
  5452. ASSERT_TRUE(matcher.match(request));
  5453. std::unordered_map<std::string, std::string> expected_params = {};
  5454. EXPECT_EQ(request.path_params, expected_params);
  5455. }
  5456. TEST(PathParamsTest, StaticMismatch) {
  5457. const auto pattern = "/users/all";
  5458. detail::PathParamsMatcher matcher(pattern);
  5459. Request request;
  5460. request.path = "/users/1";
  5461. ASSERT_FALSE(matcher.match(request));
  5462. }
  5463. TEST(PathParamsTest, SingleParamInTheMiddle) {
  5464. const auto pattern = "/users/:id/subscriptions";
  5465. detail::PathParamsMatcher matcher(pattern);
  5466. Request request;
  5467. request.path = "/users/42/subscriptions";
  5468. ASSERT_TRUE(matcher.match(request));
  5469. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5470. EXPECT_EQ(request.path_params, expected_params);
  5471. }
  5472. TEST(PathParamsTest, SingleParamInTheEnd) {
  5473. const auto pattern = "/users/:id";
  5474. detail::PathParamsMatcher matcher(pattern);
  5475. Request request;
  5476. request.path = "/users/24";
  5477. ASSERT_TRUE(matcher.match(request));
  5478. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  5479. EXPECT_EQ(request.path_params, expected_params);
  5480. }
  5481. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  5482. const auto pattern = "/users/:id/";
  5483. detail::PathParamsMatcher matcher(pattern);
  5484. Request request;
  5485. request.path = "/users/42/";
  5486. ASSERT_TRUE(matcher.match(request));
  5487. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5488. EXPECT_EQ(request.path_params, expected_params);
  5489. }
  5490. TEST(PathParamsTest, EmptyParam) {
  5491. const auto pattern = "/users/:id/";
  5492. detail::PathParamsMatcher matcher(pattern);
  5493. Request request;
  5494. request.path = "/users//";
  5495. ASSERT_TRUE(matcher.match(request));
  5496. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  5497. EXPECT_EQ(request.path_params, expected_params);
  5498. }
  5499. TEST(PathParamsTest, FragmentMismatch) {
  5500. const auto pattern = "/users/:id/";
  5501. detail::PathParamsMatcher matcher(pattern);
  5502. Request request;
  5503. request.path = "/admins/24/";
  5504. ASSERT_FALSE(matcher.match(request));
  5505. }
  5506. TEST(PathParamsTest, ExtraFragments) {
  5507. const auto pattern = "/users/:id";
  5508. detail::PathParamsMatcher matcher(pattern);
  5509. Request request;
  5510. request.path = "/users/42/subscriptions";
  5511. ASSERT_FALSE(matcher.match(request));
  5512. }
  5513. TEST(PathParamsTest, MissingTrailingParam) {
  5514. const auto pattern = "/users/:id";
  5515. detail::PathParamsMatcher matcher(pattern);
  5516. Request request;
  5517. request.path = "/users";
  5518. ASSERT_FALSE(matcher.match(request));
  5519. }
  5520. TEST(PathParamsTest, MissingParamInTheMiddle) {
  5521. const auto pattern = "/users/:id/subscriptions";
  5522. detail::PathParamsMatcher matcher(pattern);
  5523. Request request;
  5524. request.path = "/users/subscriptions";
  5525. ASSERT_FALSE(matcher.match(request));
  5526. }
  5527. TEST(PathParamsTest, MultipleParams) {
  5528. const auto pattern = "/users/:userid/subscriptions/:subid";
  5529. detail::PathParamsMatcher matcher(pattern);
  5530. Request request;
  5531. request.path = "/users/42/subscriptions/2";
  5532. ASSERT_TRUE(matcher.match(request));
  5533. std::unordered_map<std::string, std::string> expected_params = {
  5534. {"userid", "42"}, {"subid", "2"}};
  5535. EXPECT_EQ(request.path_params, expected_params);
  5536. }
  5537. TEST(PathParamsTest, SequenceOfParams) {
  5538. const auto pattern = "/values/:x/:y/:z";
  5539. detail::PathParamsMatcher matcher(pattern);
  5540. Request request;
  5541. request.path = "/values/1/2/3";
  5542. ASSERT_TRUE(matcher.match(request));
  5543. std::unordered_map<std::string, std::string> expected_params = {
  5544. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  5545. EXPECT_EQ(request.path_params, expected_params);
  5546. }