test.cc 198 KB

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