test.cc 331 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1092. auto host = "unresolvableaddress.local";
  1093. auto path = std::string{"/"};
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(1);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_FALSE(res);
  1105. }
  1106. std::this_thread::sleep_for(std::chrono::seconds(8));
  1107. }
  1108. TEST(ConnectionErrorTest, InvalidHost) {
  1109. auto host = "-abcde.com";
  1110. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1111. auto port = 443;
  1112. SSLClient cli(host, port);
  1113. #else
  1114. auto port = 80;
  1115. Client cli(host, port);
  1116. #endif
  1117. cli.set_connection_timeout(std::chrono::seconds(2));
  1118. auto res = cli.Get("/");
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Connection, res.error());
  1121. }
  1122. TEST(ConnectionErrorTest, InvalidHost2) {
  1123. auto host = "httpbin.org/";
  1124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1125. SSLClient cli(host);
  1126. #else
  1127. Client cli(host);
  1128. #endif
  1129. cli.set_connection_timeout(std::chrono::seconds(2));
  1130. auto res = cli.Get("/");
  1131. ASSERT_TRUE(!res);
  1132. EXPECT_EQ(Error::Connection, res.error());
  1133. }
  1134. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1135. auto host = "httpbin.org/";
  1136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1137. SSLClient cli(host);
  1138. #else
  1139. Client cli(host);
  1140. #endif
  1141. cli.set_connection_timeout(std::chrono::seconds(2));
  1142. auto res = cli.Get("/");
  1143. ASSERT_TRUE(!res);
  1144. stringstream s;
  1145. s << "error code: " << res.error();
  1146. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1147. }
  1148. TEST(ConnectionErrorTest, InvalidPort) {
  1149. auto host = "localhost";
  1150. auto port = 44380;
  1151. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1152. SSLClient cli(host, port);
  1153. #else
  1154. Client cli(host, port);
  1155. #endif
  1156. cli.set_connection_timeout(std::chrono::seconds(2));
  1157. auto res = cli.Get("/");
  1158. ASSERT_TRUE(!res);
  1159. EXPECT_TRUE(Error::Connection == res.error() ||
  1160. Error::ConnectionTimeout == res.error());
  1161. }
  1162. TEST(ConnectionErrorTest, Timeout_Online) {
  1163. auto host = "google.com";
  1164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1165. auto port = 44380;
  1166. SSLClient cli(host, port);
  1167. #else
  1168. auto port = 8080;
  1169. Client cli(host, port);
  1170. #endif
  1171. cli.set_connection_timeout(std::chrono::seconds(2));
  1172. // only probe one address type so that the error reason
  1173. // correlates to the timed-out IPv4, not the unsupported
  1174. // IPv6 connection attempt
  1175. cli.set_address_family(AF_INET);
  1176. auto res = cli.Get("/");
  1177. ASSERT_TRUE(!res);
  1178. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1179. }
  1180. TEST(CancelTest, NoCancel_Online) {
  1181. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1182. auto host = "httpbin.org";
  1183. auto path = std::string{"/range/32"};
  1184. #else
  1185. auto host = "nghttp2.org";
  1186. auto path = std::string{"/httpbin/range/32"};
  1187. #endif
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. auto port = 443;
  1190. SSLClient cli(host, port);
  1191. #else
  1192. auto port = 80;
  1193. Client cli(host, port);
  1194. #endif
  1195. cli.set_connection_timeout(std::chrono::seconds(5));
  1196. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1197. ASSERT_TRUE(res);
  1198. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. }
  1201. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1202. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1203. auto host = "httpbin.org";
  1204. auto path = std::string{"/range/32"};
  1205. #else
  1206. auto host = "nghttp2.org";
  1207. auto path = std::string{"/httpbin/range/32"};
  1208. #endif
  1209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1210. auto port = 443;
  1211. SSLClient cli(host, port);
  1212. #else
  1213. auto port = 80;
  1214. Client cli(host, port);
  1215. #endif
  1216. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1217. cli.set_connection_timeout(std::chrono::seconds(5));
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Canceled, res.error());
  1220. }
  1221. TEST(CancelTest, WithCancelLargePayload_Online) {
  1222. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1223. auto host = "httpbin.org";
  1224. auto path = std::string{"/range/65536"};
  1225. #else
  1226. auto host = "nghttp2.org";
  1227. auto path = std::string{"/httpbin/range/65536"};
  1228. #endif
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. auto port = 443;
  1231. SSLClient cli(host, port);
  1232. #else
  1233. auto port = 80;
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(5));
  1237. uint32_t count = 0;
  1238. auto res =
  1239. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1240. ASSERT_TRUE(!res);
  1241. EXPECT_EQ(Error::Canceled, res.error());
  1242. }
  1243. TEST(CancelTest, NoCancelPost) {
  1244. Server svr;
  1245. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1246. res.set_content("Hello World!", "text/plain");
  1247. });
  1248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1249. auto se = detail::scope_exit([&] {
  1250. svr.stop();
  1251. thread.join();
  1252. ASSERT_FALSE(svr.is_running());
  1253. });
  1254. svr.wait_until_ready();
  1255. Client cli(HOST, PORT);
  1256. cli.set_connection_timeout(std::chrono::seconds(5));
  1257. auto res =
  1258. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1259. "application/json", [](uint64_t, uint64_t) { return true; });
  1260. ASSERT_TRUE(res);
  1261. EXPECT_EQ("Hello World!", res->body);
  1262. EXPECT_EQ(StatusCode::OK_200, res->status);
  1263. }
  1264. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1265. Server svr;
  1266. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return false; });
  1281. ASSERT_TRUE(!res);
  1282. EXPECT_EQ(Error::Canceled, res.error());
  1283. }
  1284. TEST(CancelTest, WithCancelLargePayloadPost) {
  1285. Server svr;
  1286. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1287. res.set_content(LARGE_DATA, "text/plain");
  1288. });
  1289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1290. auto se = detail::scope_exit([&] {
  1291. svr.stop();
  1292. thread.join();
  1293. ASSERT_FALSE(svr.is_running());
  1294. });
  1295. svr.wait_until_ready();
  1296. Client cli(HOST, PORT);
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res =
  1299. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1300. "application/json", [](uint64_t, uint64_t) { return false; });
  1301. ASSERT_TRUE(!res);
  1302. EXPECT_EQ(Error::Canceled, res.error());
  1303. }
  1304. TEST(CancelTest, NoCancelPut) {
  1305. Server svr;
  1306. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1307. res.set_content("Hello World!", "text/plain");
  1308. });
  1309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1310. auto se = detail::scope_exit([&] {
  1311. svr.stop();
  1312. thread.join();
  1313. ASSERT_FALSE(svr.is_running());
  1314. });
  1315. svr.wait_until_ready();
  1316. Client cli(HOST, PORT);
  1317. cli.set_connection_timeout(std::chrono::seconds(5));
  1318. auto res =
  1319. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1320. "application/json", [](uint64_t, uint64_t) { return true; });
  1321. ASSERT_TRUE(res);
  1322. EXPECT_EQ("Hello World!", res->body);
  1323. EXPECT_EQ(StatusCode::OK_200, res->status);
  1324. }
  1325. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1326. Server svr;
  1327. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1328. res.set_content("Hello World!", "text/plain");
  1329. });
  1330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1331. auto se = detail::scope_exit([&] {
  1332. svr.stop();
  1333. thread.join();
  1334. ASSERT_FALSE(svr.is_running());
  1335. });
  1336. svr.wait_until_ready();
  1337. Client cli(HOST, PORT);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res =
  1340. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1341. "application/json", [](uint64_t, uint64_t) { return false; });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, WithCancelLargePayloadPut) {
  1346. Server svr;
  1347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content(LARGE_DATA, "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return false; });
  1362. ASSERT_TRUE(!res);
  1363. EXPECT_EQ(Error::Canceled, res.error());
  1364. }
  1365. TEST(CancelTest, NoCancelPatch) {
  1366. Server svr;
  1367. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1368. res.set_content("Hello World!", "text/plain");
  1369. });
  1370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1371. auto se = detail::scope_exit([&] {
  1372. svr.stop();
  1373. thread.join();
  1374. ASSERT_FALSE(svr.is_running());
  1375. });
  1376. svr.wait_until_ready();
  1377. Client cli(HOST, PORT);
  1378. cli.set_connection_timeout(std::chrono::seconds(5));
  1379. auto res =
  1380. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1381. "application/json", [](uint64_t, uint64_t) { return true; });
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("Hello World!", res->body);
  1384. EXPECT_EQ(StatusCode::OK_200, res->status);
  1385. }
  1386. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1387. Server svr;
  1388. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1389. res.set_content("Hello World!", "text/plain");
  1390. });
  1391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1392. auto se = detail::scope_exit([&] {
  1393. svr.stop();
  1394. thread.join();
  1395. ASSERT_FALSE(svr.is_running());
  1396. });
  1397. svr.wait_until_ready();
  1398. Client cli(HOST, PORT);
  1399. cli.set_connection_timeout(std::chrono::seconds(5));
  1400. auto res =
  1401. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1402. "application/json", [](uint64_t, uint64_t) { return false; });
  1403. ASSERT_TRUE(!res);
  1404. EXPECT_EQ(Error::Canceled, res.error());
  1405. }
  1406. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1407. Server svr;
  1408. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1409. res.set_content(LARGE_DATA, "text/plain");
  1410. });
  1411. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1412. auto se = detail::scope_exit([&] {
  1413. svr.stop();
  1414. thread.join();
  1415. ASSERT_FALSE(svr.is_running());
  1416. });
  1417. svr.wait_until_ready();
  1418. Client cli(HOST, PORT);
  1419. cli.set_connection_timeout(std::chrono::seconds(5));
  1420. auto res =
  1421. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1422. "application/json", [](uint64_t, uint64_t) { return false; });
  1423. ASSERT_TRUE(!res);
  1424. EXPECT_EQ(Error::Canceled, res.error());
  1425. }
  1426. TEST(CancelTest, NoCancelDelete) {
  1427. Server svr;
  1428. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1429. res.set_content("Hello World!", "text/plain");
  1430. });
  1431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. thread.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. Client cli(HOST, PORT);
  1439. cli.set_connection_timeout(std::chrono::seconds(5));
  1440. auto res =
  1441. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1442. "application/json", [](uint64_t, uint64_t) { return true; });
  1443. ASSERT_TRUE(res);
  1444. EXPECT_EQ("Hello World!", res->body);
  1445. EXPECT_EQ(StatusCode::OK_200, res->status);
  1446. }
  1447. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1448. Server svr;
  1449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("Hello World!", "text/plain");
  1451. });
  1452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1453. auto se = detail::scope_exit([&] {
  1454. svr.stop();
  1455. thread.join();
  1456. ASSERT_FALSE(svr.is_running());
  1457. });
  1458. svr.wait_until_ready();
  1459. Client cli(HOST, PORT);
  1460. cli.set_connection_timeout(std::chrono::seconds(5));
  1461. auto res =
  1462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1463. "application/json", [](uint64_t, uint64_t) { return false; });
  1464. ASSERT_TRUE(!res);
  1465. EXPECT_EQ(Error::Canceled, res.error());
  1466. }
  1467. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1468. Server svr;
  1469. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1470. res.set_content(LARGE_DATA, "text/plain");
  1471. });
  1472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1473. auto se = detail::scope_exit([&] {
  1474. svr.stop();
  1475. thread.join();
  1476. ASSERT_FALSE(svr.is_running());
  1477. });
  1478. svr.wait_until_ready();
  1479. Client cli(HOST, PORT);
  1480. cli.set_connection_timeout(std::chrono::seconds(5));
  1481. auto res =
  1482. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1483. "application/json", [](uint64_t, uint64_t) { return false; });
  1484. ASSERT_TRUE(!res);
  1485. EXPECT_EQ(Error::Canceled, res.error());
  1486. }
  1487. static std::string remove_whitespace(const std::string &input) {
  1488. std::string output;
  1489. output.reserve(input.size());
  1490. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1491. [](unsigned char c) { return !std::isspace(c); });
  1492. return output;
  1493. }
  1494. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1495. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1496. auto host = "httpbin.org";
  1497. auto path = std::string{"/basic-auth/hello/world"};
  1498. #else
  1499. auto host = "nghttp2.org";
  1500. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1501. #endif
  1502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1503. auto port = 443;
  1504. SSLClient cli(host, port);
  1505. #else
  1506. auto port = 80;
  1507. Client cli(host, port);
  1508. #endif
  1509. {
  1510. auto res = cli.Get(path);
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1513. }
  1514. {
  1515. auto res =
  1516. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1517. ASSERT_TRUE(res);
  1518. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1519. remove_whitespace(res->body));
  1520. EXPECT_EQ(StatusCode::OK_200, res->status);
  1521. }
  1522. {
  1523. cli.set_basic_auth("hello", "world");
  1524. auto res = cli.Get(path);
  1525. ASSERT_TRUE(res);
  1526. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1527. remove_whitespace(res->body));
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. }
  1530. {
  1531. cli.set_basic_auth("hello", "bad");
  1532. auto res = cli.Get(path);
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1535. }
  1536. {
  1537. cli.set_basic_auth("bad", "world");
  1538. auto res = cli.Get(path);
  1539. ASSERT_TRUE(res);
  1540. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1541. }
  1542. }
  1543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1544. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1545. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1546. auto host = "httpbin.org";
  1547. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1548. auto paths = std::vector<std::string>{
  1549. "/digest-auth/auth/hello/world/MD5",
  1550. "/digest-auth/auth/hello/world/SHA-256",
  1551. "/digest-auth/auth/hello/world/SHA-512",
  1552. "/digest-auth/auth-int/hello/world/MD5",
  1553. };
  1554. #else
  1555. auto host = "nghttp2.org";
  1556. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1557. auto paths = std::vector<std::string>{
  1558. "/httpbin/digest-auth/auth/hello/world/MD5",
  1559. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1560. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1561. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1562. };
  1563. #endif
  1564. auto port = 443;
  1565. SSLClient cli(host, port);
  1566. {
  1567. auto res = cli.Get(unauth_path);
  1568. ASSERT_TRUE(res);
  1569. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1570. }
  1571. {
  1572. cli.set_digest_auth("hello", "world");
  1573. for (const auto &path : paths) {
  1574. auto res = cli.Get(path.c_str());
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1577. remove_whitespace(res->body));
  1578. EXPECT_EQ(StatusCode::OK_200, res->status);
  1579. }
  1580. cli.set_digest_auth("hello", "bad");
  1581. for (const auto &path : paths) {
  1582. auto res = cli.Get(path.c_str());
  1583. ASSERT_TRUE(res);
  1584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1585. }
  1586. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1587. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1588. // cli.set_digest_auth("bad", "world");
  1589. // for (const auto& path : paths) {
  1590. // auto res = cli.Get(path.c_str());
  1591. // ASSERT_TRUE(res);
  1592. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1593. // }
  1594. }
  1595. }
  1596. #endif
  1597. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1598. auto host = "google.com";
  1599. auto another_host = "example.com";
  1600. auto wrong_ip = "0.0.0.0";
  1601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1602. SSLClient cli(host);
  1603. #else
  1604. Client cli(host);
  1605. #endif
  1606. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1607. auto res = cli.Get("/");
  1608. ASSERT_TRUE(res);
  1609. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1610. }
  1611. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1612. auto host = "google.com";
  1613. auto wrong_ip = "0.0.0.0";
  1614. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1615. SSLClient cli(host);
  1616. #else
  1617. Client cli(host);
  1618. #endif
  1619. cli.set_hostname_addr_map({{host, wrong_ip}});
  1620. auto res = cli.Get("/");
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Connection, res.error());
  1623. }
  1624. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1625. auto host = "nghttp2.org";
  1626. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1627. SSLClient cli(host);
  1628. #else
  1629. Client cli(host);
  1630. #endif
  1631. cli.set_follow_location(true);
  1632. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1633. ASSERT_TRUE(res);
  1634. EXPECT_EQ(StatusCode::OK_200, res->status);
  1635. }
  1636. TEST(RedirectTest, Redirect_Online) {
  1637. auto host = "nghttp2.org";
  1638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1639. SSLClient cli(host);
  1640. #else
  1641. Client cli(host);
  1642. #endif
  1643. cli.set_follow_location(true);
  1644. auto res = cli.Get("/httpbin/redirect/3");
  1645. ASSERT_TRUE(res);
  1646. EXPECT_EQ(StatusCode::OK_200, res->status);
  1647. }
  1648. TEST(RelativeRedirectTest, Redirect_Online) {
  1649. auto host = "nghttp2.org";
  1650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1651. SSLClient cli(host);
  1652. #else
  1653. Client cli(host);
  1654. #endif
  1655. cli.set_follow_location(true);
  1656. auto res = cli.Get("/httpbin/relative-redirect/3");
  1657. ASSERT_TRUE(res);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(TooManyRedirectTest, Redirect_Online) {
  1661. auto host = "nghttp2.org";
  1662. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1663. SSLClient cli(host);
  1664. #else
  1665. Client cli(host);
  1666. #endif
  1667. cli.set_follow_location(true);
  1668. auto res = cli.Get("/httpbin/redirect/21");
  1669. ASSERT_TRUE(!res);
  1670. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1671. }
  1672. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1673. TEST(YahooRedirectTest, Redirect_Online) {
  1674. Client cli("yahoo.com");
  1675. auto res = cli.Get("/");
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1678. cli.set_follow_location(true);
  1679. res = cli.Get("/");
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::OK_200, res->status);
  1682. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1683. }
  1684. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1685. #define REDIR_HOST "httpbingo.org"
  1686. #define REDIR_PATH "/redirect-to"
  1687. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1688. SSLClient cli(REDIR_HOST);
  1689. cli.set_follow_location(true);
  1690. auto res =
  1691. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::OK_200, res->status);
  1694. }
  1695. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1696. SSLClient cli(REDIR_HOST);
  1697. cli.set_follow_location(true);
  1698. Params params;
  1699. params.emplace("url", "http://example.com");
  1700. params.emplace("status_code", "302");
  1701. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1702. ASSERT_TRUE(res);
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. }
  1705. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1706. SSLClient cli(REDIR_HOST);
  1707. cli.set_follow_location(true);
  1708. Params params;
  1709. params.emplace("url", "http://example.com");
  1710. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1711. ASSERT_TRUE(res);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. TEST(UrlWithSpace, Redirect_Online) {
  1715. SSLClient cli("edge.forgecdn.net");
  1716. cli.set_follow_location(true);
  1717. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1721. }
  1722. #endif
  1723. #if !defined(_WIN32) && !defined(_WIN64)
  1724. TEST(ReceiveSignals, Signal) {
  1725. auto setupSignalHandlers = []() {
  1726. struct sigaction act;
  1727. sigemptyset(&act.sa_mask);
  1728. act.sa_flags = SA_SIGINFO;
  1729. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1730. switch (sig) {
  1731. case SIGINT:
  1732. default: break;
  1733. }
  1734. };
  1735. ::sigaction(SIGINT, &act, nullptr);
  1736. };
  1737. Server svr;
  1738. int port = 0;
  1739. auto thread = std::thread([&]() {
  1740. setupSignalHandlers();
  1741. port = svr.bind_to_any_port("localhost");
  1742. svr.listen_after_bind();
  1743. });
  1744. auto se = detail::scope_exit([&] {
  1745. svr.stop();
  1746. thread.join();
  1747. ASSERT_FALSE(svr.is_running());
  1748. });
  1749. svr.wait_until_ready();
  1750. ASSERT_TRUE(svr.is_running());
  1751. pthread_kill(thread.native_handle(), SIGINT);
  1752. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1753. ASSERT_TRUE(svr.is_running());
  1754. }
  1755. #endif
  1756. TEST(RedirectToDifferentPort, Redirect) {
  1757. Server svr1;
  1758. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1759. res.set_content("Hello World!", "text/plain");
  1760. });
  1761. int svr1_port = 0;
  1762. auto thread1 = std::thread([&]() {
  1763. svr1_port = svr1.bind_to_any_port("localhost");
  1764. svr1.listen_after_bind();
  1765. });
  1766. Server svr2;
  1767. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1768. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1769. });
  1770. int svr2_port = 0;
  1771. auto thread2 = std::thread([&]() {
  1772. svr2_port = svr2.bind_to_any_port("localhost");
  1773. svr2.listen_after_bind();
  1774. });
  1775. auto se = detail::scope_exit([&] {
  1776. svr2.stop();
  1777. thread2.join();
  1778. svr1.stop();
  1779. thread1.join();
  1780. ASSERT_FALSE(svr2.is_running());
  1781. ASSERT_FALSE(svr1.is_running());
  1782. });
  1783. svr1.wait_until_ready();
  1784. svr2.wait_until_ready();
  1785. Client cli("localhost", svr2_port);
  1786. cli.set_follow_location(true);
  1787. auto res = cli.Get("/2");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. TEST(RedirectFromPageWithContent, Redirect) {
  1793. Server svr;
  1794. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1795. res.set_content("___", "text/plain");
  1796. res.set_redirect("/2");
  1797. });
  1798. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1799. res.set_content("Hello World!", "text/plain");
  1800. });
  1801. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1802. auto se = detail::scope_exit([&] {
  1803. svr.stop();
  1804. th.join();
  1805. ASSERT_FALSE(svr.is_running());
  1806. });
  1807. svr.wait_until_ready();
  1808. {
  1809. Client cli("localhost", PORT);
  1810. cli.set_follow_location(true);
  1811. std::string body;
  1812. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1813. body.append(data, data_length);
  1814. return true;
  1815. });
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. EXPECT_EQ("Hello World!", body);
  1819. }
  1820. {
  1821. Client cli("localhost", PORT);
  1822. std::string body;
  1823. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1824. body.append(data, data_length);
  1825. return true;
  1826. });
  1827. ASSERT_TRUE(res);
  1828. EXPECT_EQ(StatusCode::Found_302, res->status);
  1829. EXPECT_EQ("___", body);
  1830. }
  1831. }
  1832. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1833. Server svr;
  1834. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1835. res.set_content("___", "text/plain");
  1836. // res.set_redirect("/2");
  1837. res.set_redirect("http://[::1]:1234/2");
  1838. });
  1839. svr.Get("/2", [&](const Request &req, Response &res) {
  1840. auto host_header = req.headers.find("Host");
  1841. ASSERT_TRUE(host_header != req.headers.end());
  1842. EXPECT_EQ("[::1]:1234", host_header->second);
  1843. res.set_content("Hello World!", "text/plain");
  1844. });
  1845. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. th.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1852. // actually starts anything, so the condition !svr.is_running() will
  1853. // always remain true, and the loop never stops.
  1854. // This basically counts how many milliseconds have passed since the
  1855. // call to svr.listen(), and if after 5 seconds nothing started yet
  1856. // aborts the test.
  1857. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1858. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1859. ASSERT_LT(milliseconds, 5000U);
  1860. }
  1861. {
  1862. Client cli("http://[::1]:1234");
  1863. cli.set_follow_location(true);
  1864. std::string body;
  1865. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1866. body.append(data, data_length);
  1867. return true;
  1868. });
  1869. ASSERT_TRUE(res);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. EXPECT_EQ("Hello World!", body);
  1872. }
  1873. {
  1874. Client cli("http://[::1]:1234");
  1875. std::string body;
  1876. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1877. body.append(data, data_length);
  1878. return true;
  1879. });
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::Found_302, res->status);
  1882. EXPECT_EQ("___", body);
  1883. }
  1884. }
  1885. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1886. Server svr;
  1887. svr.Get("/foo", [](const Request &req, Response &res) {
  1888. auto a = req.params.find("a");
  1889. if (a != req.params.end()) {
  1890. res.set_content((*a).second, "text/plain");
  1891. res.status = StatusCode::OK_200;
  1892. } else {
  1893. res.status = StatusCode::BadRequest_400;
  1894. }
  1895. });
  1896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1897. auto se = detail::scope_exit([&] {
  1898. svr.stop();
  1899. thread.join();
  1900. ASSERT_FALSE(svr.is_running());
  1901. });
  1902. svr.wait_until_ready();
  1903. {
  1904. Client cli(HOST, PORT);
  1905. cli.set_path_encode(false);
  1906. auto res = cli.Get("/foo?a=explicitly+encoded");
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. // This expects it back with a space, as the `+` won't have been
  1910. // url-encoded, and server-side the params get decoded turning `+`
  1911. // into spaces.
  1912. EXPECT_EQ("explicitly encoded", res->body);
  1913. }
  1914. }
  1915. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1916. Server svr;
  1917. svr.Get("/", [](const Request &req, Response &) {
  1918. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. {
  1928. Client cli(HOST, PORT);
  1929. cli.set_path_encode(false);
  1930. auto res = cli.Get("/?something=%0A");
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. }
  1934. }
  1935. TEST(BindServerTest, DISABLED_BindDualStack) {
  1936. Server svr;
  1937. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1938. res.set_content("Hello World!", "text/plain");
  1939. });
  1940. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1941. auto se = detail::scope_exit([&] {
  1942. svr.stop();
  1943. thread.join();
  1944. ASSERT_FALSE(svr.is_running());
  1945. });
  1946. svr.wait_until_ready();
  1947. {
  1948. Client cli("127.0.0.1", PORT);
  1949. auto res = cli.Get("/1");
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::OK_200, res->status);
  1952. EXPECT_EQ("Hello World!", res->body);
  1953. }
  1954. {
  1955. Client cli("::1", PORT);
  1956. auto res = cli.Get("/1");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", res->body);
  1960. }
  1961. }
  1962. TEST(BindServerTest, BindAndListenSeparately) {
  1963. Server svr;
  1964. int port = svr.bind_to_any_port("0.0.0.0");
  1965. ASSERT_TRUE(svr.is_valid());
  1966. ASSERT_TRUE(port > 0);
  1967. svr.stop();
  1968. }
  1969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1970. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1972. CLIENT_CA_CERT_DIR);
  1973. int port = svr.bind_to_any_port("0.0.0.0");
  1974. ASSERT_TRUE(svr.is_valid());
  1975. ASSERT_TRUE(port > 0);
  1976. svr.stop();
  1977. }
  1978. #endif
  1979. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1980. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1981. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1982. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1983. int port = svr.bind_to_any_port("0.0.0.0");
  1984. ASSERT_TRUE(svr.is_valid());
  1985. ASSERT_TRUE(port > 0);
  1986. svr.stop();
  1987. }
  1988. #endif
  1989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1990. X509 *readCertificate(const std::string &strFileName) {
  1991. std::ifstream inStream(strFileName);
  1992. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1993. std::istreambuf_iterator<char>());
  1994. if (strCertPEM.empty()) return (nullptr);
  1995. BIO *pbCert = BIO_new(BIO_s_mem());
  1996. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1997. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1998. BIO_free(pbCert);
  1999. return (pCert);
  2000. }
  2001. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2002. std::ifstream inStream(strFileName);
  2003. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2004. std::istreambuf_iterator<char>());
  2005. if (strPrivateKeyPEM.empty()) return (nullptr);
  2006. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2007. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2008. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2009. BIO_free(pbPrivKey);
  2010. return (pPrivateKey);
  2011. }
  2012. TEST(BindServerTest, UpdateCerts) {
  2013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2014. int port = svr.bind_to_any_port("0.0.0.0");
  2015. ASSERT_TRUE(svr.is_valid());
  2016. ASSERT_TRUE(port > 0);
  2017. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2018. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2019. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2020. ASSERT_TRUE(cert != nullptr);
  2021. ASSERT_TRUE(ca_cert != nullptr);
  2022. ASSERT_TRUE(key != nullptr);
  2023. X509_STORE *cert_store = X509_STORE_new();
  2024. X509_STORE_add_cert(cert_store, ca_cert);
  2025. svr.update_certs(cert, key, cert_store);
  2026. ASSERT_TRUE(svr.is_valid());
  2027. svr.stop();
  2028. X509_free(cert);
  2029. X509_free(ca_cert);
  2030. EVP_PKEY_free(key);
  2031. }
  2032. #endif
  2033. TEST(ErrorHandlerTest, ContentLength) {
  2034. Server svr;
  2035. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2036. res.status = StatusCode::OK_200;
  2037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2038. "text/html"); // <= Content-Length still 13
  2039. });
  2040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2041. res.set_content("Hello World!\n", "text/plain");
  2042. res.status = 524;
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. Client cli(HOST, PORT);
  2053. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(StatusCode::OK_200, res->status);
  2056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2057. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2058. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2059. }
  2060. }
  2061. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2062. TEST(ExceptionTest, WithoutExceptionHandler) {
  2063. Server svr;
  2064. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2065. throw std::runtime_error("exception...");
  2066. });
  2067. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2068. throw std::runtime_error("exception\r\n...");
  2069. });
  2070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2071. auto se = detail::scope_exit([&] {
  2072. svr.stop();
  2073. listen_thread.join();
  2074. ASSERT_FALSE(svr.is_running());
  2075. });
  2076. svr.wait_until_ready();
  2077. Client cli("localhost", PORT);
  2078. {
  2079. auto res = cli.Get("/exception");
  2080. ASSERT_TRUE(res);
  2081. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2082. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2083. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2084. }
  2085. {
  2086. auto res = cli.Get("/unknown");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2089. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2090. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2091. }
  2092. }
  2093. TEST(ExceptionTest, WithExceptionHandler) {
  2094. Server svr;
  2095. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2096. std::exception_ptr ep) {
  2097. EXPECT_FALSE(ep == nullptr);
  2098. try {
  2099. std::rethrow_exception(ep);
  2100. } catch (std::exception &e) {
  2101. EXPECT_EQ("abc", std::string(e.what()));
  2102. } catch (...) {}
  2103. res.status = StatusCode::InternalServerError_500;
  2104. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2105. "text/html"); // <= Content-Length still 13 at this point
  2106. });
  2107. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2108. res.set_content("Hello World!\n", "text/plain");
  2109. throw std::runtime_error("abc");
  2110. });
  2111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2112. auto se = detail::scope_exit([&] {
  2113. svr.stop();
  2114. thread.join();
  2115. ASSERT_FALSE(svr.is_running());
  2116. });
  2117. svr.wait_until_ready();
  2118. for (size_t i = 0; i < 10; i++) {
  2119. Client cli(HOST, PORT);
  2120. for (size_t j = 0; j < 100; j++) {
  2121. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2127. }
  2128. cli.set_keep_alive(true);
  2129. for (size_t j = 0; j < 100; j++) {
  2130. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2131. ASSERT_TRUE(res);
  2132. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2134. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2135. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2136. }
  2137. }
  2138. }
  2139. TEST(ExceptionTest, AndErrorHandler) {
  2140. Server svr;
  2141. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2142. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2143. });
  2144. svr.set_exception_handler(
  2145. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2146. EXPECT_FALSE(ep == nullptr);
  2147. try {
  2148. std::rethrow_exception(ep);
  2149. } catch (std::exception &e) {
  2150. res.set_content(e.what(), "text/html");
  2151. } catch (...) {}
  2152. res.status = StatusCode::InternalServerError_500;
  2153. });
  2154. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2155. throw std::runtime_error("EXCEPTION");
  2156. });
  2157. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2158. res.set_content("ERROR", "text/html");
  2159. res.status = StatusCode::InternalServerError_500;
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. {
  2170. auto res = cli.Get("/exception");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2173. EXPECT_EQ("EXCEPTION", res->body);
  2174. }
  2175. {
  2176. auto res = cli.Get("/error");
  2177. ASSERT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2179. EXPECT_EQ("ERROR", res->body);
  2180. }
  2181. {
  2182. auto res = cli.Get("/invalid");
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2185. EXPECT_EQ("NOT_FOUND", res->body);
  2186. }
  2187. }
  2188. #endif
  2189. TEST(NoContentTest, ContentLength) {
  2190. Server svr;
  2191. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2192. res.status = StatusCode::NoContent_204;
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. {
  2202. Client cli(HOST, PORT);
  2203. auto res = cli.Get("/hi");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2206. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2207. }
  2208. }
  2209. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2212. ASSERT_TRUE(svr.is_valid());
  2213. #else
  2214. Server svr;
  2215. #endif
  2216. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2217. if (req.path == "/routing_handler") {
  2218. res.set_header("PRE_ROUTING", "on");
  2219. res.set_content("Routing Handler", "text/plain");
  2220. return httplib::Server::HandlerResponse::Handled;
  2221. }
  2222. return httplib::Server::HandlerResponse::Unhandled;
  2223. });
  2224. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2225. res.set_content("Error", "text/html");
  2226. });
  2227. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2228. if (req.path == "/routing_handler") {
  2229. res.set_header("POST_ROUTING", "on");
  2230. }
  2231. });
  2232. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2233. res.set_content("Hello World!\n", "text/plain");
  2234. });
  2235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2236. auto se = detail::scope_exit([&] {
  2237. svr.stop();
  2238. thread.join();
  2239. ASSERT_FALSE(svr.is_running());
  2240. });
  2241. svr.wait_until_ready();
  2242. {
  2243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2244. SSLClient cli(HOST, PORT);
  2245. cli.enable_server_certificate_verification(false);
  2246. #else
  2247. Client cli(HOST, PORT);
  2248. #endif
  2249. auto res = cli.Get("/routing_handler");
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(StatusCode::OK_200, res->status);
  2252. EXPECT_EQ("Routing Handler", res->body);
  2253. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2254. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2255. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2256. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2257. }
  2258. {
  2259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2260. SSLClient cli(HOST, PORT);
  2261. cli.enable_server_certificate_verification(false);
  2262. #else
  2263. Client cli(HOST, PORT);
  2264. #endif
  2265. auto res = cli.Get("/hi");
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ("Hello World!\n", res->body);
  2269. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2270. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2271. }
  2272. {
  2273. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2274. SSLClient cli(HOST, PORT);
  2275. cli.enable_server_certificate_verification(false);
  2276. #else
  2277. Client cli(HOST, PORT);
  2278. #endif
  2279. auto res = cli.Get("/aaa");
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2282. EXPECT_EQ("Error", res->body);
  2283. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2284. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2285. }
  2286. }
  2287. TEST(RequestHandlerTest, PreRequestHandler) {
  2288. auto route_path = "/user/:user";
  2289. Server svr;
  2290. svr.Get("/hi", [](const Request &, Response &res) {
  2291. res.set_content("hi", "text/plain");
  2292. });
  2293. svr.Get(route_path, [](const Request &req, Response &res) {
  2294. res.set_content(req.path_params.at("user"), "text/plain");
  2295. });
  2296. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2297. if (req.matched_route == route_path) {
  2298. auto user = req.path_params.at("user");
  2299. if (user != "john") {
  2300. res.status = StatusCode::Forbidden_403;
  2301. res.set_content("error", "text/html");
  2302. return Server::HandlerResponse::Handled;
  2303. }
  2304. }
  2305. return Server::HandlerResponse::Unhandled;
  2306. });
  2307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2308. auto se = detail::scope_exit([&] {
  2309. svr.stop();
  2310. thread.join();
  2311. ASSERT_FALSE(svr.is_running());
  2312. });
  2313. svr.wait_until_ready();
  2314. Client cli(HOST, PORT);
  2315. {
  2316. auto res = cli.Get("/hi");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::OK_200, res->status);
  2319. EXPECT_EQ("hi", res->body);
  2320. }
  2321. {
  2322. auto res = cli.Get("/user/john");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::OK_200, res->status);
  2325. EXPECT_EQ("john", res->body);
  2326. }
  2327. {
  2328. auto res = cli.Get("/user/invalid-user");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2331. EXPECT_EQ("error", res->body);
  2332. }
  2333. }
  2334. TEST(InvalidFormatTest, StatusCode) {
  2335. Server svr;
  2336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!\n", "text/plain");
  2338. res.status = 9999; // Status should be a three-digit code...
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. {
  2348. Client cli(HOST, PORT);
  2349. auto res = cli.Get("/hi");
  2350. ASSERT_FALSE(res);
  2351. }
  2352. }
  2353. TEST(URLFragmentTest, WithFragment) {
  2354. Server svr;
  2355. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2356. EXPECT_TRUE(req.target == "/hi");
  2357. });
  2358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2359. auto se = detail::scope_exit([&] {
  2360. svr.stop();
  2361. thread.join();
  2362. ASSERT_FALSE(svr.is_running());
  2363. });
  2364. svr.wait_until_ready();
  2365. {
  2366. Client cli(HOST, PORT);
  2367. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2368. EXPECT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. res = cli.Get("/hi%23key1=val1=key2=val2");
  2371. EXPECT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. }
  2374. }
  2375. TEST(HeaderWriter, SetHeaderWriter) {
  2376. Server svr;
  2377. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2378. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2379. return detail::write_headers(strm, hdrs);
  2380. });
  2381. svr.Get("/hi", [](const Request &req, Response &res) {
  2382. auto it = req.headers.find("CustomClientHeader");
  2383. EXPECT_TRUE(it != req.headers.end());
  2384. EXPECT_EQ(it->second, "CustomClientValue");
  2385. res.set_content("Hello World!\n", "text/plain");
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. {
  2395. Client cli(HOST, PORT);
  2396. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2397. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2398. return detail::write_headers(strm, hdrs);
  2399. });
  2400. auto res = cli.Get("/hi");
  2401. EXPECT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::OK_200, res->status);
  2403. auto it = res->headers.find("CustomServerHeader");
  2404. EXPECT_TRUE(it != res->headers.end());
  2405. EXPECT_EQ(it->second, "CustomServerValue");
  2406. }
  2407. }
  2408. class ServerTest : public ::testing::Test {
  2409. protected:
  2410. ServerTest()
  2411. : cli_(HOST, PORT)
  2412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2413. ,
  2414. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2415. #endif
  2416. {
  2417. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2418. cli_.enable_server_certificate_verification(false);
  2419. #endif
  2420. }
  2421. virtual void SetUp() {
  2422. svr_.set_mount_point("/", "./www");
  2423. svr_.set_mount_point("/mount", "./www2");
  2424. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2425. svr_.Get("/hi",
  2426. [&](const Request & /*req*/, Response &res) {
  2427. res.set_content("Hello World!", "text/plain");
  2428. })
  2429. .Get("/file_content",
  2430. [&](const Request & /*req*/, Response &res) {
  2431. res.set_file_content("./www/dir/test.html");
  2432. })
  2433. .Get("/file_content_with_content_type",
  2434. [&](const Request & /*req*/, Response &res) {
  2435. res.set_file_content("./www/file", "text/plain");
  2436. })
  2437. .Get("/invalid_file_content",
  2438. [&](const Request & /*req*/, Response &res) {
  2439. res.set_file_content("./www/dir/invalid_file_path");
  2440. })
  2441. .Get("/http_response_splitting",
  2442. [&](const Request & /*req*/, Response &res) {
  2443. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2444. EXPECT_EQ(0U, res.headers.size());
  2445. EXPECT_FALSE(res.has_header("a"));
  2446. res.set_header("a", "1\nSet-Cookie: a=1");
  2447. EXPECT_EQ(0U, res.headers.size());
  2448. EXPECT_FALSE(res.has_header("a"));
  2449. res.set_header("a", "1\rSet-Cookie: a=1");
  2450. EXPECT_EQ(0U, res.headers.size());
  2451. EXPECT_FALSE(res.has_header("a"));
  2452. res.set_header("a\r\nb", "0");
  2453. EXPECT_EQ(0U, res.headers.size());
  2454. EXPECT_FALSE(res.has_header("a"));
  2455. res.set_header("a\rb", "0");
  2456. EXPECT_EQ(0U, res.headers.size());
  2457. EXPECT_FALSE(res.has_header("a"));
  2458. res.set_header("a\nb", "0");
  2459. EXPECT_EQ(0U, res.headers.size());
  2460. EXPECT_FALSE(res.has_header("a"));
  2461. res.set_redirect("1\r\nSet-Cookie: a=1");
  2462. EXPECT_EQ(0U, res.headers.size());
  2463. EXPECT_FALSE(res.has_header("Location"));
  2464. })
  2465. .Get("/slow",
  2466. [&](const Request & /*req*/, Response &res) {
  2467. std::this_thread::sleep_for(std::chrono::seconds(2));
  2468. res.set_content("slow", "text/plain");
  2469. })
  2470. #if 0
  2471. .Post("/slowpost",
  2472. [&](const Request & /*req*/, Response &res) {
  2473. std::this_thread::sleep_for(std::chrono::seconds(2));
  2474. res.set_content("slow", "text/plain");
  2475. })
  2476. #endif
  2477. .Get("/remote_addr",
  2478. [&](const Request &req, Response &res) {
  2479. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2480. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2481. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2482. EXPECT_EQ(req.remote_port,
  2483. std::stoi(req.get_header_value("REMOTE_PORT")));
  2484. res.set_content(remote_addr.c_str(), "text/plain");
  2485. })
  2486. .Get("/local_addr",
  2487. [&](const Request &req, Response &res) {
  2488. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2489. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2490. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2491. auto local_port = req.get_header_value("LOCAL_PORT");
  2492. EXPECT_EQ(req.local_addr, local_addr);
  2493. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2494. res.set_content(local_addr.append(":").append(local_port),
  2495. "text/plain");
  2496. })
  2497. .Get("/endwith%",
  2498. [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. })
  2501. .Get("/a\\+\\+b",
  2502. [&](const Request &req, Response &res) {
  2503. ASSERT_TRUE(req.has_param("a +b"));
  2504. auto val = req.get_param_value("a +b");
  2505. res.set_content(val, "text/plain");
  2506. })
  2507. .Get("/", [&](const Request & /*req*/,
  2508. Response &res) { res.set_redirect("/hi"); })
  2509. .Post("/1",
  2510. [](const Request & /*req*/, Response &res) {
  2511. res.set_redirect("/2", StatusCode::SeeOther_303);
  2512. })
  2513. .Get("/2",
  2514. [](const Request & /*req*/, Response &res) {
  2515. res.set_content("redirected.", "text/plain");
  2516. res.status = StatusCode::OK_200;
  2517. })
  2518. .Post("/person",
  2519. [&](const Request &req, Response &res) {
  2520. if (req.has_param("name") && req.has_param("note")) {
  2521. persons_[req.get_param_value("name")] =
  2522. req.get_param_value("note");
  2523. } else {
  2524. res.status = StatusCode::BadRequest_400;
  2525. }
  2526. })
  2527. .Put("/person",
  2528. [&](const Request &req, Response &res) {
  2529. if (req.has_param("name") && req.has_param("note")) {
  2530. persons_[req.get_param_value("name")] =
  2531. req.get_param_value("note");
  2532. } else {
  2533. res.status = StatusCode::BadRequest_400;
  2534. }
  2535. })
  2536. .Get("/person/(.*)",
  2537. [&](const Request &req, Response &res) {
  2538. string name = req.matches[1];
  2539. if (persons_.find(name) != persons_.end()) {
  2540. auto note = persons_[name];
  2541. res.set_content(note, "text/plain");
  2542. } else {
  2543. res.status = StatusCode::NotFound_404;
  2544. }
  2545. })
  2546. .Delete("/person",
  2547. [&](const Request &req, Response &res) {
  2548. if (req.has_param("name")) {
  2549. string name = req.get_param_value("name");
  2550. if (persons_.find(name) != persons_.end()) {
  2551. persons_.erase(name);
  2552. res.set_content("DELETED", "text/plain");
  2553. } else {
  2554. res.status = StatusCode::NotFound_404;
  2555. }
  2556. } else {
  2557. res.status = StatusCode::BadRequest_400;
  2558. }
  2559. })
  2560. .Post("/x-www-form-urlencoded-json",
  2561. [&](const Request &req, Response &res) {
  2562. auto json = req.get_param_value("json");
  2563. ASSERT_EQ(JSON_DATA, json);
  2564. res.set_content(json, "appliation/json");
  2565. res.status = StatusCode::OK_200;
  2566. })
  2567. .Get("/streamed-chunked",
  2568. [&](const Request & /*req*/, Response &res) {
  2569. res.set_chunked_content_provider(
  2570. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2571. sink.os << "123";
  2572. sink.os << "456";
  2573. sink.os << "789";
  2574. sink.done();
  2575. return true;
  2576. });
  2577. })
  2578. .Get("/streamed-chunked2",
  2579. [&](const Request & /*req*/, Response &res) {
  2580. auto i = new int(0);
  2581. res.set_chunked_content_provider(
  2582. "text/plain",
  2583. [i](size_t /*offset*/, DataSink &sink) {
  2584. switch (*i) {
  2585. case 0: sink.os << "123"; break;
  2586. case 1: sink.os << "456"; break;
  2587. case 2: sink.os << "789"; break;
  2588. case 3: sink.done(); break;
  2589. }
  2590. (*i)++;
  2591. return true;
  2592. },
  2593. [i](bool success) {
  2594. EXPECT_TRUE(success);
  2595. delete i;
  2596. });
  2597. })
  2598. .Get("/streamed-chunked-with-trailer",
  2599. [&](const Request & /*req*/, Response &res) {
  2600. auto i = new int(0);
  2601. res.set_header("Trailer", "Dummy1, Dummy2");
  2602. res.set_chunked_content_provider(
  2603. "text/plain",
  2604. [i](size_t /*offset*/, DataSink &sink) {
  2605. switch (*i) {
  2606. case 0: sink.os << "123"; break;
  2607. case 1: sink.os << "456"; break;
  2608. case 2: sink.os << "789"; break;
  2609. case 3: {
  2610. sink.done_with_trailer(
  2611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2612. } break;
  2613. }
  2614. (*i)++;
  2615. return true;
  2616. },
  2617. [i](bool success) {
  2618. EXPECT_TRUE(success);
  2619. delete i;
  2620. });
  2621. })
  2622. .Get("/streamed",
  2623. [&](const Request & /*req*/, Response &res) {
  2624. res.set_content_provider(
  2625. 6, "text/plain",
  2626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2627. sink.os << (offset < 3 ? "a" : "b");
  2628. return true;
  2629. });
  2630. })
  2631. .Get("/streamed-with-range",
  2632. [&](const Request &req, Response &res) {
  2633. auto data = new std::string("abcdefg");
  2634. res.set_content_provider(
  2635. data->size(), "text/plain",
  2636. [data](size_t offset, size_t length, DataSink &sink) {
  2637. size_t DATA_CHUNK_SIZE = 4;
  2638. const auto &d = *data;
  2639. auto out_len =
  2640. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2641. auto ret =
  2642. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2643. EXPECT_TRUE(ret);
  2644. return true;
  2645. },
  2646. [data, &req](bool success) {
  2647. EXPECT_EQ(success, !req.has_param("error"));
  2648. delete data;
  2649. });
  2650. })
  2651. .Get("/streamed-cancel",
  2652. [&](const Request & /*req*/, Response &res) {
  2653. res.set_content_provider(
  2654. size_t(-1), "text/plain",
  2655. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2656. sink.os << "data_chunk";
  2657. return true;
  2658. });
  2659. })
  2660. .Get("/regex-with-delimiter",
  2661. [&](const Request &req, Response & /*res*/) {
  2662. ASSERT_TRUE(req.has_param("key"));
  2663. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2664. })
  2665. .Get("/with-range",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. res.set_content("abcdefg", "text/plain");
  2668. })
  2669. .Get("/test-start-time",
  2670. [&](const Request &req, Response & /*res*/) {
  2671. EXPECT_NE(req.start_time_,
  2672. std::chrono::steady_clock::time_point::min());
  2673. })
  2674. .Get("/with-range-customized-response",
  2675. [&](const Request & /*req*/, Response &res) {
  2676. res.status = StatusCode::BadRequest_400;
  2677. res.set_content(JSON_DATA, "application/json");
  2678. })
  2679. .Post("/chunked",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(req.body, "dechunked post body");
  2682. })
  2683. .Post("/large-chunked",
  2684. [&](const Request &req, Response & /*res*/) {
  2685. std::string expected(6 * 30 * 1024u, 'a');
  2686. EXPECT_EQ(req.body, expected);
  2687. })
  2688. .Post("/multipart",
  2689. [&](const Request &req, Response & /*res*/) {
  2690. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2691. req.form.get_field_count("text2") +
  2692. req.form.get_field_count("file3") +
  2693. req.form.get_field_count("file4"));
  2694. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2695. req.form.get_file_count("file2"));
  2696. ASSERT_TRUE(!req.form.has_file("???"));
  2697. ASSERT_TRUE(!req.form.has_field("???"));
  2698. ASSERT_TRUE(req.body.empty());
  2699. {
  2700. const auto &text = req.form.get_field("text1");
  2701. EXPECT_EQ("text default", text);
  2702. }
  2703. {
  2704. const auto &text = req.form.get_field("text2");
  2705. EXPECT_EQ("aωb", text);
  2706. }
  2707. {
  2708. const auto &file = req.form.get_file("file1");
  2709. EXPECT_EQ("hello.txt", file.filename);
  2710. EXPECT_EQ("text/plain", file.content_type);
  2711. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2712. }
  2713. {
  2714. const auto &file = req.form.get_file("file2");
  2715. EXPECT_EQ("world.json", file.filename);
  2716. EXPECT_EQ("application/json", file.content_type);
  2717. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2718. }
  2719. {
  2720. const auto &text = req.form.get_field("file3");
  2721. EXPECT_EQ(0u, text.size());
  2722. }
  2723. {
  2724. const auto &text = req.form.get_field("file4");
  2725. EXPECT_EQ(0u, text.size());
  2726. }
  2727. })
  2728. .Post("/multipart/multi_file_values",
  2729. [&](const Request &req, Response & /*res*/) {
  2730. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2731. req.form.get_field_count("multi_text1"));
  2732. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2733. ASSERT_TRUE(!req.form.has_file("???"));
  2734. ASSERT_TRUE(!req.form.has_field("???"));
  2735. ASSERT_TRUE(req.body.empty());
  2736. {
  2737. const auto &text = req.form.get_field("text");
  2738. EXPECT_EQ("default text", text);
  2739. }
  2740. {
  2741. const auto &text1_values = req.form.get_fields("multi_text1");
  2742. EXPECT_EQ(2u, text1_values.size());
  2743. EXPECT_EQ("aaaaa", text1_values[0]);
  2744. EXPECT_EQ("bbbbb", text1_values[1]);
  2745. }
  2746. {
  2747. const auto &file1_values = req.form.get_files("multi_file1");
  2748. EXPECT_EQ(2u, file1_values.size());
  2749. auto file1 = file1_values[0];
  2750. EXPECT_EQ(file1.filename, "hello.txt");
  2751. EXPECT_EQ(file1.content_type, "text/plain");
  2752. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2753. auto file2 = file1_values[1];
  2754. EXPECT_EQ(file2.filename, "world.json");
  2755. EXPECT_EQ(file2.content_type, "application/json");
  2756. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2757. }
  2758. })
  2759. .Post("/empty",
  2760. [&](const Request &req, Response &res) {
  2761. EXPECT_EQ(req.body, "");
  2762. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2763. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2764. res.set_content("empty", "text/plain");
  2765. })
  2766. .Post("/empty-no-content-type",
  2767. [&](const Request &req, Response &res) {
  2768. EXPECT_EQ(req.body, "");
  2769. EXPECT_FALSE(req.has_header("Content-Type"));
  2770. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2771. res.set_content("empty-no-content-type", "text/plain");
  2772. })
  2773. .Post("/path-only",
  2774. [&](const Request &req, Response &res) {
  2775. EXPECT_EQ(req.body, "");
  2776. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2777. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2778. res.set_content("path-only", "text/plain");
  2779. })
  2780. .Post("/path-headers-only",
  2781. [&](const Request &req, Response &res) {
  2782. EXPECT_EQ(req.body, "");
  2783. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2784. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2785. EXPECT_EQ("world", req.get_header_value("hello"));
  2786. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2787. res.set_content("path-headers-only", "text/plain");
  2788. })
  2789. .Post("/post-large",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, LARGE_DATA);
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Put("/empty-no-content-type",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(req.body, "");
  2797. EXPECT_FALSE(req.has_header("Content-Type"));
  2798. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2799. res.set_content("empty-no-content-type", "text/plain");
  2800. })
  2801. .Put("/put",
  2802. [&](const Request &req, Response &res) {
  2803. EXPECT_EQ(req.body, "PUT");
  2804. res.set_content(req.body, "text/plain");
  2805. })
  2806. .Put("/put-large",
  2807. [&](const Request &req, Response &res) {
  2808. EXPECT_EQ(req.body, LARGE_DATA);
  2809. res.set_content(req.body, "text/plain");
  2810. })
  2811. .Patch("/patch",
  2812. [&](const Request &req, Response &res) {
  2813. EXPECT_EQ(req.body, "PATCH");
  2814. res.set_content(req.body, "text/plain");
  2815. })
  2816. .Delete("/delete",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. res.set_content("DELETE", "text/plain");
  2819. })
  2820. .Delete("/delete-body",
  2821. [&](const Request &req, Response &res) {
  2822. EXPECT_EQ(req.body, "content");
  2823. res.set_content(req.body, "text/plain");
  2824. })
  2825. .Options(R"(\*)",
  2826. [&](const Request & /*req*/, Response &res) {
  2827. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2828. })
  2829. .Get("/request-target",
  2830. [&](const Request &req, Response & /*res*/) {
  2831. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2832. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2833. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2834. })
  2835. .Get("/long-query-value",
  2836. [&](const Request &req, Response & /*res*/) {
  2837. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2838. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2839. })
  2840. .Get("/too-long-query-value",
  2841. [&](const Request &req, Response & /*res*/) {
  2842. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2843. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2844. })
  2845. .Get("/array-param",
  2846. [&](const Request &req, Response & /*res*/) {
  2847. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2848. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2849. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2850. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2851. })
  2852. .Post("/validate-no-multiple-headers",
  2853. [&](const Request &req, Response & /*res*/) {
  2854. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2855. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2856. })
  2857. .Post("/content_receiver",
  2858. [&](const Request &req, Response &res,
  2859. const ContentReader &content_reader) {
  2860. if (req.is_multipart_form_data()) {
  2861. std::vector<FormData> items;
  2862. content_reader(
  2863. [&](const FormData &file) {
  2864. items.push_back(file);
  2865. return true;
  2866. },
  2867. [&](const char *data, size_t data_length) {
  2868. items.back().content.append(data, data_length);
  2869. return true;
  2870. });
  2871. EXPECT_EQ(5u, items.size());
  2872. {
  2873. const auto &file = get_file_value(items, "text1");
  2874. EXPECT_TRUE(file.filename.empty());
  2875. EXPECT_EQ("text default", file.content);
  2876. }
  2877. {
  2878. const auto &file = get_file_value(items, "text2");
  2879. EXPECT_TRUE(file.filename.empty());
  2880. EXPECT_EQ("aωb", file.content);
  2881. }
  2882. {
  2883. const auto &file = get_file_value(items, "file1");
  2884. EXPECT_EQ("hello.txt", file.filename);
  2885. EXPECT_EQ("text/plain", file.content_type);
  2886. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2887. }
  2888. {
  2889. const auto &file = get_file_value(items, "file2");
  2890. EXPECT_EQ("world.json", file.filename);
  2891. EXPECT_EQ("application/json", file.content_type);
  2892. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2893. }
  2894. {
  2895. const auto &file = get_file_value(items, "file3");
  2896. EXPECT_TRUE(file.filename.empty());
  2897. EXPECT_EQ("application/octet-stream", file.content_type);
  2898. EXPECT_EQ(0u, file.content.size());
  2899. }
  2900. } else {
  2901. std::string body;
  2902. content_reader([&](const char *data, size_t data_length) {
  2903. EXPECT_EQ(7U, data_length);
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. EXPECT_EQ(body, "content");
  2908. res.set_content(body, "text/plain");
  2909. }
  2910. })
  2911. .Put("/content_receiver",
  2912. [&](const Request & /*req*/, Response &res,
  2913. const ContentReader &content_reader) {
  2914. std::string body;
  2915. content_reader([&](const char *data, size_t data_length) {
  2916. body.append(data, data_length);
  2917. return true;
  2918. });
  2919. EXPECT_EQ(body, "content");
  2920. res.set_content(body, "text/plain");
  2921. })
  2922. .Patch("/content_receiver",
  2923. [&](const Request & /*req*/, Response &res,
  2924. const ContentReader &content_reader) {
  2925. std::string body;
  2926. content_reader([&](const char *data, size_t data_length) {
  2927. body.append(data, data_length);
  2928. return true;
  2929. });
  2930. EXPECT_EQ(body, "content");
  2931. res.set_content(body, "text/plain");
  2932. })
  2933. .Post("/query-string-and-body",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. ASSERT_TRUE(req.has_param("key"));
  2936. EXPECT_EQ(req.get_param_value("key"), "value");
  2937. EXPECT_EQ(req.body, "content");
  2938. })
  2939. .Get("/last-request",
  2940. [&](const Request &req, Response & /*res*/) {
  2941. EXPECT_EQ("close", req.get_header_value("Connection"));
  2942. })
  2943. .Get(R"(/redirect/(\d+))",
  2944. [&](const Request &req, Response &res) {
  2945. auto num = std::stoi(req.matches[1]) + 1;
  2946. std::string url = "/redirect/" + std::to_string(num);
  2947. res.set_redirect(url);
  2948. })
  2949. .Post("/binary",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(4U, req.body.size());
  2952. EXPECT_EQ("application/octet-stream",
  2953. req.get_header_value("Content-Type"));
  2954. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2955. res.set_content(req.body, "application/octet-stream");
  2956. })
  2957. .Put("/binary",
  2958. [&](const Request &req, Response &res) {
  2959. EXPECT_EQ(4U, req.body.size());
  2960. EXPECT_EQ("application/octet-stream",
  2961. req.get_header_value("Content-Type"));
  2962. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2963. res.set_content(req.body, "application/octet-stream");
  2964. })
  2965. .Patch("/binary",
  2966. [&](const Request &req, Response &res) {
  2967. EXPECT_EQ(4U, req.body.size());
  2968. EXPECT_EQ("application/octet-stream",
  2969. req.get_header_value("Content-Type"));
  2970. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2971. res.set_content(req.body, "application/octet-stream");
  2972. })
  2973. .Delete("/binary",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(4U, req.body.size());
  2976. EXPECT_EQ("application/octet-stream",
  2977. req.get_header_value("Content-Type"));
  2978. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2979. res.set_content(req.body, "application/octet-stream");
  2980. })
  2981. .Get("/issue1772",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = 401;
  2984. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2985. })
  2986. .Delete("/issue609",
  2987. [](const httplib::Request &, httplib::Response &res,
  2988. const httplib::ContentReader &) {
  2989. res.set_content("ok", "text/plain");
  2990. })
  2991. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2992. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2993. .Get("/compress",
  2994. [&](const Request & /*req*/, Response &res) {
  2995. res.set_content(
  2996. "12345678901234567890123456789012345678901234567890123456789"
  2997. "01234567890123456789012345678901234567890",
  2998. "text/plain");
  2999. })
  3000. .Get("/nocompress",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content(
  3003. "12345678901234567890123456789012345678901234567890123456789"
  3004. "01234567890123456789012345678901234567890",
  3005. "application/octet-stream");
  3006. })
  3007. .Post("/compress-multipart",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_EQ(2u, req.form.fields.size());
  3010. ASSERT_TRUE(!req.form.has_field("???"));
  3011. {
  3012. const auto &text = req.form.get_field("key1");
  3013. EXPECT_EQ("test", text);
  3014. }
  3015. {
  3016. const auto &text = req.form.get_field("key2");
  3017. EXPECT_EQ("--abcdefg123", text);
  3018. }
  3019. })
  3020. #endif
  3021. ;
  3022. persons_["john"] = "programmer";
  3023. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3024. svr_.wait_until_ready();
  3025. }
  3026. virtual void TearDown() {
  3027. svr_.stop();
  3028. if (!request_threads_.empty()) {
  3029. std::this_thread::sleep_for(std::chrono::seconds(1));
  3030. for (auto &t : request_threads_) {
  3031. t.join();
  3032. }
  3033. }
  3034. t_.join();
  3035. }
  3036. map<string, string> persons_;
  3037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3038. SSLClient cli_;
  3039. SSLServer svr_;
  3040. #else
  3041. Client cli_;
  3042. Server svr_;
  3043. #endif
  3044. thread t_;
  3045. std::vector<thread> request_threads_;
  3046. };
  3047. TEST_F(ServerTest, GetMethod200) {
  3048. auto res = cli_.Get("/hi");
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ("HTTP/1.1", res->version);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. EXPECT_EQ("OK", res->reason);
  3053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3054. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3055. EXPECT_EQ("Hello World!", res->body);
  3056. }
  3057. void performance_test(const char *host) {
  3058. auto port = 1234;
  3059. Server svr;
  3060. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3061. res.set_content("Benchmark Response", "text/plain");
  3062. });
  3063. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. listen_thread.join();
  3067. ASSERT_FALSE(svr.is_running());
  3068. });
  3069. svr.wait_until_ready();
  3070. Client cli(host, port);
  3071. auto start = std::chrono::high_resolution_clock::now();
  3072. auto res = cli.Get("/benchmark");
  3073. ASSERT_TRUE(res);
  3074. EXPECT_EQ(StatusCode::OK_200, res->status);
  3075. auto end = std::chrono::high_resolution_clock::now();
  3076. auto elapsed =
  3077. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3078. .count();
  3079. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3080. << "ms (Issue #1777)";
  3081. }
  3082. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3083. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3084. TEST_F(ServerTest, GetEmptyFile) {
  3085. auto res = cli_.Get("/empty_file");
  3086. ASSERT_TRUE(res);
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3089. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3090. EXPECT_EQ("", res->body);
  3091. }
  3092. TEST_F(ServerTest, GetFileContent) {
  3093. auto res = cli_.Get("/file_content");
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3097. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3098. EXPECT_EQ("test.html", res->body);
  3099. }
  3100. TEST_F(ServerTest, GetFileContentWithRange) {
  3101. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3105. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3106. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3107. EXPECT_EQ("est", res->body);
  3108. }
  3109. TEST_F(ServerTest, GetFileContentWithContentType) {
  3110. auto res = cli_.Get("/file_content_with_content_type");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3114. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3115. EXPECT_EQ("file\n", res->body);
  3116. }
  3117. TEST_F(ServerTest, GetInvalidFileContent) {
  3118. auto res = cli_.Get("/invalid_file_content");
  3119. ASSERT_TRUE(res);
  3120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3121. }
  3122. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3123. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3124. ASSERT_TRUE(res);
  3125. EXPECT_EQ("HTTP/1.1", res->version);
  3126. EXPECT_EQ(StatusCode::OK_200, res->status);
  3127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3128. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3129. EXPECT_EQ("Hello World!", res->body);
  3130. }
  3131. TEST_F(ServerTest, GetMethod302) {
  3132. auto res = cli_.Get("/");
  3133. ASSERT_TRUE(res);
  3134. EXPECT_EQ(StatusCode::Found_302, res->status);
  3135. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3136. }
  3137. TEST_F(ServerTest, GetMethod302Redirect) {
  3138. cli_.set_follow_location(true);
  3139. auto res = cli_.Get("/");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. EXPECT_EQ("/hi", res->location);
  3144. }
  3145. TEST_F(ServerTest, GetMethod404) {
  3146. auto res = cli_.Get("/invalid");
  3147. ASSERT_TRUE(res);
  3148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3149. }
  3150. TEST_F(ServerTest, HeadMethod200) {
  3151. auto res = cli_.Head("/hi");
  3152. ASSERT_TRUE(res);
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3155. EXPECT_TRUE(res->body.empty());
  3156. }
  3157. TEST_F(ServerTest, HeadMethod200Static) {
  3158. auto res = cli_.Head("/mount/dir/index.html");
  3159. ASSERT_TRUE(res);
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3162. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3163. EXPECT_TRUE(res->body.empty());
  3164. }
  3165. TEST_F(ServerTest, HeadMethod404) {
  3166. auto res = cli_.Head("/invalid");
  3167. ASSERT_TRUE(res);
  3168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3169. EXPECT_TRUE(res->body.empty());
  3170. }
  3171. TEST_F(ServerTest, GetMethodPersonJohn) {
  3172. auto res = cli_.Get("/person/john");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3176. EXPECT_EQ("programmer", res->body);
  3177. }
  3178. TEST_F(ServerTest, PostMethod1) {
  3179. auto res = cli_.Get("/person/john1");
  3180. ASSERT_TRUE(res);
  3181. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3182. res = cli_.Post("/person", "name=john1&note=coder",
  3183. "application/x-www-form-urlencoded");
  3184. ASSERT_TRUE(res);
  3185. ASSERT_EQ(StatusCode::OK_200, res->status);
  3186. res = cli_.Get("/person/john1");
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::OK_200, res->status);
  3189. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3190. ASSERT_EQ("coder", res->body);
  3191. }
  3192. TEST_F(ServerTest, PostMethod2) {
  3193. auto res = cli_.Get("/person/john2");
  3194. ASSERT_TRUE(res);
  3195. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3196. Params params;
  3197. params.emplace("name", "john2");
  3198. params.emplace("note", "coder");
  3199. res = cli_.Post("/person", params);
  3200. ASSERT_TRUE(res);
  3201. ASSERT_EQ(StatusCode::OK_200, res->status);
  3202. res = cli_.Get("/person/john2");
  3203. ASSERT_TRUE(res);
  3204. ASSERT_EQ(StatusCode::OK_200, res->status);
  3205. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3206. ASSERT_EQ("coder", res->body);
  3207. }
  3208. TEST_F(ServerTest, PutMethod3) {
  3209. auto res = cli_.Get("/person/john3");
  3210. ASSERT_TRUE(res);
  3211. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3212. Params params;
  3213. params.emplace("name", "john3");
  3214. params.emplace("note", "coder");
  3215. res = cli_.Put("/person", params);
  3216. ASSERT_TRUE(res);
  3217. ASSERT_EQ(StatusCode::OK_200, res->status);
  3218. res = cli_.Get("/person/john3");
  3219. ASSERT_TRUE(res);
  3220. ASSERT_EQ(StatusCode::OK_200, res->status);
  3221. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. ASSERT_EQ("coder", res->body);
  3223. }
  3224. TEST_F(ServerTest, DeleteMethod1) {
  3225. auto res = cli_.Get("/person/john4");
  3226. ASSERT_TRUE(res);
  3227. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3228. Params params;
  3229. params.emplace("name", "john4");
  3230. params.emplace("note", "coder");
  3231. res = cli_.Post("/person", params);
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. res = cli_.Get("/person/john4");
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(StatusCode::OK_200, res->status);
  3237. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3238. ASSERT_EQ("coder", res->body);
  3239. Params delete_params;
  3240. delete_params.emplace("name", "john4");
  3241. res = cli_.Delete("/person", delete_params);
  3242. ASSERT_TRUE(res);
  3243. ASSERT_EQ(StatusCode::OK_200, res->status);
  3244. ASSERT_EQ("DELETED", res->body);
  3245. res = cli_.Get("/person/john4");
  3246. ASSERT_TRUE(res);
  3247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3248. }
  3249. TEST_F(ServerTest, DeleteMethod2) {
  3250. auto res = cli_.Get("/person/john5");
  3251. ASSERT_TRUE(res);
  3252. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3253. Params params;
  3254. params.emplace("name", "john5");
  3255. params.emplace("note", "developer");
  3256. res = cli_.Post("/person", params);
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. res = cli_.Get("/person/john5");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::OK_200, res->status);
  3262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. ASSERT_EQ("developer", res->body);
  3264. Params delete_params;
  3265. delete_params.emplace("name", "john5");
  3266. Headers headers;
  3267. headers.emplace("Custom-Header", "test-value");
  3268. res = cli_.Delete("/person", headers, delete_params);
  3269. ASSERT_TRUE(res);
  3270. ASSERT_EQ(StatusCode::OK_200, res->status);
  3271. ASSERT_EQ("DELETED", res->body);
  3272. res = cli_.Get("/person/john5");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3275. }
  3276. TEST_F(ServerTest, DeleteMethod3) {
  3277. auto res = cli_.Get("/person/john6");
  3278. ASSERT_TRUE(res);
  3279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3280. Params params;
  3281. params.emplace("name", "john6");
  3282. params.emplace("note", "tester");
  3283. res = cli_.Post("/person", params);
  3284. ASSERT_TRUE(res);
  3285. ASSERT_EQ(StatusCode::OK_200, res->status);
  3286. res = cli_.Get("/person/john6");
  3287. ASSERT_TRUE(res);
  3288. ASSERT_EQ(StatusCode::OK_200, res->status);
  3289. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3290. ASSERT_EQ("tester", res->body);
  3291. Params delete_params;
  3292. delete_params.emplace("name", "john6");
  3293. Headers headers;
  3294. headers.emplace("Custom-Header", "test-value");
  3295. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john6");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3304. Params params;
  3305. params.emplace("json", JSON_DATA);
  3306. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3307. ASSERT_TRUE(res);
  3308. ASSERT_EQ(StatusCode::OK_200, res->status);
  3309. ASSERT_EQ(JSON_DATA, res->body);
  3310. }
  3311. TEST_F(ServerTest, PostEmptyContent) {
  3312. auto res = cli_.Post("/empty", "", "text/plain");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::OK_200, res->status);
  3315. ASSERT_EQ("empty", res->body);
  3316. }
  3317. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3318. auto res = cli_.Post("/empty-no-content-type");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("empty-no-content-type", res->body);
  3322. }
  3323. TEST_F(ServerTest, PostPathOnly) {
  3324. auto res = cli_.Post("/path-only");
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::OK_200, res->status);
  3327. ASSERT_EQ("path-only", res->body);
  3328. }
  3329. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3330. auto res = cli_.Post("/path-headers-only",
  3331. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ("path-headers-only", res->body);
  3335. }
  3336. TEST_F(ServerTest, PostLarge) {
  3337. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. EXPECT_EQ(LARGE_DATA, res->body);
  3341. }
  3342. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3343. auto res = cli_.Put("/empty-no-content-type");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("empty-no-content-type", res->body);
  3347. }
  3348. TEST_F(ServerTest, GetMethodDir) {
  3349. auto res = cli_.Get("/dir/");
  3350. ASSERT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3353. auto body = R"(<html>
  3354. <head>
  3355. </head>
  3356. <body>
  3357. <a href="/dir/test.html">Test</a>
  3358. <a href="/hi">hi</a>
  3359. </body>
  3360. </html>
  3361. )";
  3362. EXPECT_EQ(body, res->body);
  3363. }
  3364. TEST_F(ServerTest, GetMethodDirTest) {
  3365. auto res = cli_.Get("/dir/test.html");
  3366. ASSERT_TRUE(res);
  3367. EXPECT_EQ(StatusCode::OK_200, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("test.html", res->body);
  3370. }
  3371. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3372. auto res = cli_.Get("/dir/../dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3376. EXPECT_EQ("test.html", res->body);
  3377. }
  3378. TEST_F(ServerTest, GetMethodInvalidPath) {
  3379. auto res = cli_.Get("/dir/../test.html");
  3380. ASSERT_TRUE(res);
  3381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3382. }
  3383. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3384. auto res = cli_.Get("/../www/dir/test.html");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3387. }
  3388. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3389. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3392. }
  3393. TEST_F(ServerTest, GetMethodDirMountTest) {
  3394. auto res = cli_.Get("/mount/dir/test.html");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ("test.html", res->body);
  3399. }
  3400. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3401. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::OK_200, res->status);
  3404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3405. EXPECT_EQ("test.html", res->body);
  3406. }
  3407. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3408. auto res = cli_.Get("/mount/dir/../test.html");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3413. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3418. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3421. }
  3422. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3423. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3426. }
  3427. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3428. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3429. ASSERT_TRUE(res);
  3430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3431. }
  3432. TEST_F(ServerTest, PostMethod303) {
  3433. auto res = cli_.Post("/1", "body", "text/plain");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3436. EXPECT_EQ("/2", res->get_header_value("Location"));
  3437. }
  3438. TEST_F(ServerTest, PostMethod303Redirect) {
  3439. cli_.set_follow_location(true);
  3440. auto res = cli_.Post("/1", "body", "text/plain");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("redirected.", res->body);
  3444. EXPECT_EQ("/2", res->location);
  3445. }
  3446. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3447. auto res = cli_.Get("/dir/test.abcde");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ("abcde", res->body);
  3452. }
  3453. TEST_F(ServerTest, StaticFileRange) {
  3454. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3457. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ(true, res->has_header("Content-Range"));
  3460. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3461. EXPECT_EQ(std::string("cd"), res->body);
  3462. }
  3463. TEST_F(ServerTest, StaticFileRanges) {
  3464. auto res =
  3465. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_TRUE(
  3469. res->get_header_value("Content-Type")
  3470. .find(
  3471. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3472. 0);
  3473. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3474. }
  3475. TEST_F(ServerTest, StaticFileRangeHead) {
  3476. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3480. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3481. EXPECT_EQ(true, res->has_header("Content-Range"));
  3482. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3483. }
  3484. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3485. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3486. ASSERT_TRUE(res);
  3487. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3489. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3490. EXPECT_EQ(true, res->has_header("Content-Range"));
  3491. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3492. res->get_header_value("Content-Range"));
  3493. EXPECT_EQ("LAST\n", res->body);
  3494. }
  3495. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3496. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3500. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3501. EXPECT_EQ(true, res->has_header("Content-Range"));
  3502. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3503. }
  3504. TEST_F(ServerTest, StaticFileBigFile) {
  3505. auto res = cli_.Get("/dir/1MB.txt");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3509. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3510. }
  3511. TEST_F(ServerTest, InvalidBaseDirMount) {
  3512. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3513. }
  3514. TEST_F(ServerTest, Binary) {
  3515. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3516. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3517. "application/octet-stream");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. ASSERT_EQ(4U, res->body.size());
  3521. res = cli_.Put("/binary", binary.data(), binary.size(),
  3522. "application/octet-stream");
  3523. ASSERT_TRUE(res);
  3524. ASSERT_EQ(StatusCode::OK_200, res->status);
  3525. ASSERT_EQ(4U, res->body.size());
  3526. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3527. "application/octet-stream");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. ASSERT_EQ(4U, res->body.size());
  3531. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3532. "application/octet-stream");
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. ASSERT_EQ(4U, res->body.size());
  3536. }
  3537. TEST_F(ServerTest, BinaryString) {
  3538. auto binary = std::string("\x00\x01\x02\x03", 4);
  3539. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ(4U, res->body.size());
  3543. res = cli_.Put("/binary", binary, "application/octet-stream");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::OK_200, res->status);
  3546. ASSERT_EQ(4U, res->body.size());
  3547. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ(4U, res->body.size());
  3551. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ(4U, res->body.size());
  3555. }
  3556. TEST_F(ServerTest, EmptyRequest) {
  3557. auto res = cli_.Get("");
  3558. ASSERT_TRUE(!res);
  3559. EXPECT_EQ(Error::Connection, res.error());
  3560. }
  3561. TEST_F(ServerTest, LongRequest) {
  3562. std::string request;
  3563. for (size_t i = 0; i < 545; i++) {
  3564. request += "/TooLongRequest";
  3565. }
  3566. request += "OK";
  3567. auto res = cli_.Get(request.c_str());
  3568. ASSERT_TRUE(res);
  3569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3570. }
  3571. TEST_F(ServerTest, TooLongRequest) {
  3572. std::string request;
  3573. for (size_t i = 0; i < 546; i++) {
  3574. request += "/TooLongRequest";
  3575. }
  3576. request += "_NG";
  3577. auto res = cli_.Get(request.c_str());
  3578. ASSERT_TRUE(res);
  3579. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3580. }
  3581. TEST_F(ServerTest, AlmostTooLongRequest) {
  3582. // test for #2046 - URI length check shouldn't include other content on req
  3583. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3584. // leading /, space, HTTP/1.1)
  3585. std::string request =
  3586. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3587. auto res = cli_.Get(request.c_str());
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3590. }
  3591. TEST_F(ServerTest, LongHeader) {
  3592. Request req;
  3593. req.method = "GET";
  3594. req.path = "/hi";
  3595. std::string host_and_port;
  3596. host_and_port += HOST;
  3597. host_and_port += ":";
  3598. host_and_port += std::to_string(PORT);
  3599. req.headers.emplace("Host", host_and_port.c_str());
  3600. req.headers.emplace("Accept", "*/*");
  3601. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3602. req.headers.emplace(
  3603. "Header-Name",
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@");
  3633. auto res = std::make_shared<Response>();
  3634. auto error = Error::Success;
  3635. auto ret = cli_.send(req, *res, error);
  3636. ASSERT_TRUE(ret);
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. }
  3639. TEST_F(ServerTest, LongQueryValue) {
  3640. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3643. }
  3644. TEST_F(ServerTest, TooLongQueryValue) {
  3645. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3646. ASSERT_FALSE(res);
  3647. EXPECT_EQ(Error::Read, res.error());
  3648. }
  3649. TEST_F(ServerTest, TooLongHeader) {
  3650. Request req;
  3651. req.method = "GET";
  3652. req.path = "/hi";
  3653. std::string host_and_port;
  3654. host_and_port += HOST;
  3655. host_and_port += ":";
  3656. host_and_port += std::to_string(PORT);
  3657. req.headers.emplace("Host", host_and_port.c_str());
  3658. req.headers.emplace("Accept", "*/*");
  3659. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3660. req.headers.emplace(
  3661. "Header-Name",
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@");
  3691. auto res = std::make_shared<Response>();
  3692. auto error = Error::Success;
  3693. auto ret = cli_.send(req, *res, error);
  3694. ASSERT_TRUE(ret);
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. }
  3697. TEST_F(ServerTest, HeaderCountAtLimit) {
  3698. // Test with headers just under the 100 limit
  3699. httplib::Headers headers;
  3700. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3701. // This should keep us just under the 100 header limit
  3702. for (int i = 0; i < 95; i++) {
  3703. std::string name = "X-Test-Header-" + std::to_string(i);
  3704. std::string value = "value" + std::to_string(i);
  3705. headers.emplace(name, value);
  3706. }
  3707. // This should work fine as we're under the limit
  3708. auto res = cli_.Get("/hi", headers);
  3709. EXPECT_TRUE(res);
  3710. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3711. }
  3712. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3713. // Test with many headers to exceed the 100 limit
  3714. httplib::Headers headers;
  3715. // Add 150 headers to definitely exceed the 100 limit
  3716. for (int i = 0; i < 150; i++) {
  3717. std::string name = "X-Test-Header-" + std::to_string(i);
  3718. std::string value = "value" + std::to_string(i);
  3719. headers.emplace(name, value);
  3720. }
  3721. // This should fail due to exceeding header count limit
  3722. auto res = cli_.Get("/hi", headers);
  3723. // The request should either fail or return 400 Bad Request
  3724. if (res) {
  3725. // If we get a response, it should be 400 Bad Request
  3726. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3727. } else {
  3728. // Or the request should fail entirely
  3729. EXPECT_FALSE(res);
  3730. }
  3731. }
  3732. TEST_F(ServerTest, PercentEncoding) {
  3733. auto res = cli_.Get("/e%6edwith%");
  3734. ASSERT_TRUE(res);
  3735. EXPECT_EQ(StatusCode::OK_200, res->status);
  3736. }
  3737. TEST_F(ServerTest, PercentEncodingUnicode) {
  3738. auto res = cli_.Get("/e%u006edwith%");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, InvalidPercentEncoding) {
  3743. auto res = cli_.Get("/%endwith%");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3748. auto res = cli_.Get("/%uendwith%");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3753. auto res = cli_.Get("/hello?aaa=bbb%");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, PlusSignEncoding) {
  3758. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. EXPECT_EQ("a +b", res->body);
  3762. }
  3763. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3764. // This test simulates a potential DoS attack using many headers
  3765. // to verify our security fix prevents memory exhaustion
  3766. httplib::Headers attack_headers;
  3767. // Attempt to add many headers like an attacker would (200 headers to far
  3768. // exceed limit)
  3769. for (int i = 0; i < 200; i++) {
  3770. std::string name = "X-Attack-Header-" + std::to_string(i);
  3771. std::string value = "attack_payload_" + std::to_string(i);
  3772. attack_headers.emplace(name, value);
  3773. }
  3774. // Try to POST with excessive headers
  3775. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3776. // Should either fail or return 400 Bad Request due to security limit
  3777. if (res) {
  3778. // If we get a response, it should be 400 Bad Request
  3779. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3780. } else {
  3781. // Request failed, which is the expected behavior for DoS protection
  3782. EXPECT_FALSE(res);
  3783. }
  3784. }
  3785. TEST_F(ServerTest, MultipartFormData) {
  3786. UploadFormDataItems items = {
  3787. {"text1", "text default", "", ""},
  3788. {"text2", "aωb", "", ""},
  3789. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3790. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3791. {"file3", "", "", "application/octet-stream"},
  3792. {"file4", "", "", " application/json tmp-string "}};
  3793. auto res = cli_.Post("/multipart", items);
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::OK_200, res->status);
  3796. }
  3797. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3798. UploadFormDataItems items = {
  3799. {"text", "default text", "", ""},
  3800. {"multi_text1", "aaaaa", "", ""},
  3801. {"multi_text1", "bbbbb", "", ""},
  3802. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3803. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3804. "application/json"},
  3805. };
  3806. auto res = cli_.Post("/multipart/multi_file_values", items);
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. }
  3810. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3811. auto res = cli_.Get("/hi");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3815. EXPECT_EQ("Hello World!", res->body);
  3816. }
  3817. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3818. Request req;
  3819. req.method = "POST";
  3820. req.path = "/chunked";
  3821. std::string host_and_port;
  3822. host_and_port += HOST;
  3823. host_and_port += ":";
  3824. host_and_port += std::to_string(PORT);
  3825. req.headers.emplace("Host", host_and_port.c_str());
  3826. req.headers.emplace("Accept", "*/*");
  3827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3828. req.headers.emplace("Content-Type", "text/plain");
  3829. req.headers.emplace("Content-Length", "0");
  3830. req.headers.emplace(
  3831. "Transfer-Encoding",
  3832. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3833. // Client does not chunk, so make a chunked body manually.
  3834. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3835. auto res = std::make_shared<Response>();
  3836. auto error = Error::Success;
  3837. auto ret = cli_.send(req, *res, error);
  3838. ASSERT_TRUE(ret);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. }
  3841. TEST_F(ServerTest, GetStreamed2) {
  3842. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3845. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3846. EXPECT_EQ(true, res->has_header("Content-Range"));
  3847. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3848. EXPECT_EQ(std::string("ab"), res->body);
  3849. }
  3850. TEST_F(ServerTest, GetStreamed) {
  3851. auto res = cli_.Get("/streamed");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::OK_200, res->status);
  3854. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3855. EXPECT_EQ(std::string("aaabbb"), res->body);
  3856. }
  3857. TEST_F(ServerTest, GetStreamedWithRange1) {
  3858. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3859. ASSERT_TRUE(res);
  3860. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3861. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3862. EXPECT_EQ(true, res->has_header("Content-Range"));
  3863. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3864. EXPECT_EQ(std::string("def"), res->body);
  3865. }
  3866. TEST_F(ServerTest, GetStreamedWithRange2) {
  3867. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3870. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3871. EXPECT_EQ(true, res->has_header("Content-Range"));
  3872. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3873. EXPECT_EQ(std::string("bcdefg"), res->body);
  3874. }
  3875. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3876. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3879. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3880. EXPECT_EQ(true, res->has_header("Content-Range"));
  3881. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3882. EXPECT_EQ(std::string("efg"), res->body);
  3883. }
  3884. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3885. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3888. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(false, res->has_header("Content-Range"));
  3890. EXPECT_EQ(0U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3893. auto res = cli_.Get("/streamed-with-range",
  3894. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3895. "92233720368547758079223372036854775807"}});
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3898. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3899. EXPECT_EQ(false, res->has_header("Content-Range"));
  3900. EXPECT_EQ(0U, res->body.size());
  3901. }
  3902. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3903. auto res = cli_.Get(
  3904. "/with-range",
  3905. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3906. {"Accept-Encoding", ""}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(true, res->has_header("Content-Range"));
  3911. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3912. EXPECT_EQ(std::string("abcdefg"), res->body);
  3913. }
  3914. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3915. auto res = cli_.Get("/with-range", {
  3916. {"Range", "bytes=0-"},
  3917. {"Accept-Encoding", ""},
  3918. });
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3921. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3922. EXPECT_EQ(true, res->has_header("Content-Range"));
  3923. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3924. EXPECT_EQ(std::string("abcdefg"), res->body);
  3925. }
  3926. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3927. auto res =
  3928. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3929. ASSERT_TRUE(res);
  3930. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3931. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(false, res->has_header("Content-Range"));
  3933. EXPECT_EQ(267U, res->body.size());
  3934. // Check that both range contents are present
  3935. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3936. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3937. // Check that Content-Range headers are present for both ranges
  3938. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3939. std::string::npos);
  3940. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3941. std::string::npos);
  3942. }
  3943. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3944. Ranges ranges;
  3945. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3946. ranges.emplace_back(0, -1);
  3947. }
  3948. auto res =
  3949. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3952. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3953. EXPECT_EQ(false, res->has_header("Content-Range"));
  3954. EXPECT_EQ(0U, res->body.size());
  3955. }
  3956. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3957. auto res =
  3958. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ(5U, res->body.size());
  3962. // Check that overlapping ranges are coalesced into a single range
  3963. EXPECT_EQ("bcdef", res->body);
  3964. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3965. // Should be single range, not multipart
  3966. EXPECT_TRUE(res->has_header("Content-Range"));
  3967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3968. }
  3969. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3970. auto res =
  3971. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3974. EXPECT_EQ(268U, res->body.size());
  3975. // Check that both range contents are present
  3976. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3977. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3978. // Check that Content-Range headers are present for both ranges
  3979. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3980. std::string::npos);
  3981. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3982. std::string::npos);
  3983. }
  3984. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3985. auto res =
  3986. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3987. ASSERT_TRUE(res);
  3988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3989. EXPECT_EQ(269U, res->body.size());
  3990. // Check that both duplicate range contents are present
  3991. size_t first_abc = res->body.find("abc\r\n");
  3992. EXPECT_TRUE(first_abc != std::string::npos);
  3993. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3994. EXPECT_TRUE(second_abc != std::string::npos);
  3995. // Check that Content-Range headers are present for both ranges
  3996. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3997. EXPECT_TRUE(first_range != std::string::npos);
  3998. size_t second_range =
  3999. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4000. EXPECT_TRUE(second_range != std::string::npos);
  4001. }
  4002. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4003. auto res = cli_.Get("/streamed-with-range?error",
  4004. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. EXPECT_EQ(false, res->has_header("Content-Range"));
  4009. EXPECT_EQ(0U, res->body.size());
  4010. }
  4011. TEST_F(ServerTest, GetStreamedEndless) {
  4012. uint64_t offset = 0;
  4013. auto res = cli_.Get("/streamed-cancel",
  4014. [&](const char * /*data*/, uint64_t data_length) {
  4015. if (offset < 100) {
  4016. offset += data_length;
  4017. return true;
  4018. }
  4019. return false;
  4020. });
  4021. ASSERT_TRUE(!res);
  4022. EXPECT_EQ(Error::Canceled, res.error());
  4023. }
  4024. TEST_F(ServerTest, ClientStop) {
  4025. std::atomic_size_t count{4};
  4026. std::vector<std::thread> threads;
  4027. for (auto i = count.load(); i != 0; --i) {
  4028. threads.emplace_back([&]() {
  4029. auto res = cli_.Get("/streamed-cancel",
  4030. [&](const char *, uint64_t) { return true; });
  4031. --count;
  4032. ASSERT_TRUE(!res);
  4033. EXPECT_TRUE(res.error() == Error::Canceled ||
  4034. res.error() == Error::Read || res.error() == Error::Write);
  4035. });
  4036. }
  4037. std::this_thread::sleep_for(std::chrono::seconds(2));
  4038. while (count != 0) {
  4039. cli_.stop();
  4040. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4041. }
  4042. for (auto &t : threads) {
  4043. t.join();
  4044. }
  4045. }
  4046. TEST_F(ServerTest, GetWithRange1) {
  4047. auto res = cli_.Get("/with-range", {
  4048. make_range_header({{3, 5}}),
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("def"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetWithRange2) {
  4059. auto res = cli_.Get("/with-range", {
  4060. make_range_header({{1, -1}}),
  4061. {"Accept-Encoding", ""},
  4062. });
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4068. EXPECT_EQ(std::string("bcdefg"), res->body);
  4069. }
  4070. TEST_F(ServerTest, GetWithRange3) {
  4071. auto res = cli_.Get("/with-range", {
  4072. make_range_header({{0, 0}}),
  4073. {"Accept-Encoding", ""},
  4074. });
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4077. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4078. EXPECT_EQ(true, res->has_header("Content-Range"));
  4079. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4080. EXPECT_EQ(std::string("a"), res->body);
  4081. }
  4082. TEST_F(ServerTest, GetWithRange4) {
  4083. auto res = cli_.Get("/with-range", {
  4084. make_range_header({{-1, 2}}),
  4085. {"Accept-Encoding", ""},
  4086. });
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4089. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4090. EXPECT_EQ(true, res->has_header("Content-Range"));
  4091. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4092. EXPECT_EQ(std::string("fg"), res->body);
  4093. }
  4094. TEST_F(ServerTest, GetWithRange5) {
  4095. auto res = cli_.Get("/with-range", {
  4096. make_range_header({{0, 5}}),
  4097. {"Accept-Encoding", ""},
  4098. });
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("abcdef"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4107. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4110. }
  4111. TEST_F(ServerTest, GetWithRangeMultipart) {
  4112. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4115. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4116. EXPECT_EQ(false, res->has_header("Content-Range"));
  4117. EXPECT_EQ(267U, res->body.size());
  4118. }
  4119. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4120. auto res =
  4121. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4124. }
  4125. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4126. auto res = cli_.Get("/with-range-customized-response",
  4127. {{make_range_header({{1, 2}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4130. EXPECT_EQ(true, res->has_header("Content-Length"));
  4131. EXPECT_EQ(false, res->has_header("Content-Range"));
  4132. EXPECT_EQ(JSON_DATA, res->body);
  4133. }
  4134. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4135. auto res = cli_.Get("/with-range-customized-response",
  4136. {{make_range_header({{1, 2}, {4, 5}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4139. EXPECT_EQ(true, res->has_header("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(JSON_DATA, res->body);
  4142. }
  4143. TEST_F(ServerTest, Issue1772) {
  4144. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4147. }
  4148. TEST_F(ServerTest, Issue609) {
  4149. auto res = cli_.Delete("/issue609");
  4150. ASSERT_TRUE(res);
  4151. EXPECT_EQ(StatusCode::OK_200, res->status);
  4152. EXPECT_EQ(std::string("ok"), res->body);
  4153. }
  4154. TEST_F(ServerTest, GetStreamedChunked) {
  4155. auto res = cli_.Get("/streamed-chunked");
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::OK_200, res->status);
  4158. EXPECT_EQ(std::string("123456789"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetStreamedChunked2) {
  4161. auto res = cli_.Get("/streamed-chunked2");
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::OK_200, res->status);
  4164. EXPECT_EQ(std::string("123456789"), res->body);
  4165. }
  4166. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4167. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. EXPECT_EQ(std::string("123456789"), res->body);
  4171. EXPECT_TRUE(res->has_header("Trailer"));
  4172. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4173. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4174. // Trailers are now stored separately from headers (security fix)
  4175. EXPECT_EQ(2U, res->trailers.size());
  4176. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4177. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4178. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4179. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4180. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4181. // Verify trailers are NOT in headers (security verification)
  4182. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4183. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4184. }
  4185. TEST_F(ServerTest, LargeChunkedPost) {
  4186. Request req;
  4187. req.method = "POST";
  4188. req.path = "/large-chunked";
  4189. std::string host_and_port;
  4190. host_and_port += HOST;
  4191. host_and_port += ":";
  4192. host_and_port += std::to_string(PORT);
  4193. req.headers.emplace("Host", host_and_port.c_str());
  4194. req.headers.emplace("Accept", "*/*");
  4195. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4196. req.headers.emplace("Content-Type", "text/plain");
  4197. req.headers.emplace("Content-Length", "0");
  4198. req.headers.emplace("Transfer-Encoding", "chunked");
  4199. std::string long_string(30 * 1024u, 'a');
  4200. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4201. // Attempt to make a large enough post to exceed OS buffers, to test that
  4202. // the server handles short reads if the full chunk data isn't available.
  4203. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4204. auto res = std::make_shared<Response>();
  4205. auto error = Error::Success;
  4206. auto ret = cli_.send(req, *res, error);
  4207. ASSERT_TRUE(ret);
  4208. EXPECT_EQ(StatusCode::OK_200, res->status);
  4209. }
  4210. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4211. auto res = cli_.Get("/remote_addr");
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4215. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4216. }
  4217. TEST_F(ServerTest, GetMethodLocalAddr) {
  4218. auto res = cli_.Get("/local_addr");
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4222. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4223. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4224. }
  4225. TEST_F(ServerTest, HTTPResponseSplitting) {
  4226. auto res = cli_.Get("/http_response_splitting");
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. }
  4230. TEST_F(ServerTest, SlowRequest) {
  4231. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4232. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4233. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4234. }
  4235. #if 0
  4236. TEST_F(ServerTest, SlowPost) {
  4237. char buffer[64 * 1024];
  4238. memset(buffer, 0x42, sizeof(buffer));
  4239. auto res = cli_.Post(
  4240. "/slowpost", 64 * 1024 * 1024,
  4241. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4242. auto ret = sink.write(buffer, sizeof(buffer));
  4243. EXPECT_TRUE(ret);
  4244. return true;
  4245. },
  4246. "text/plain");
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::OK_200, res->status);
  4249. }
  4250. TEST_F(ServerTest, SlowPostFail) {
  4251. char buffer[64 * 1024];
  4252. memset(buffer, 0x42, sizeof(buffer));
  4253. cli_.set_write_timeout(std::chrono::seconds(0));
  4254. auto res = cli_.Post(
  4255. "/slowpost", 64 * 1024 * 1024,
  4256. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4257. sink.write(buffer, sizeof(buffer));
  4258. return true;
  4259. },
  4260. "text/plain");
  4261. ASSERT_TRUE(!res);
  4262. EXPECT_EQ(Error::Write, res.error());
  4263. }
  4264. #endif
  4265. TEST_F(ServerTest, Put) {
  4266. auto res = cli_.Put("/put", "PUT", "text/plain");
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::OK_200, res->status);
  4269. EXPECT_EQ("PUT", res->body);
  4270. }
  4271. TEST_F(ServerTest, PutWithContentProvider) {
  4272. auto res = cli_.Put(
  4273. "/put", 3,
  4274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4275. sink.os << "PUT";
  4276. return true;
  4277. },
  4278. "text/plain");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("PUT", res->body);
  4282. }
  4283. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4284. auto res = cli_.Post(
  4285. "/post", 42,
  4286. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4287. return false;
  4288. },
  4289. "text/plain");
  4290. ASSERT_TRUE(!res);
  4291. EXPECT_EQ(Error::Canceled, res.error());
  4292. }
  4293. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4294. auto res = cli_.Put(
  4295. "/put",
  4296. [](size_t /*offset*/, DataSink &sink) {
  4297. sink.os << "PUT";
  4298. sink.done();
  4299. return true;
  4300. },
  4301. "text/plain");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("PUT", res->body);
  4305. }
  4306. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4307. auto res = cli_.Post(
  4308. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4309. "text/plain");
  4310. ASSERT_TRUE(!res);
  4311. EXPECT_EQ(Error::Canceled, res.error());
  4312. }
  4313. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4314. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4315. cli_.set_compress(true);
  4316. auto res = cli_.Put(
  4317. "/put", 3,
  4318. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4319. sink.os << "PUT";
  4320. return true;
  4321. },
  4322. "text/plain");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("PUT", res->body);
  4326. }
  4327. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4328. cli_.set_compress(true);
  4329. auto res = cli_.Post(
  4330. "/post", 42,
  4331. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4332. return false;
  4333. },
  4334. "text/plain");
  4335. ASSERT_TRUE(!res);
  4336. EXPECT_EQ(Error::Canceled, res.error());
  4337. }
  4338. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4339. cli_.set_compress(true);
  4340. auto res = cli_.Put(
  4341. "/put",
  4342. [](size_t /*offset*/, DataSink &sink) {
  4343. sink.os << "PUT";
  4344. sink.done();
  4345. return true;
  4346. },
  4347. "text/plain");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("PUT", res->body);
  4351. }
  4352. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4353. cli_.set_compress(true);
  4354. auto res = cli_.Post(
  4355. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4356. "text/plain");
  4357. ASSERT_TRUE(!res);
  4358. EXPECT_EQ(Error::Canceled, res.error());
  4359. }
  4360. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4361. cli_.set_compress(true);
  4362. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4363. ASSERT_TRUE(res);
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ(LARGE_DATA, res->body);
  4366. }
  4367. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4369. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4370. Client cli(s.c_str());
  4371. cli.enable_server_certificate_verification(false);
  4372. #else
  4373. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4374. Client cli(s.c_str());
  4375. #endif
  4376. cli.set_compress(true);
  4377. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(StatusCode::OK_200, res->status);
  4380. EXPECT_EQ(LARGE_DATA, res->body);
  4381. // The compressed size should be less than a 10th of the original. May vary
  4382. // depending on the zlib library.
  4383. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4384. static_cast<uint64_t>(10 * 1024 * 1024));
  4385. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4386. }
  4387. TEST_F(ServerTest, PutContentWithDeflate) {
  4388. cli_.set_compress(false);
  4389. Headers headers;
  4390. headers.emplace("Content-Encoding", "deflate");
  4391. // PUT in deflate format:
  4392. auto res = cli_.Put("/put", headers,
  4393. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("PUT", res->body);
  4397. }
  4398. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4399. Headers headers;
  4400. headers.emplace("Accept-Encoding", "gzip, deflate");
  4401. auto res = cli_.Get("/streamed-chunked", headers);
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ(std::string("123456789"), res->body);
  4405. }
  4406. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4407. Headers headers;
  4408. headers.emplace("Accept-Encoding", "gzip, deflate");
  4409. auto res = cli_.Get("/streamed-chunked2", headers);
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ(std::string("123456789"), res->body);
  4413. }
  4414. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4415. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. }
  4419. TEST(GzipDecompressor, ChunkedDecompression) {
  4420. std::string data;
  4421. for (size_t i = 0; i < 32 * 1024; ++i) {
  4422. data.push_back(static_cast<char>('a' + i % 26));
  4423. }
  4424. std::string compressed_data;
  4425. {
  4426. httplib::detail::gzip_compressor compressor;
  4427. bool result = compressor.compress(
  4428. data.data(), data.size(),
  4429. /*last=*/true,
  4430. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4431. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4432. compressed_data_size);
  4433. return true;
  4434. });
  4435. ASSERT_TRUE(result);
  4436. }
  4437. std::string decompressed_data;
  4438. {
  4439. httplib::detail::gzip_decompressor decompressor;
  4440. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4441. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4442. size_t chunk_size = 130;
  4443. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4444. chunk_begin += chunk_size) {
  4445. size_t current_chunk_size =
  4446. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4447. bool result = decompressor.decompress(
  4448. compressed_data.data() + chunk_begin, current_chunk_size,
  4449. [&](const char *decompressed_data_chunk,
  4450. size_t decompressed_data_chunk_size) {
  4451. decompressed_data.insert(decompressed_data.size(),
  4452. decompressed_data_chunk,
  4453. decompressed_data_chunk_size);
  4454. return true;
  4455. });
  4456. ASSERT_TRUE(result);
  4457. }
  4458. }
  4459. ASSERT_EQ(data, decompressed_data);
  4460. }
  4461. TEST(GzipDecompressor, DeflateDecompression) {
  4462. std::string original_text = "Raw deflate without gzip";
  4463. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4464. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4465. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4466. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4467. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4468. std::string decompressed_data;
  4469. {
  4470. httplib::detail::gzip_decompressor decompressor;
  4471. bool result = decompressor.decompress(
  4472. compressed_data.data(), compressed_data.size(),
  4473. [&](const char *decompressed_data_chunk,
  4474. size_t decompressed_data_chunk_size) {
  4475. decompressed_data.insert(decompressed_data.size(),
  4476. decompressed_data_chunk,
  4477. decompressed_data_chunk_size);
  4478. return true;
  4479. });
  4480. ASSERT_TRUE(result);
  4481. }
  4482. ASSERT_EQ(original_text, decompressed_data);
  4483. }
  4484. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4485. std::string original_text = "Raw deflate without gzip";
  4486. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4487. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4488. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4489. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4490. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4491. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4492. std::string decompressed_data;
  4493. {
  4494. httplib::detail::gzip_decompressor decompressor;
  4495. bool result = decompressor.decompress(
  4496. compressed_data.data(), compressed_data.size(),
  4497. [&](const char *decompressed_data_chunk,
  4498. size_t decompressed_data_chunk_size) {
  4499. decompressed_data.insert(decompressed_data.size(),
  4500. decompressed_data_chunk,
  4501. decompressed_data_chunk_size);
  4502. return true;
  4503. });
  4504. ASSERT_TRUE(result);
  4505. }
  4506. ASSERT_EQ(original_text, decompressed_data);
  4507. }
  4508. #ifdef _WIN32
  4509. TEST(GzipDecompressor, LargeRandomData) {
  4510. // prepare large random data that is difficult to be compressed and is
  4511. // expected to have large size even when compressed
  4512. std::random_device seed_gen;
  4513. std::mt19937 random(seed_gen());
  4514. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4515. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4516. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4517. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4518. // compress data over 4GiB
  4519. std::string compressed_data;
  4520. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4521. httplib::detail::gzip_compressor compressor;
  4522. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4523. data.size() * sizeof(std::uint32_t), true,
  4524. [&](const char *data, size_t size) {
  4525. compressed_data.insert(
  4526. compressed_data.size(), data, size);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(result);
  4530. // FIXME: compressed data size is expected to be greater than 4GiB,
  4531. // but there is no guarantee
  4532. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4533. // decompress data over 4GiB
  4534. std::string decompressed_data;
  4535. decompressed_data.reserve(data_size);
  4536. httplib::detail::gzip_decompressor decompressor;
  4537. result = decompressor.decompress(
  4538. compressed_data.data(), compressed_data.size(),
  4539. [&](const char *data, size_t size) {
  4540. decompressed_data.insert(decompressed_data.size(), data, size);
  4541. return true;
  4542. });
  4543. ASSERT_TRUE(result);
  4544. // compare
  4545. ASSERT_EQ(data_size, decompressed_data.size());
  4546. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4547. 0);
  4548. }
  4549. #endif
  4550. #endif
  4551. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4552. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4553. Headers headers;
  4554. headers.emplace("Accept-Encoding", "br");
  4555. auto res = cli_.Get("/streamed-chunked", headers);
  4556. ASSERT_TRUE(res);
  4557. EXPECT_EQ(StatusCode::OK_200, res->status);
  4558. EXPECT_EQ(std::string("123456789"), res->body);
  4559. }
  4560. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4561. Headers headers;
  4562. headers.emplace("Accept-Encoding", "br");
  4563. auto res = cli_.Get("/streamed-chunked2", headers);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ(std::string("123456789"), res->body);
  4567. }
  4568. #endif
  4569. TEST_F(ServerTest, Patch) {
  4570. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4571. ASSERT_TRUE(res);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. EXPECT_EQ("PATCH", res->body);
  4574. }
  4575. TEST_F(ServerTest, Delete) {
  4576. auto res = cli_.Delete("/delete");
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. EXPECT_EQ("DELETE", res->body);
  4580. }
  4581. TEST_F(ServerTest, DeleteContentReceiver) {
  4582. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("content", res->body);
  4586. }
  4587. TEST_F(ServerTest, Options) {
  4588. auto res = cli_.Options("*");
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4592. EXPECT_TRUE(res->body.empty());
  4593. }
  4594. TEST_F(ServerTest, URL) {
  4595. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. }
  4599. TEST_F(ServerTest, ArrayParam) {
  4600. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. }
  4604. TEST_F(ServerTest, NoMultipleHeaders) {
  4605. Headers headers = {{"Content-Length", "5"}};
  4606. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4607. "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. TEST_F(ServerTest, PostContentReceiver) {
  4612. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4613. ASSERT_TRUE(res);
  4614. ASSERT_EQ(StatusCode::OK_200, res->status);
  4615. ASSERT_EQ("content", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4618. UploadFormDataItems items = {
  4619. {"text1", "text default", "", ""},
  4620. {"text2", "aωb", "", ""},
  4621. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4622. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4623. {"file3", "", "", "application/octet-stream"},
  4624. };
  4625. auto res = cli_.Post("/content_receiver", items);
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::OK_200, res->status);
  4628. }
  4629. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4630. UploadFormDataItems items = {
  4631. {"text1", "text default", "", ""},
  4632. {"text2", "aωb", "", ""},
  4633. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4634. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4635. {"file3", "", "", "application/octet-stream"},
  4636. };
  4637. auto boundary = std::string("+++++");
  4638. std::string body;
  4639. for (const auto &item : items) {
  4640. body += "--" + boundary + "\r\n";
  4641. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4642. if (!item.filename.empty()) {
  4643. body += "; filename=\"" + item.filename + "\"";
  4644. }
  4645. body += "\r\n";
  4646. if (!item.content_type.empty()) {
  4647. body += "Content-Type: " + item.content_type + "\r\n";
  4648. }
  4649. body += "\r\n";
  4650. body += item.content + "\r\n";
  4651. }
  4652. body += "--" + boundary + "--\r\n";
  4653. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4654. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. }
  4658. TEST_F(ServerTest, PostContentReceiverGzip) {
  4659. cli_.set_compress(true);
  4660. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4661. ASSERT_TRUE(res);
  4662. ASSERT_EQ(StatusCode::OK_200, res->status);
  4663. ASSERT_EQ("content", res->body);
  4664. }
  4665. TEST_F(ServerTest, PutContentReceiver) {
  4666. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4667. ASSERT_TRUE(res);
  4668. ASSERT_EQ(StatusCode::OK_200, res->status);
  4669. ASSERT_EQ("content", res->body);
  4670. }
  4671. TEST_F(ServerTest, PatchContentReceiver) {
  4672. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4673. ASSERT_TRUE(res);
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("content", res->body);
  4676. }
  4677. template <typename ClientType>
  4678. void TestWithHeadersAndContentReceiver(
  4679. ClientType &cli,
  4680. std::function<Result(ClientType &, const std::string &, const Headers &,
  4681. const std::string &, const std::string &,
  4682. ContentReceiver, DownloadProgress)>
  4683. request_func) {
  4684. Headers headers;
  4685. headers.emplace("X-Custom-Header", "test-value");
  4686. std::string received_body;
  4687. auto res = request_func(
  4688. cli, "/content_receiver", headers, "content", "application/json",
  4689. [&](const char *data, size_t data_length) {
  4690. received_body.append(data, data_length);
  4691. return true;
  4692. },
  4693. nullptr);
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ("content", received_body);
  4697. }
  4698. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4700. using ClientT = SSLClient;
  4701. #else
  4702. using ClientT = Client;
  4703. #endif
  4704. TestWithHeadersAndContentReceiver<ClientT>(
  4705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4706. const std::string &body, const std::string &content_type,
  4707. ContentReceiver receiver, DownloadProgress progress) {
  4708. return cli.Post(path, headers, body, content_type, receiver, progress);
  4709. });
  4710. }
  4711. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4713. using ClientT = SSLClient;
  4714. #else
  4715. using ClientT = Client;
  4716. #endif
  4717. TestWithHeadersAndContentReceiver<ClientT>(
  4718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4719. const std::string &body, const std::string &content_type,
  4720. ContentReceiver receiver, DownloadProgress progress) {
  4721. return cli.Put(path, headers, body, content_type, receiver, progress);
  4722. });
  4723. }
  4724. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4726. using ClientT = SSLClient;
  4727. #else
  4728. using ClientT = Client;
  4729. #endif
  4730. TestWithHeadersAndContentReceiver<ClientT>(
  4731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4732. const std::string &body, const std::string &content_type,
  4733. ContentReceiver receiver, DownloadProgress progress) {
  4734. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4735. });
  4736. }
  4737. template <typename ClientType>
  4738. void TestWithHeadersAndContentReceiverWithProgress(
  4739. ClientType &cli,
  4740. std::function<Result(ClientType &, const std::string &, const Headers &,
  4741. const std::string &, const std::string &,
  4742. ContentReceiver, DownloadProgress)>
  4743. request_func) {
  4744. Headers headers;
  4745. headers.emplace("X-Test-Header", "progress-test");
  4746. std::string received_body;
  4747. auto progress_called = false;
  4748. auto res = request_func(
  4749. cli, "/content_receiver", headers, "content", "text/plain",
  4750. [&](const char *data, size_t data_length) {
  4751. received_body.append(data, data_length);
  4752. return true;
  4753. },
  4754. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4755. progress_called = true;
  4756. return true;
  4757. });
  4758. ASSERT_TRUE(res);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. EXPECT_EQ("content", received_body);
  4761. EXPECT_TRUE(progress_called);
  4762. }
  4763. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4765. using ClientT = SSLClient;
  4766. #else
  4767. using ClientT = Client;
  4768. #endif
  4769. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4770. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4771. const std::string &body, const std::string &content_type,
  4772. ContentReceiver receiver, DownloadProgress progress) {
  4773. return cli.Post(path, headers, body, content_type, receiver, progress);
  4774. });
  4775. }
  4776. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4777. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4778. using ClientT = SSLClient;
  4779. #else
  4780. using ClientT = Client;
  4781. #endif
  4782. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4783. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4784. const std::string &body, const std::string &content_type,
  4785. ContentReceiver receiver, DownloadProgress progress) {
  4786. return cli.Put(path, headers, body, content_type, receiver, progress);
  4787. });
  4788. }
  4789. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4791. using ClientT = SSLClient;
  4792. #else
  4793. using ClientT = Client;
  4794. #endif
  4795. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4796. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4797. const std::string &body, const std::string &content_type,
  4798. ContentReceiver receiver, DownloadProgress progress) {
  4799. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4800. });
  4801. }
  4802. template <typename ClientType>
  4803. void TestWithHeadersAndContentReceiverError(
  4804. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4805. const Headers &, const std::string &,
  4806. const std::string &, ContentReceiver)>
  4807. request_func) {
  4808. Headers headers;
  4809. headers.emplace("X-Error-Test", "true");
  4810. std::string received_body;
  4811. auto receiver_failed = false;
  4812. auto res =
  4813. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4814. [&](const char *data, size_t data_length) {
  4815. received_body.append(data, data_length);
  4816. receiver_failed = true;
  4817. return false;
  4818. });
  4819. ASSERT_FALSE(res);
  4820. EXPECT_TRUE(receiver_failed);
  4821. }
  4822. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4823. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4824. using ClientT = SSLClient;
  4825. #else
  4826. using ClientT = Client;
  4827. #endif
  4828. TestWithHeadersAndContentReceiverError<ClientT>(
  4829. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4830. const std::string &body, const std::string &content_type,
  4831. ContentReceiver receiver) {
  4832. return cli.Post(path, headers, body, content_type, receiver);
  4833. });
  4834. }
  4835. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4837. using ClientT = SSLClient;
  4838. #else
  4839. using ClientT = Client;
  4840. #endif
  4841. TestWithHeadersAndContentReceiverError<ClientT>(
  4842. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4843. const std::string &body, const std::string &content_type,
  4844. ContentReceiver receiver) {
  4845. return cli.Put(path, headers, body, content_type, receiver);
  4846. });
  4847. }
  4848. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4849. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4850. using ClientT = SSLClient;
  4851. #else
  4852. using ClientT = Client;
  4853. #endif
  4854. TestWithHeadersAndContentReceiverError<ClientT>(
  4855. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4856. const std::string &body, const std::string &content_type,
  4857. ContentReceiver receiver) {
  4858. return cli.Patch(path, headers, body, content_type, receiver);
  4859. });
  4860. }
  4861. TEST_F(ServerTest, PostQueryStringAndBody) {
  4862. auto res =
  4863. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4864. ASSERT_TRUE(res);
  4865. ASSERT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, HTTP2Magic) {
  4868. Request req;
  4869. req.method = "PRI";
  4870. req.path = "*";
  4871. req.body = "SM";
  4872. auto res = std::make_shared<Response>();
  4873. auto error = Error::Success;
  4874. auto ret = cli_.send(req, *res, error);
  4875. ASSERT_TRUE(ret);
  4876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4877. }
  4878. TEST_F(ServerTest, KeepAlive) {
  4879. auto res = cli_.Get("/hi");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4883. EXPECT_EQ("Hello World!", res->body);
  4884. res = cli_.Get("/hi");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("Hello World!", res->body);
  4889. res = cli_.Get("/hi");
  4890. ASSERT_TRUE(res);
  4891. EXPECT_EQ(StatusCode::OK_200, res->status);
  4892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. EXPECT_EQ("Hello World!", res->body);
  4894. res = cli_.Get("/not-exist");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4897. res = cli_.Post("/empty", "", "text/plain");
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4901. EXPECT_EQ("empty", res->body);
  4902. EXPECT_EQ("close", res->get_header_value("Connection"));
  4903. res = cli_.Post(
  4904. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4905. "text/plain");
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("empty", res->body);
  4910. cli_.set_keep_alive(false);
  4911. res = cli_.Get("/last-request");
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. EXPECT_EQ("close", res->get_header_value("Connection"));
  4915. }
  4916. TEST_F(ServerTest, TooManyRedirect) {
  4917. cli_.set_follow_location(true);
  4918. auto res = cli_.Get("/redirect/0");
  4919. ASSERT_TRUE(!res);
  4920. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4921. }
  4922. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4924. TEST_F(ServerTest, Gzip) {
  4925. Headers headers;
  4926. headers.emplace("Accept-Encoding", "gzip, deflate");
  4927. auto res = cli_.Get("/compress", headers);
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4933. "7890123456789012345678901234567890",
  4934. res->body);
  4935. EXPECT_EQ(StatusCode::OK_200, res->status);
  4936. }
  4937. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "");
  4940. auto res = cli_.Get("/compress", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4946. "7890123456789012345678901234567890",
  4947. res->body);
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. }
  4950. TEST_F(ServerTest, GzipWithContentReceiver) {
  4951. Headers headers;
  4952. headers.emplace("Accept-Encoding", "gzip, deflate");
  4953. std::string body;
  4954. auto res = cli_.Get("/compress", headers,
  4955. [&](const char *data, uint64_t data_length) {
  4956. EXPECT_EQ(100U, data_length);
  4957. body.append(data, data_length);
  4958. return true;
  4959. });
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4963. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4964. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4965. "7890123456789012345678901234567890",
  4966. body);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. }
  4969. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4970. Headers headers;
  4971. headers.emplace("Accept-Encoding", "gzip, deflate");
  4972. cli_.set_decompress(false);
  4973. auto res = cli_.Get("/compress", headers);
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4977. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4978. EXPECT_EQ(33U, res->body.size());
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. }
  4981. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4982. Headers headers;
  4983. headers.emplace("Accept-Encoding", "");
  4984. std::string body;
  4985. auto res = cli_.Get("/compress", headers,
  4986. [&](const char *data, uint64_t data_length) {
  4987. EXPECT_EQ(100U, data_length);
  4988. body.append(data, data_length);
  4989. return true;
  4990. });
  4991. ASSERT_TRUE(res);
  4992. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4996. "7890123456789012345678901234567890",
  4997. body);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. }
  5000. TEST_F(ServerTest, NoGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/nocompress", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5006. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5007. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5009. "7890123456789012345678901234567890",
  5010. res->body);
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. }
  5013. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5014. Headers headers;
  5015. headers.emplace("Accept-Encoding", "gzip, deflate");
  5016. std::string body;
  5017. auto res = cli_.Get("/nocompress", headers,
  5018. [&](const char *data, uint64_t data_length) {
  5019. EXPECT_EQ(100U, data_length);
  5020. body.append(data, data_length);
  5021. return true;
  5022. });
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5028. "7890123456789012345678901234567890",
  5029. body);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. }
  5032. TEST_F(ServerTest, MultipartFormDataGzip) {
  5033. UploadFormDataItems items = {
  5034. {"key1", "test", "", ""},
  5035. {"key2", "--abcdefg123", "", ""},
  5036. };
  5037. cli_.set_compress(true);
  5038. auto res = cli_.Post("/compress-multipart", items);
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. }
  5042. #endif
  5043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5044. TEST_F(ServerTest, Brotli) {
  5045. Headers headers;
  5046. headers.emplace("Accept-Encoding", "br");
  5047. auto res = cli_.Get("/compress", headers);
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5053. "7890123456789012345678901234567890",
  5054. res->body);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. }
  5057. #endif
  5058. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5059. TEST_F(ServerTest, Zstd) {
  5060. Headers headers;
  5061. headers.emplace("Accept-Encoding", "zstd");
  5062. auto res = cli_.Get("/compress", headers);
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5068. "7890123456789012345678901234567890",
  5069. res->body);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5073. Headers headers;
  5074. headers.emplace("Accept-Encoding", "");
  5075. auto res = cli_.Get("/compress", headers);
  5076. ASSERT_TRUE(res);
  5077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5081. "7890123456789012345678901234567890",
  5082. res->body);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "zstd");
  5088. std::string body;
  5089. auto res = cli_.Get("/compress", headers,
  5090. [&](const char *data, uint64_t data_length) {
  5091. EXPECT_EQ(100U, data_length);
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. ASSERT_TRUE(res);
  5096. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5098. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5100. "7890123456789012345678901234567890",
  5101. body);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5105. Headers headers;
  5106. headers.emplace("Accept-Encoding", "zstd");
  5107. cli_.set_decompress(false);
  5108. auto res = cli_.Get("/compress", headers);
  5109. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5110. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5111. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5112. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5116. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ(26U, res->body.size());
  5119. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5120. 0);
  5121. }
  5122. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5123. Headers headers;
  5124. headers.emplace("Accept-Encoding", "");
  5125. std::string body;
  5126. auto res = cli_.Get("/compress", headers,
  5127. [&](const char *data, uint64_t data_length) {
  5128. EXPECT_EQ(100U, data_length);
  5129. body.append(data, data_length);
  5130. return true;
  5131. });
  5132. ASSERT_TRUE(res);
  5133. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5135. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5136. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5137. "7890123456789012345678901234567890",
  5138. body);
  5139. EXPECT_EQ(StatusCode::OK_200, res->status);
  5140. }
  5141. TEST_F(ServerTest, NoZstd) {
  5142. Headers headers;
  5143. headers.emplace("Accept-Encoding", "zstd");
  5144. auto res = cli_.Get("/nocompress", headers);
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5147. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5149. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5150. "7890123456789012345678901234567890",
  5151. res->body);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. }
  5154. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5155. Headers headers;
  5156. headers.emplace("Accept-Encoding", "zstd");
  5157. std::string body;
  5158. auto res = cli_.Get("/nocompress", headers,
  5159. [&](const char *data, uint64_t data_length) {
  5160. EXPECT_EQ(100U, data_length);
  5161. body.append(data, data_length);
  5162. return true;
  5163. });
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. // TODO: How to enable zstd ??
  5174. TEST_F(ServerTest, MultipartFormDataZstd) {
  5175. UploadFormDataItems items = {
  5176. {"key1", "test", "", ""},
  5177. {"key2", "--abcdefg123", "", ""},
  5178. };
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "zstd");
  5181. cli_.set_compress(true);
  5182. auto res = cli_.Post("/compress-multipart", headers, items);
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. }
  5186. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5187. Headers headers;
  5188. headers.emplace("Accept-Encoding", "zstd");
  5189. cli_.set_compress(true);
  5190. auto res = cli_.Put(
  5191. "/put", headers, 3,
  5192. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5193. sink.os << "PUT";
  5194. return true;
  5195. },
  5196. "text/plain");
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. EXPECT_EQ("PUT", res->body);
  5200. }
  5201. // Pre-compression logging tests
  5202. TEST_F(ServerTest, PreCompressionLogging) {
  5203. // Test data for compression (matches the actual /compress endpoint content)
  5204. const std::string test_content =
  5205. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5206. "3456789012345678901234567890";
  5207. // Variables to capture logging data
  5208. std::string pre_compression_body;
  5209. std::string pre_compression_content_type;
  5210. std::string pre_compression_content_encoding;
  5211. std::string post_compression_body;
  5212. std::string post_compression_content_type;
  5213. std::string post_compression_content_encoding;
  5214. // Set up pre-compression logger
  5215. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5216. const Response &res) {
  5217. pre_compression_body = res.body;
  5218. pre_compression_content_type = res.get_header_value("Content-Type");
  5219. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5220. });
  5221. // Set up post-compression logger
  5222. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5223. post_compression_body = res.body;
  5224. post_compression_content_type = res.get_header_value("Content-Type");
  5225. post_compression_content_encoding =
  5226. res.get_header_value("Content-Encoding");
  5227. });
  5228. // Test with gzip compression
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "gzip");
  5231. auto res = cli_.Get("/compress", headers);
  5232. // Verify response was compressed
  5233. ASSERT_TRUE(res);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5236. // Verify pre-compression logger captured uncompressed content
  5237. EXPECT_EQ(test_content, pre_compression_body);
  5238. EXPECT_EQ("text/plain", pre_compression_content_type);
  5239. EXPECT_TRUE(pre_compression_content_encoding
  5240. .empty()); // No encoding header before compression
  5241. // Verify post-compression logger captured compressed content
  5242. EXPECT_NE(test_content,
  5243. post_compression_body); // Should be different after compression
  5244. EXPECT_EQ("text/plain", post_compression_content_type);
  5245. EXPECT_EQ("gzip", post_compression_content_encoding);
  5246. // Verify compressed content is smaller
  5247. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5248. }
  5249. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5250. const std::string test_content =
  5251. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5252. "3456789012345678901234567890";
  5253. std::string pre_compression_body;
  5254. std::string post_compression_body;
  5255. svr_.set_pre_compression_logger(
  5256. [&](const Request & /*req*/, const Response &res) {
  5257. pre_compression_body = res.body;
  5258. });
  5259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5260. post_compression_body = res.body;
  5261. });
  5262. Headers headers;
  5263. headers.emplace("Accept-Encoding", "br");
  5264. auto res = cli_.Get("/compress", headers);
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5268. // Verify pre-compression content is uncompressed
  5269. EXPECT_EQ(test_content, pre_compression_body);
  5270. // Verify post-compression content is compressed
  5271. EXPECT_NE(test_content, post_compression_body);
  5272. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5273. }
  5274. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5275. const std::string test_content =
  5276. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5277. "3456789012345678901234567890";
  5278. std::string pre_compression_body;
  5279. std::string post_compression_body;
  5280. svr_.set_pre_compression_logger(
  5281. [&](const Request & /*req*/, const Response &res) {
  5282. pre_compression_body = res.body;
  5283. });
  5284. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5285. post_compression_body = res.body;
  5286. });
  5287. // Request without compression (use /nocompress endpoint)
  5288. Headers headers;
  5289. auto res = cli_.Get("/nocompress", headers);
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5293. // Pre-compression logger should not be called when no compression is applied
  5294. EXPECT_TRUE(
  5295. pre_compression_body.empty()); // Pre-compression logger not called
  5296. EXPECT_EQ(
  5297. test_content,
  5298. post_compression_body); // Post-compression logger captures final content
  5299. }
  5300. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5301. const std::string test_content =
  5302. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5303. "3456789012345678901234567890";
  5304. std::string pre_compression_body;
  5305. bool pre_logger_called = false;
  5306. // Set only pre-compression logger
  5307. svr_.set_pre_compression_logger(
  5308. [&](const Request & /*req*/, const Response &res) {
  5309. pre_compression_body = res.body;
  5310. pre_logger_called = true;
  5311. });
  5312. Headers headers;
  5313. headers.emplace("Accept-Encoding", "gzip");
  5314. auto res = cli_.Get("/compress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5318. // Verify pre-compression logger was called
  5319. EXPECT_TRUE(pre_logger_called);
  5320. EXPECT_EQ(test_content, pre_compression_body);
  5321. }
  5322. TEST(ZstdDecompressor, ChunkedDecompression) {
  5323. std::string data;
  5324. for (size_t i = 0; i < 32 * 1024; ++i) {
  5325. data.push_back(static_cast<char>('a' + i % 26));
  5326. }
  5327. std::string compressed_data;
  5328. {
  5329. httplib::detail::zstd_compressor compressor;
  5330. bool result = compressor.compress(
  5331. data.data(), data.size(),
  5332. /*last=*/true,
  5333. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5334. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5335. compressed_data_size);
  5336. return true;
  5337. });
  5338. ASSERT_TRUE(result);
  5339. }
  5340. std::string decompressed_data;
  5341. {
  5342. httplib::detail::zstd_decompressor decompressor;
  5343. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5344. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5345. size_t chunk_size = 130;
  5346. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5347. chunk_begin += chunk_size) {
  5348. size_t current_chunk_size =
  5349. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5350. bool result = decompressor.decompress(
  5351. compressed_data.data() + chunk_begin, current_chunk_size,
  5352. [&](const char *decompressed_data_chunk,
  5353. size_t decompressed_data_chunk_size) {
  5354. decompressed_data.insert(decompressed_data.size(),
  5355. decompressed_data_chunk,
  5356. decompressed_data_chunk_size);
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(result);
  5360. }
  5361. }
  5362. ASSERT_EQ(data, decompressed_data);
  5363. }
  5364. TEST(ZstdDecompressor, Decompress) {
  5365. std::string original_text = "Compressed with ZSTD";
  5366. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5367. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5368. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5369. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5370. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5371. std::string decompressed_data;
  5372. {
  5373. httplib::detail::zstd_decompressor decompressor;
  5374. bool result = decompressor.decompress(
  5375. compressed_data.data(), compressed_data.size(),
  5376. [&](const char *decompressed_data_chunk,
  5377. size_t decompressed_data_chunk_size) {
  5378. decompressed_data.insert(decompressed_data.size(),
  5379. decompressed_data_chunk,
  5380. decompressed_data_chunk_size);
  5381. return true;
  5382. });
  5383. ASSERT_TRUE(result);
  5384. }
  5385. ASSERT_EQ(original_text, decompressed_data);
  5386. }
  5387. #endif
  5388. // Sends a raw request to a server listening at HOST:PORT.
  5389. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5390. std::string *resp = nullptr) {
  5391. auto error = Error::Success;
  5392. auto client_sock = detail::create_client_socket(
  5393. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5394. /*connection_timeout_sec=*/5, 0,
  5395. /*read_timeout_sec=*/5, 0,
  5396. /*write_timeout_sec=*/5, 0, std::string(), error);
  5397. if (client_sock == INVALID_SOCKET) { return false; }
  5398. auto ret = detail::process_client_socket(
  5399. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5400. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5401. if (req.size() !=
  5402. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5403. return false;
  5404. }
  5405. char buf[512];
  5406. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5407. while (line_reader.getline()) {
  5408. if (resp) { *resp += line_reader.ptr(); }
  5409. }
  5410. return true;
  5411. });
  5412. detail::close_socket(client_sock);
  5413. return ret;
  5414. }
  5415. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5416. Server svr;
  5417. std::string header_value;
  5418. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5419. header_value = req.get_header_value("foo");
  5420. res.set_content("ok", "text/plain");
  5421. });
  5422. thread t = thread([&] { svr.listen(HOST, PORT); });
  5423. auto se = detail::scope_exit([&] {
  5424. svr.stop();
  5425. t.join();
  5426. ASSERT_FALSE(svr.is_running());
  5427. });
  5428. svr.wait_until_ready();
  5429. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5430. // like characters are not treated the same - use vertical tab and escape.
  5431. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5432. "foo: \t \v bar \x1B\t \r\n"
  5433. "Connection: close\r\n"
  5434. "\r\n";
  5435. std::string res;
  5436. ASSERT_TRUE(send_request(5, req, &res));
  5437. EXPECT_EQ(header_value, "");
  5438. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5439. }
  5440. // Sends a raw request and verifies that there isn't a crash or exception.
  5441. static void test_raw_request(const std::string &req,
  5442. std::string *out = nullptr) {
  5443. Server svr;
  5444. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5445. res.set_content("ok", "text/plain");
  5446. });
  5447. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5448. res.set_content("ok", "text/plain");
  5449. });
  5450. svr.Get("/header_field_value_check",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.set_content("ok", "text/plain");
  5453. });
  5454. // Server read timeout must be longer than the client read timeout for the
  5455. // bug to reproduce, probably to force the server to process a request
  5456. // without a trailing blank line.
  5457. const time_t client_read_timeout_sec = 1;
  5458. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5459. bool listen_thread_ok = false;
  5460. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5461. auto se = detail::scope_exit([&] {
  5462. svr.stop();
  5463. t.join();
  5464. ASSERT_FALSE(svr.is_running());
  5465. EXPECT_TRUE(listen_thread_ok);
  5466. });
  5467. svr.wait_until_ready();
  5468. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5469. }
  5470. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5471. // A certain header line causes an exception if the header property is parsed
  5472. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5473. test_raw_request(
  5474. "GET /hi HTTP/1.1\r\n"
  5475. " : "
  5476. " "
  5477. " ");
  5478. }
  5479. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5480. // A certain header line causes an exception if the header property *name* is
  5481. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5482. // greedy matcher and requires backtracking when there are a lot of ":"
  5483. // characters.
  5484. // This occurs with libc++ but not libstdc++.
  5485. test_raw_request(
  5486. "GET /hi HTTP/1.1\r\n"
  5487. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5488. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5489. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5490. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5491. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5492. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5493. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5494. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5495. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5496. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5497. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5498. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5499. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5500. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5501. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5502. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5503. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5504. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5505. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5506. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5507. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5508. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5509. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5510. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5511. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5512. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5513. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5514. "&&&%%%");
  5515. }
  5516. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5517. // Make sure this doesn't crash the server.
  5518. // In a previous version of the header line regex, the "\r" rendered the line
  5519. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5520. // a new position where the leading white space ended and the field value
  5521. // began.
  5522. // The crash occurs with libc++ but not libstdc++.
  5523. test_raw_request("GET /hi HTTP/1.1\r\n"
  5524. "a:" +
  5525. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5526. "\r\n"
  5527. "\r\n");
  5528. }
  5529. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5530. std::string out;
  5531. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5532. "Content-Type: text/plain\r\n"
  5533. "Transfer-Encoding: chunked\r\n"
  5534. "\r\n"
  5535. "nothex\r\n",
  5536. &out);
  5537. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5538. }
  5539. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5540. std::string out;
  5541. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5542. "Content-Type: text/plain\r\n"
  5543. "Transfer-Encoding: chunked\r\n"
  5544. "\r\n"
  5545. "3\r\n"
  5546. "xyz\r\n"
  5547. "NaN\r\n",
  5548. &out);
  5549. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5550. }
  5551. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5552. std::string out;
  5553. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5554. "Content-Type: text/plain\r\n"
  5555. "Transfer-Encoding: chunked\r\n"
  5556. "\r\n"
  5557. // Length is too large for 64 bits.
  5558. "1ffffffffffffffff\r\n"
  5559. "xyz\r\n",
  5560. &out);
  5561. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5562. }
  5563. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5564. test_raw_request("GET /hi HTTP/1.1\r\n"
  5565. "Content-Type: text/plain\r\n\r");
  5566. }
  5567. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5568. std::string out;
  5569. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5570. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5571. }
  5572. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5573. std::string out;
  5574. std::string request(
  5575. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5576. test_raw_request(request, &out);
  5577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5578. }
  5579. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5580. std::string out;
  5581. std::string request(
  5582. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5583. test_raw_request(request, &out);
  5584. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5585. }
  5586. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5587. std::string out;
  5588. std::string request(
  5589. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5590. test_raw_request(request, &out);
  5591. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5592. }
  5593. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5594. std::string out;
  5595. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5596. "Test: \r\n\r\n",
  5597. &out);
  5598. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5599. }
  5600. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5601. Server svr;
  5602. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5603. res.set_header("Cache-Control", "no-cache");
  5604. res.set_chunked_content_provider(
  5605. "text/event-stream", [](size_t offset, DataSink &sink) {
  5606. std::string s = "data:";
  5607. s += std::to_string(offset);
  5608. s += "\n\n";
  5609. auto ret = sink.write(s.data(), s.size());
  5610. EXPECT_TRUE(ret);
  5611. std::this_thread::sleep_for(std::chrono::seconds(1));
  5612. return true;
  5613. });
  5614. });
  5615. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5616. svr.wait_until_ready();
  5617. Client client(HOST, PORT);
  5618. const Headers headers = {{"Accept", "text/event-stream"}};
  5619. auto get_thread = std::thread([&client, &headers]() {
  5620. auto res = client.Get(
  5621. "/events", headers,
  5622. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5623. });
  5624. auto se = detail::scope_exit([&] {
  5625. svr.stop();
  5626. get_thread.join();
  5627. listen_thread.join();
  5628. ASSERT_FALSE(svr.is_running());
  5629. });
  5630. // Give GET time to get a few messages.
  5631. std::this_thread::sleep_for(std::chrono::seconds(2));
  5632. }
  5633. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5634. httplib::Server svr;
  5635. svr.Post("/hi",
  5636. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5637. res.status = StatusCode::OK_200;
  5638. });
  5639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5640. svr.wait_until_ready();
  5641. Client cli(HOST, PORT);
  5642. auto res = cli.Post("/hi", "data", "text/plain");
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ(StatusCode::OK_200, res->status);
  5645. svr.stop();
  5646. thread.join();
  5647. ASSERT_FALSE(svr.is_running());
  5648. res = cli.Post("/hi", "data", "text/plain");
  5649. ASSERT_FALSE(res);
  5650. }
  5651. TEST(ServerStopTest, ListenFailure) {
  5652. Server svr;
  5653. auto t = thread([&]() {
  5654. auto ret = svr.listen("????", PORT);
  5655. EXPECT_FALSE(ret);
  5656. });
  5657. svr.wait_until_ready();
  5658. svr.stop();
  5659. t.join();
  5660. }
  5661. TEST(ServerStopTest, Decommision) {
  5662. Server svr;
  5663. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5664. for (int i = 0; i < 4; i++) {
  5665. auto is_even = !(i % 2);
  5666. std::thread t{[&] {
  5667. try {
  5668. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5669. if (is_even) {
  5670. throw std::runtime_error("Some thing that happens to go wrong.");
  5671. }
  5672. svr.listen(HOST, PORT);
  5673. } catch (...) { svr.decommission(); }
  5674. }};
  5675. svr.wait_until_ready();
  5676. // Server is up
  5677. {
  5678. Client cli(HOST, PORT);
  5679. auto res = cli.Get("/hi");
  5680. if (is_even) {
  5681. EXPECT_FALSE(res);
  5682. } else {
  5683. EXPECT_TRUE(res);
  5684. EXPECT_EQ("hi...", res->body);
  5685. }
  5686. }
  5687. svr.stop();
  5688. t.join();
  5689. // Server is down...
  5690. {
  5691. Client cli(HOST, PORT);
  5692. auto res = cli.Get("/hi");
  5693. EXPECT_FALSE(res);
  5694. }
  5695. }
  5696. }
  5697. // Helper function for string body upload progress tests
  5698. template <typename SetupHandler, typename ClientCall>
  5699. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5700. ClientCall &&client_call,
  5701. const string &body) {
  5702. Server svr;
  5703. setup_handler(svr);
  5704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5705. auto se = detail::scope_exit([&] {
  5706. svr.stop();
  5707. t.join();
  5708. });
  5709. svr.wait_until_ready();
  5710. Client cli(HOST, PORT);
  5711. vector<uint64_t> progress_values;
  5712. bool progress_called = false;
  5713. auto res =
  5714. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5715. progress_values.push_back(current);
  5716. progress_called = true;
  5717. return true;
  5718. });
  5719. ASSERT_TRUE(res);
  5720. EXPECT_EQ(200, res->status);
  5721. EXPECT_TRUE(progress_called);
  5722. }
  5723. TEST(UploadProgressTest, PostStringBodyBasic) {
  5724. TestStringBodyUploadProgress(
  5725. [](Server &svr) {
  5726. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5727. res.set_content("received", "text/plain");
  5728. });
  5729. },
  5730. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5731. return cli.Post("/test", body, "text/plain", progress_callback);
  5732. },
  5733. "test data for upload progress");
  5734. }
  5735. TEST(UploadProgressTest, PutStringBodyBasic) {
  5736. TestStringBodyUploadProgress(
  5737. [](Server &svr) {
  5738. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5739. res.set_content("put received", "text/plain");
  5740. });
  5741. },
  5742. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5743. return cli.Put("/test", body, "text/plain", progress_callback);
  5744. },
  5745. "put test data for upload progress");
  5746. }
  5747. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5748. TestStringBodyUploadProgress(
  5749. [](Server &svr) {
  5750. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5751. res.set_content("patch received", "text/plain");
  5752. });
  5753. },
  5754. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5755. return cli.Patch("/test", body, "text/plain", progress_callback);
  5756. },
  5757. "patch test data for upload progress");
  5758. }
  5759. // Helper function for content provider upload progress tests
  5760. template <typename SetupHandler, typename ClientCall>
  5761. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5762. ClientCall &&client_call) {
  5763. Server svr;
  5764. setup_handler(svr);
  5765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5766. auto se = detail::scope_exit([&] {
  5767. svr.stop();
  5768. t.join();
  5769. });
  5770. svr.wait_until_ready();
  5771. Client cli(HOST, PORT);
  5772. vector<uint64_t> progress_values;
  5773. auto res =
  5774. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5775. progress_values.push_back(current);
  5776. return true;
  5777. });
  5778. ASSERT_TRUE(res);
  5779. EXPECT_EQ(200, res->status);
  5780. EXPECT_FALSE(progress_values.empty());
  5781. }
  5782. TEST(UploadProgressTest, PostContentProviderProgress) {
  5783. TestContentProviderUploadProgress(
  5784. [](Server &svr) {
  5785. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5786. res.set_content("provider received", "text/plain");
  5787. });
  5788. },
  5789. [](Client &cli, UploadProgress progress_callback) {
  5790. return cli.Post(
  5791. "/test", 10,
  5792. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5793. sink.os << "test data";
  5794. return true;
  5795. },
  5796. "text/plain", progress_callback);
  5797. });
  5798. }
  5799. // Helper function for multipart upload progress tests
  5800. template <typename SetupHandler, typename ClientCall>
  5801. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5802. ClientCall &&client_call,
  5803. const string &endpoint) {
  5804. Server svr;
  5805. setup_handler(svr);
  5806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5807. auto se = detail::scope_exit([&] {
  5808. svr.stop();
  5809. t.join();
  5810. });
  5811. svr.wait_until_ready();
  5812. Client cli(HOST, PORT);
  5813. vector<uint64_t> progress_values;
  5814. UploadFormDataItems items = {
  5815. {"field1", "value1", "", ""},
  5816. {"field2", "longer value for progress tracking test", "", ""},
  5817. {"file1", "file content data for upload progress", "test.txt",
  5818. "text/plain"}};
  5819. auto res = client_call(cli, endpoint, items,
  5820. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5821. progress_values.push_back(current);
  5822. return true;
  5823. });
  5824. ASSERT_TRUE(res);
  5825. EXPECT_EQ(200, res->status);
  5826. EXPECT_FALSE(progress_values.empty());
  5827. }
  5828. TEST(UploadProgressTest, PostMultipartProgress) {
  5829. TestMultipartUploadProgress(
  5830. [](Server &svr) {
  5831. svr.Post("/multipart", [](const Request &req, Response &res) {
  5832. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5833. res.set_content("multipart received", "text/plain");
  5834. });
  5835. },
  5836. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5837. UploadProgress progress_callback) {
  5838. return cli.Post(endpoint, items, progress_callback);
  5839. },
  5840. "/multipart");
  5841. }
  5842. // Helper function for basic download progress tests
  5843. template <typename SetupHandler, typename ClientCall>
  5844. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5845. ClientCall &&client_call, const string &endpoint,
  5846. size_t expected_content_size) {
  5847. Server svr;
  5848. setup_handler(svr);
  5849. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5850. auto se = detail::scope_exit([&] {
  5851. svr.stop();
  5852. t.join();
  5853. });
  5854. svr.wait_until_ready();
  5855. Client cli(HOST, PORT);
  5856. vector<uint64_t> progress_values;
  5857. auto res = client_call(cli, endpoint,
  5858. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5859. progress_values.push_back(current);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res);
  5863. EXPECT_EQ(200, res->status);
  5864. EXPECT_FALSE(progress_values.empty());
  5865. EXPECT_EQ(expected_content_size, res->body.size());
  5866. }
  5867. TEST(DownloadProgressTest, GetBasic) {
  5868. TestBasicDownloadProgress(
  5869. [](Server &svr) {
  5870. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5871. string content(1000, 'D');
  5872. res.set_content(content, "text/plain");
  5873. });
  5874. },
  5875. [](Client &cli, const string &endpoint,
  5876. DownloadProgress progress_callback) {
  5877. return cli.Get(endpoint, progress_callback);
  5878. },
  5879. "/download", 1000u);
  5880. }
  5881. // Helper function for content receiver download progress tests
  5882. template <typename SetupHandler, typename ClientCall>
  5883. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5884. ClientCall &&client_call,
  5885. const string &endpoint,
  5886. size_t expected_content_size) {
  5887. Server svr;
  5888. setup_handler(svr);
  5889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. });
  5894. svr.wait_until_ready();
  5895. Client cli(HOST, PORT);
  5896. vector<uint64_t> progress_values;
  5897. string received_body;
  5898. auto res = client_call(
  5899. cli, endpoint,
  5900. [&](const char *data, size_t data_length) -> bool {
  5901. received_body.append(data, data_length);
  5902. return true;
  5903. },
  5904. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5905. progress_values.push_back(current);
  5906. return true;
  5907. });
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(200, res->status);
  5910. EXPECT_FALSE(progress_values.empty());
  5911. EXPECT_EQ(expected_content_size, received_body.size());
  5912. EXPECT_TRUE(res->body.empty());
  5913. }
  5914. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5915. TestContentReceiverDownloadProgress(
  5916. [](Server &svr) {
  5917. svr.Get("/download-receiver",
  5918. [](const Request & /*req*/, Response &res) {
  5919. string content(2000, 'R');
  5920. res.set_content(content, "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5924. DownloadProgress progress_callback) {
  5925. return cli.Get(endpoint, content_receiver, progress_callback);
  5926. },
  5927. "/download-receiver", 2000u);
  5928. }
  5929. TEST(StreamingTest, NoContentLengthStreaming) {
  5930. Server svr;
  5931. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5932. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5933. if (offset < 6) {
  5934. sink.os << (offset < 3 ? "a" : "b");
  5935. } else {
  5936. sink.done();
  5937. }
  5938. return true;
  5939. });
  5940. });
  5941. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5942. auto listen_se = detail::scope_exit([&] {
  5943. svr.stop();
  5944. listen_thread.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. svr.wait_until_ready();
  5948. Client client(HOST, PORT);
  5949. auto get_thread = std::thread([&client]() {
  5950. std::string s;
  5951. auto res =
  5952. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5953. s += std::string(data, len);
  5954. return true;
  5955. });
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. EXPECT_EQ("aaabbb", s);
  5959. });
  5960. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5961. // Give GET time to get a few messages.
  5962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5963. }
  5964. TEST(MountTest, Unmount) {
  5965. Server svr;
  5966. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. listen_thread.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. Client cli("localhost", PORT);
  5974. svr.set_mount_point("/mount2", "./www2");
  5975. auto res = cli.Get("/");
  5976. ASSERT_TRUE(res);
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. res = cli.Get("/mount2/dir/test.html");
  5979. ASSERT_TRUE(res);
  5980. EXPECT_EQ(StatusCode::OK_200, res->status);
  5981. svr.set_mount_point("/", "./www");
  5982. res = cli.Get("/dir/");
  5983. ASSERT_TRUE(res);
  5984. EXPECT_EQ(StatusCode::OK_200, res->status);
  5985. svr.remove_mount_point("/");
  5986. res = cli.Get("/dir/");
  5987. ASSERT_TRUE(res);
  5988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5989. svr.remove_mount_point("/mount2");
  5990. res = cli.Get("/mount2/dir/test.html");
  5991. ASSERT_TRUE(res);
  5992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5993. }
  5994. TEST(MountTest, Redicect) {
  5995. Server svr;
  5996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5997. auto se = detail::scope_exit([&] {
  5998. svr.stop();
  5999. listen_thread.join();
  6000. ASSERT_FALSE(svr.is_running());
  6001. });
  6002. svr.set_mount_point("/", "./www");
  6003. svr.wait_until_ready();
  6004. Client cli("localhost", PORT);
  6005. auto res = cli.Get("/dir/");
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. res = cli.Get("/dir");
  6009. ASSERT_TRUE(res);
  6010. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6011. res = cli.Get("/file");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. res = cli.Get("/file/");
  6015. ASSERT_TRUE(res);
  6016. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6017. cli.set_follow_location(true);
  6018. res = cli.Get("/dir");
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. }
  6022. TEST(MountTest, MultibytesPathName) {
  6023. Server svr;
  6024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6025. auto se = detail::scope_exit([&] {
  6026. svr.stop();
  6027. listen_thread.join();
  6028. ASSERT_FALSE(svr.is_running());
  6029. });
  6030. svr.set_mount_point("/", "./www");
  6031. svr.wait_until_ready();
  6032. Client cli("localhost", PORT);
  6033. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6037. }
  6038. TEST(KeepAliveTest, ReadTimeout) {
  6039. Server svr;
  6040. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6041. std::this_thread::sleep_for(std::chrono::seconds(2));
  6042. res.set_content("a", "text/plain");
  6043. });
  6044. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6045. res.set_content("b", "text/plain");
  6046. });
  6047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. listen_thread.join();
  6051. ASSERT_FALSE(svr.is_running());
  6052. });
  6053. svr.wait_until_ready();
  6054. Client cli("localhost", PORT);
  6055. cli.set_keep_alive(true);
  6056. cli.set_read_timeout(std::chrono::seconds(1));
  6057. auto resa = cli.Get("/a");
  6058. ASSERT_FALSE(resa);
  6059. EXPECT_EQ(Error::Read, resa.error());
  6060. auto resb = cli.Get("/b");
  6061. ASSERT_TRUE(resb);
  6062. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6063. EXPECT_EQ("b", resb->body);
  6064. }
  6065. TEST(KeepAliveTest, MaxCount) {
  6066. size_t keep_alive_max_count = 3;
  6067. Server svr;
  6068. svr.set_keep_alive_max_count(keep_alive_max_count);
  6069. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6070. res.set_content("Hello World!", "text/plain");
  6071. });
  6072. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. listen_thread.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli(HOST, PORT);
  6080. cli.set_keep_alive(true);
  6081. for (size_t i = 0; i < 5; i++) {
  6082. auto result = cli.Get("/hi");
  6083. ASSERT_TRUE(result);
  6084. EXPECT_EQ(StatusCode::OK_200, result->status);
  6085. if (i == keep_alive_max_count - 1) {
  6086. EXPECT_EQ("close", result->get_header_value("Connection"));
  6087. } else {
  6088. EXPECT_FALSE(result->has_header("Connection"));
  6089. }
  6090. }
  6091. }
  6092. TEST(KeepAliveTest, Issue1041) {
  6093. Server svr;
  6094. svr.set_keep_alive_timeout(3);
  6095. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6096. res.set_content("Hello World!", "text/plain");
  6097. });
  6098. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6099. auto se = detail::scope_exit([&] {
  6100. svr.stop();
  6101. listen_thread.join();
  6102. ASSERT_FALSE(svr.is_running());
  6103. });
  6104. svr.wait_until_ready();
  6105. Client cli(HOST, PORT);
  6106. cli.set_keep_alive(true);
  6107. auto result = cli.Get("/hi");
  6108. ASSERT_TRUE(result);
  6109. EXPECT_EQ(StatusCode::OK_200, result->status);
  6110. std::this_thread::sleep_for(std::chrono::seconds(5));
  6111. result = cli.Get("/hi");
  6112. ASSERT_TRUE(result);
  6113. EXPECT_EQ(StatusCode::OK_200, result->status);
  6114. }
  6115. TEST(KeepAliveTest, Issue1959) {
  6116. Server svr;
  6117. svr.set_keep_alive_timeout(5);
  6118. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6119. res.set_content("a", "text/plain");
  6120. });
  6121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6122. auto se = detail::scope_exit([&] {
  6123. if (!svr.is_running()) return;
  6124. svr.stop();
  6125. listen_thread.join();
  6126. ASSERT_FALSE(svr.is_running());
  6127. });
  6128. svr.wait_until_ready();
  6129. Client cli("localhost", PORT);
  6130. cli.set_keep_alive(true);
  6131. using namespace std::chrono;
  6132. auto start = steady_clock::now();
  6133. cli.Get("/a");
  6134. svr.stop();
  6135. listen_thread.join();
  6136. auto end = steady_clock::now();
  6137. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6138. EXPECT_LT(elapsed, 5000);
  6139. }
  6140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6141. TEST(KeepAliveTest, SSLClientReconnection) {
  6142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6143. ASSERT_TRUE(svr.is_valid());
  6144. svr.set_keep_alive_timeout(1);
  6145. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6146. res.set_content("Hello World!", "text/plain");
  6147. });
  6148. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6149. auto se = detail::scope_exit([&] {
  6150. svr.stop();
  6151. listen_thread.join();
  6152. ASSERT_FALSE(svr.is_running());
  6153. });
  6154. svr.wait_until_ready();
  6155. SSLClient cli(HOST, PORT);
  6156. cli.enable_server_certificate_verification(false);
  6157. cli.set_keep_alive(true);
  6158. auto result = cli.Get("/hi");
  6159. ASSERT_TRUE(result);
  6160. EXPECT_EQ(StatusCode::OK_200, result->status);
  6161. result = cli.Get("/hi");
  6162. ASSERT_TRUE(result);
  6163. EXPECT_EQ(StatusCode::OK_200, result->status);
  6164. std::this_thread::sleep_for(std::chrono::seconds(2));
  6165. // Recoonect
  6166. result = cli.Get("/hi");
  6167. ASSERT_TRUE(result);
  6168. EXPECT_EQ(StatusCode::OK_200, result->status);
  6169. result = cli.Get("/hi");
  6170. ASSERT_TRUE(result);
  6171. EXPECT_EQ(StatusCode::OK_200, result->status);
  6172. }
  6173. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6175. ASSERT_TRUE(svr.is_valid());
  6176. svr.set_keep_alive_timeout(1);
  6177. std::string content = "reconnect";
  6178. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6179. res.set_content("Hello World!", "text/plain");
  6180. });
  6181. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6182. auto se = detail::scope_exit([&] {
  6183. svr.stop();
  6184. listen_thread.join();
  6185. ASSERT_FALSE(svr.is_running());
  6186. });
  6187. svr.wait_until_ready();
  6188. SSLClient cli(HOST, PORT);
  6189. cli.enable_server_certificate_verification(false);
  6190. cli.set_keep_alive(true);
  6191. auto result = cli.Post(
  6192. "/hi", content.size(),
  6193. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6194. sink.write(content.c_str(), content.size());
  6195. return true;
  6196. },
  6197. "text/plain");
  6198. ASSERT_TRUE(result);
  6199. EXPECT_EQ(200, result->status);
  6200. std::this_thread::sleep_for(std::chrono::seconds(2));
  6201. // Recoonect
  6202. result = cli.Post(
  6203. "/hi", content.size(),
  6204. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6205. sink.write(content.c_str(), content.size());
  6206. return true;
  6207. },
  6208. "text/plain");
  6209. ASSERT_TRUE(result);
  6210. EXPECT_EQ(200, result->status);
  6211. result = cli.Post(
  6212. "/hi", content.size(),
  6213. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6214. sink.write(content.c_str(), content.size());
  6215. return true;
  6216. },
  6217. "text/plain");
  6218. ASSERT_TRUE(result);
  6219. EXPECT_EQ(200, result->status);
  6220. }
  6221. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6222. {
  6223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6224. ASSERT_TRUE(svr.is_valid());
  6225. svr.Get("/sni", [&](const Request &req, Response &res) {
  6226. std::string expected;
  6227. if (req.ssl) {
  6228. if (const char *sni =
  6229. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6230. expected = sni;
  6231. }
  6232. }
  6233. EXPECT_EQ(expected, req.get_param_value("expected"));
  6234. res.set_content("ok", "text/plain");
  6235. });
  6236. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6237. auto se = detail::scope_exit([&] {
  6238. svr.stop();
  6239. listen_thread.join();
  6240. ASSERT_FALSE(svr.is_running());
  6241. });
  6242. svr.wait_until_ready();
  6243. {
  6244. SSLClient cli("localhost", PORT);
  6245. cli.enable_server_certificate_verification(false);
  6246. auto res = cli.Get("/sni?expected=localhost");
  6247. ASSERT_TRUE(res);
  6248. }
  6249. {
  6250. SSLClient cli("::1", PORT);
  6251. cli.enable_server_certificate_verification(false);
  6252. auto res = cli.Get("/sni?expected=");
  6253. ASSERT_TRUE(res);
  6254. }
  6255. }
  6256. }
  6257. #endif
  6258. TEST(ClientProblemDetectionTest, ContentProvider) {
  6259. Server svr;
  6260. size_t content_length = 1024 * 1024;
  6261. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6262. res.set_content_provider(
  6263. content_length, "text/plain",
  6264. [&](size_t offset, size_t length, DataSink &sink) {
  6265. auto out_len = std::min(length, static_cast<size_t>(1024));
  6266. std::string out(out_len, '@');
  6267. sink.write(out.data(), out_len);
  6268. return offset < 4096;
  6269. },
  6270. [](bool success) { ASSERT_FALSE(success); });
  6271. });
  6272. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6273. res.set_content_provider(
  6274. 0, "text/plain",
  6275. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6276. EXPECT_TRUE(false);
  6277. return true;
  6278. },
  6279. [](bool success) { ASSERT_FALSE(success); });
  6280. });
  6281. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6282. auto se = detail::scope_exit([&] {
  6283. svr.stop();
  6284. listen_thread.join();
  6285. ASSERT_FALSE(svr.is_running());
  6286. });
  6287. svr.wait_until_ready();
  6288. Client cli("localhost", PORT);
  6289. {
  6290. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6291. size_t /*data_length*/) { return false; });
  6292. ASSERT_FALSE(res);
  6293. }
  6294. {
  6295. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6296. size_t /*data_length*/) { return false; });
  6297. ASSERT_TRUE(res);
  6298. }
  6299. }
  6300. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6301. Server svr;
  6302. svr.set_error_handler([](Request const &, Response &res) -> void {
  6303. res.set_chunked_content_provider(
  6304. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6305. sink.os << "hello";
  6306. sink.os << "world";
  6307. sink.done();
  6308. return true;
  6309. });
  6310. });
  6311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6312. auto se = detail::scope_exit([&] {
  6313. svr.stop();
  6314. listen_thread.join();
  6315. ASSERT_FALSE(svr.is_running());
  6316. });
  6317. svr.wait_until_ready();
  6318. Client cli("localhost", PORT);
  6319. auto res = cli.Get("/");
  6320. ASSERT_TRUE(res);
  6321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6322. EXPECT_EQ("helloworld", res->body);
  6323. }
  6324. TEST(LongPollingTest, ClientCloseDetection) {
  6325. Server svr;
  6326. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6327. res.set_chunked_content_provider(
  6328. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6329. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6330. sink.os << "hello";
  6331. auto count = 10;
  6332. while (count > 0 && sink.is_writable()) {
  6333. this_thread::sleep_for(chrono::milliseconds(10));
  6334. count--;
  6335. }
  6336. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6337. return true;
  6338. });
  6339. });
  6340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. listen_thread.join();
  6344. ASSERT_FALSE(svr.is_running());
  6345. });
  6346. svr.wait_until_ready();
  6347. Client cli("localhost", PORT);
  6348. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6349. EXPECT_EQ("hello", string(data, data_length));
  6350. return false; // close the socket immediately.
  6351. });
  6352. ASSERT_FALSE(res);
  6353. }
  6354. TEST(GetWithParametersTest, GetWithParameters) {
  6355. Server svr;
  6356. svr.Get("/", [&](const Request &req, Response &) {
  6357. EXPECT_EQ("world", req.get_param_value("hello"));
  6358. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6359. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6360. });
  6361. svr.Get("/params", [&](const Request &req, Response &) {
  6362. EXPECT_EQ("world", req.get_param_value("hello"));
  6363. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6364. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6365. });
  6366. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6367. EXPECT_EQ("resource-id", req.matches[1]);
  6368. EXPECT_EQ("foo", req.get_param_value("param1"));
  6369. EXPECT_EQ("bar", req.get_param_value("param2"));
  6370. });
  6371. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6372. EXPECT_EQ("user-id", req.path_params.at("id"));
  6373. EXPECT_EQ("foo", req.get_param_value("param1"));
  6374. EXPECT_EQ("bar", req.get_param_value("param2"));
  6375. });
  6376. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. ASSERT_FALSE(svr.is_running());
  6381. });
  6382. svr.wait_until_ready();
  6383. {
  6384. Client cli(HOST, PORT);
  6385. Params params;
  6386. params.emplace("hello", "world");
  6387. params.emplace("hello2", "world2");
  6388. params.emplace("hello3", "world3");
  6389. auto res = cli.Get("/", params, Headers{});
  6390. ASSERT_TRUE(res);
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. {
  6394. Client cli(HOST, PORT);
  6395. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ(StatusCode::OK_200, res->status);
  6398. }
  6399. {
  6400. Client cli(HOST, PORT);
  6401. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6402. ASSERT_TRUE(res);
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. }
  6405. {
  6406. Client cli(HOST, PORT);
  6407. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6408. ASSERT_TRUE(res);
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. }
  6412. TEST(GetWithParametersTest, GetWithParameters2) {
  6413. Server svr;
  6414. svr.Get("/", [&](const Request &req, Response &res) {
  6415. auto text = req.get_param_value("hello");
  6416. res.set_content(text, "text/plain");
  6417. });
  6418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6419. auto se = detail::scope_exit([&] {
  6420. svr.stop();
  6421. listen_thread.join();
  6422. ASSERT_FALSE(svr.is_running());
  6423. });
  6424. svr.wait_until_ready();
  6425. Client cli("localhost", PORT);
  6426. Params params;
  6427. params.emplace("hello", "world");
  6428. std::string body;
  6429. auto res = cli.Get("/", params, Headers{},
  6430. [&](const char *data, size_t data_length) {
  6431. body.append(data, data_length);
  6432. return true;
  6433. });
  6434. ASSERT_TRUE(res);
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. EXPECT_EQ("world", body);
  6437. }
  6438. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6439. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6440. auto host = "httpbin.org";
  6441. auto path = std::string{"/range/32"};
  6442. #else
  6443. auto host = "nghttp2.org";
  6444. auto path = std::string{"/httpbin/range/32"};
  6445. #endif
  6446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6447. SSLClient cli(host);
  6448. #else
  6449. Client cli(host);
  6450. #endif
  6451. cli.set_default_headers({make_range_header({{1, 10}})});
  6452. cli.set_connection_timeout(5);
  6453. {
  6454. auto res = cli.Get(path);
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ("bcdefghijk", res->body);
  6457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6458. }
  6459. {
  6460. auto res = cli.Get(path);
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ("bcdefghijk", res->body);
  6463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6464. }
  6465. }
  6466. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6467. Server svr;
  6468. svr.set_default_headers({{"Hello", "World"}});
  6469. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6470. res.set_content("ok", "text/plain");
  6471. });
  6472. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6473. auto se = detail::scope_exit([&] {
  6474. svr.stop();
  6475. listen_thread.join();
  6476. ASSERT_FALSE(svr.is_running());
  6477. });
  6478. svr.wait_until_ready();
  6479. Client cli("localhost", PORT);
  6480. auto res = cli.Get("/");
  6481. ASSERT_TRUE(res);
  6482. EXPECT_EQ(StatusCode::OK_200, res->status);
  6483. EXPECT_EQ("ok", res->body);
  6484. EXPECT_EQ("World", res->get_header_value("Hello"));
  6485. }
  6486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6487. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6489. ASSERT_TRUE(svr.is_valid());
  6490. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6491. std::this_thread::sleep_for(std::chrono::seconds(2));
  6492. res.set_content("a", "text/plain");
  6493. });
  6494. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6495. res.set_content("b", "text/plain");
  6496. });
  6497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. listen_thread.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. SSLClient cli("localhost", PORT);
  6505. cli.enable_server_certificate_verification(false);
  6506. cli.set_keep_alive(true);
  6507. cli.set_read_timeout(std::chrono::seconds(1));
  6508. auto resa = cli.Get("/a");
  6509. ASSERT_TRUE(!resa);
  6510. EXPECT_EQ(Error::Read, resa.error());
  6511. auto resb = cli.Get("/b");
  6512. ASSERT_TRUE(resb);
  6513. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6514. EXPECT_EQ("b", resb->body);
  6515. }
  6516. #endif
  6517. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6518. protected:
  6519. ServerTestWithAI_PASSIVE()
  6520. : cli_(HOST, PORT)
  6521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6522. ,
  6523. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6524. #endif
  6525. {
  6526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6527. cli_.enable_server_certificate_verification(false);
  6528. #endif
  6529. }
  6530. virtual void SetUp() {
  6531. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6532. res.set_content("Hello World!", "text/plain");
  6533. });
  6534. t_ = thread(
  6535. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6536. svr_.wait_until_ready();
  6537. }
  6538. virtual void TearDown() {
  6539. svr_.stop();
  6540. t_.join();
  6541. }
  6542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6543. SSLClient cli_;
  6544. SSLServer svr_;
  6545. #else
  6546. Client cli_;
  6547. Server svr_;
  6548. #endif
  6549. thread t_;
  6550. };
  6551. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6552. auto res = cli_.Get("/hi");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6556. EXPECT_EQ("Hello World!", res->body);
  6557. }
  6558. class ServerUpDownTest : public ::testing::Test {
  6559. protected:
  6560. ServerUpDownTest() : cli_(HOST, PORT) {}
  6561. virtual void SetUp() {
  6562. t_ = thread([&]() {
  6563. svr_.bind_to_any_port(HOST);
  6564. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6565. ASSERT_TRUE(svr_.listen_after_bind());
  6566. });
  6567. svr_.wait_until_ready();
  6568. }
  6569. virtual void TearDown() {
  6570. svr_.stop();
  6571. t_.join();
  6572. }
  6573. Client cli_;
  6574. Server svr_;
  6575. thread t_;
  6576. };
  6577. TEST_F(ServerUpDownTest, QuickStartStop) {
  6578. // Should not crash, especially when run with
  6579. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6580. }
  6581. class PayloadMaxLengthTest : public ::testing::Test {
  6582. protected:
  6583. PayloadMaxLengthTest()
  6584. : cli_(HOST, PORT)
  6585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6586. ,
  6587. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6588. #endif
  6589. {
  6590. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6591. cli_.enable_server_certificate_verification(false);
  6592. #endif
  6593. }
  6594. virtual void SetUp() {
  6595. svr_.set_payload_max_length(8);
  6596. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6597. res.set_content("test", "text/plain");
  6598. });
  6599. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6600. svr_.wait_until_ready();
  6601. }
  6602. virtual void TearDown() {
  6603. svr_.stop();
  6604. t_.join();
  6605. }
  6606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6607. SSLClient cli_;
  6608. SSLServer svr_;
  6609. #else
  6610. Client cli_;
  6611. Server svr_;
  6612. #endif
  6613. thread t_;
  6614. };
  6615. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6616. auto res = cli_.Post("/test", "123456789", "text/plain");
  6617. ASSERT_TRUE(res);
  6618. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6619. res = cli_.Post("/test", "12345678", "text/plain");
  6620. ASSERT_TRUE(res);
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. }
  6623. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6624. // Test chunked encoding with payload exceeding the 8-byte limit
  6625. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6626. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6627. ASSERT_TRUE(res);
  6628. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6629. }
  6630. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6631. // Test chunked encoding with payload within the 8-byte limit
  6632. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6633. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6634. ASSERT_TRUE(res);
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. }
  6637. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6638. // Test using send_request to send chunked data exceeding payload limit
  6639. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6640. "Host: " +
  6641. std::string(HOST) + ":" + std::to_string(PORT) +
  6642. "\r\n"
  6643. "Transfer-Encoding: chunked\r\n"
  6644. "Connection: close\r\n"
  6645. "\r\n"
  6646. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6647. "0123456789\r\n"
  6648. "0\r\n" // End chunk
  6649. "\r\n";
  6650. std::string response;
  6651. bool result = send_request(1, chunked_request, &response);
  6652. if (!result) {
  6653. // If send_request fails, it might be because the server closed the
  6654. // connection due to payload limit enforcement, which is acceptable
  6655. SUCCEED()
  6656. << "Server rejected oversized chunked request (connection closed)";
  6657. } else {
  6658. // If we got a response, check if it's an error response or connection was
  6659. // closed early Short response length indicates connection was closed due to
  6660. // payload limit
  6661. if (response.length() <= 10) {
  6662. SUCCEED() << "Server closed connection for oversized chunked request";
  6663. } else {
  6664. // Check for error status codes
  6665. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6666. response.find("Payload Too Large") != std::string::npos ||
  6667. response.find("400") != std::string::npos);
  6668. }
  6669. }
  6670. }
  6671. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6672. // Test request without Content-Length header exceeding payload limit
  6673. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6674. "Host: " +
  6675. std::string(HOST) + ":" +
  6676. std::to_string(PORT) +
  6677. "\r\n"
  6678. "Connection: close\r\n"
  6679. "\r\n";
  6680. // Add payload exceeding the 8-byte limit
  6681. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6682. request_without_content_length += large_payload;
  6683. std::string response;
  6684. bool result = send_request(1, request_without_content_length, &response);
  6685. if (!result) {
  6686. // If send_request fails, server likely closed connection due to payload
  6687. // limit
  6688. SUCCEED() << "Server rejected oversized request without Content-Length "
  6689. "(connection closed)";
  6690. } else {
  6691. // Check if server responded with error or closed connection early
  6692. if (response.length() <= 10) {
  6693. SUCCEED() << "Server closed connection for oversized request without "
  6694. "Content-Length";
  6695. } else {
  6696. // Check for error status codes
  6697. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6698. response.find("Payload Too Large") != std::string::npos ||
  6699. response.find("400") != std::string::npos);
  6700. }
  6701. }
  6702. }
  6703. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6704. // Test request without Content-Length header within payload limit
  6705. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6706. "Host: " +
  6707. std::string(HOST) + ":" +
  6708. std::to_string(PORT) +
  6709. "\r\n"
  6710. "Connection: close\r\n"
  6711. "\r\n";
  6712. // Add payload within the 8-byte limit
  6713. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6714. request_without_content_length += small_payload;
  6715. std::string response;
  6716. bool result = send_request(1, request_without_content_length, &response);
  6717. // For requests without Content-Length, the server may have different behavior
  6718. // The key is that it should not reject due to payload limit for small
  6719. // payloads
  6720. if (result) {
  6721. // Check for any HTTP response (success or error, but not connection closed)
  6722. if (response.length() > 10) {
  6723. SUCCEED()
  6724. << "Server processed request without Content-Length within limit";
  6725. } else {
  6726. // Short response might indicate connection closed, which is acceptable
  6727. SUCCEED() << "Server closed connection for request without "
  6728. "Content-Length (acceptable behavior)";
  6729. }
  6730. } else {
  6731. // Connection failure might be due to protocol requirements
  6732. SUCCEED() << "Connection issue with request without Content-Length "
  6733. "(environment-specific)";
  6734. }
  6735. }
  6736. class LargePayloadMaxLengthTest : public ::testing::Test {
  6737. protected:
  6738. LargePayloadMaxLengthTest()
  6739. : cli_(HOST, PORT)
  6740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6741. ,
  6742. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6743. #endif
  6744. {
  6745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6746. cli_.enable_server_certificate_verification(false);
  6747. #endif
  6748. }
  6749. virtual void SetUp() {
  6750. // Set 10MB payload limit
  6751. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6752. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6753. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6754. res.set_content("Large payload test", "text/plain");
  6755. });
  6756. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6757. svr_.wait_until_ready();
  6758. }
  6759. virtual void TearDown() {
  6760. svr_.stop();
  6761. t_.join();
  6762. }
  6763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6764. SSLClient cli_;
  6765. SSLServer svr_;
  6766. #else
  6767. Client cli_;
  6768. Server svr_;
  6769. #endif
  6770. thread t_;
  6771. };
  6772. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6773. // Test chunked encoding with payload within 10MB limit
  6774. std::string medium_payload(5 * 1024 * 1024,
  6775. 'A'); // 5MB payload, within 10MB limit
  6776. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6777. ASSERT_TRUE(res);
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. }
  6780. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6781. // Test chunked encoding with payload exceeding 10MB limit
  6782. std::string large_payload(12 * 1024 * 1024,
  6783. 'B'); // 12MB payload, exceeds 10MB limit
  6784. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6785. ASSERT_TRUE(res);
  6786. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6787. }
  6788. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6789. // Test request without Content-Length header within 10MB limit
  6790. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6791. "Host: " +
  6792. std::string(HOST) + ":" +
  6793. std::to_string(PORT) +
  6794. "\r\n"
  6795. "Connection: close\r\n"
  6796. "\r\n";
  6797. // Add 1MB payload (within 10MB limit)
  6798. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6799. request_without_content_length += medium_payload;
  6800. std::string response;
  6801. bool result = send_request(5, request_without_content_length, &response);
  6802. if (result) {
  6803. // Should get a proper HTTP response for payloads within limit
  6804. if (response.length() > 10) {
  6805. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6806. "10MB limit";
  6807. } else {
  6808. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6809. "Content-Length)";
  6810. }
  6811. } else {
  6812. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6813. }
  6814. }
  6815. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6816. // Test request without Content-Length header exceeding 10MB limit
  6817. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6818. "Host: " +
  6819. std::string(HOST) + ":" +
  6820. std::to_string(PORT) +
  6821. "\r\n"
  6822. "Connection: close\r\n"
  6823. "\r\n";
  6824. // Add 12MB payload (exceeds 10MB limit)
  6825. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6826. request_without_content_length += large_payload;
  6827. std::string response;
  6828. bool result = send_request(10, request_without_content_length, &response);
  6829. if (!result) {
  6830. // Server should close connection due to payload limit
  6831. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6832. "(connection closed)";
  6833. } else {
  6834. // Check for error response
  6835. if (response.length() <= 10) {
  6836. SUCCEED()
  6837. << "Server closed connection for 12MB request exceeding 10MB limit";
  6838. } else {
  6839. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6840. response.find("Payload Too Large") != std::string::npos ||
  6841. response.find("400") != std::string::npos);
  6842. }
  6843. }
  6844. }
  6845. TEST(HostAndPortPropertiesTest, NoSSL) {
  6846. httplib::Client cli("www.google.com", 1234);
  6847. ASSERT_EQ("www.google.com", cli.host());
  6848. ASSERT_EQ(1234, cli.port());
  6849. }
  6850. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6851. httplib::Client cli("www.google.com:1234");
  6852. ASSERT_EQ("www.google.com", cli.host());
  6853. ASSERT_EQ(1234, cli.port());
  6854. }
  6855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6856. TEST(HostAndPortPropertiesTest, SSL) {
  6857. httplib::SSLClient cli("www.google.com");
  6858. ASSERT_EQ("www.google.com", cli.host());
  6859. ASSERT_EQ(443, cli.port());
  6860. }
  6861. #endif
  6862. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6863. TEST(SSLClientTest, UpdateCAStore) {
  6864. httplib::SSLClient httplib_client("www.google.com");
  6865. auto ca_store_1 = X509_STORE_new();
  6866. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6867. nullptr);
  6868. httplib_client.set_ca_cert_store(ca_store_1);
  6869. auto ca_store_2 = X509_STORE_new();
  6870. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6871. nullptr);
  6872. httplib_client.set_ca_cert_store(ca_store_2);
  6873. }
  6874. TEST(SSLClientTest, ServerNameIndication_Online) {
  6875. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6876. auto host = "httpbin.org";
  6877. auto path = std::string{"/get"};
  6878. #else
  6879. auto host = "nghttp2.org";
  6880. auto path = std::string{"/httpbin/get"};
  6881. #endif
  6882. SSLClient cli(host, 443);
  6883. auto res = cli.Get(path);
  6884. ASSERT_TRUE(res);
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. }
  6887. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6888. // Use a site that will cause SSL verification failure due to self-signed cert
  6889. SSLClient cli("self-signed.badssl.com", 443);
  6890. cli.enable_server_certificate_verification(true);
  6891. auto res = cli.Get("/");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6894. // For SSL server verification errors, ssl_error should be 0, only
  6895. // ssl_openssl_error should be set
  6896. EXPECT_EQ(0, res.ssl_error());
  6897. // Verify OpenSSL error is captured for SSLServerVerification
  6898. // This occurs when SSL_get_verify_result() returns a verification failure
  6899. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6900. res.ssl_openssl_error());
  6901. }
  6902. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6903. // Use a site where hostname doesn't match the certificate
  6904. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6905. SSLClient cli("wrong.host.badssl.com", 443);
  6906. cli.enable_server_certificate_verification(true);
  6907. cli.enable_server_hostname_verification(true);
  6908. auto res = cli.Get("/");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6911. // For SSL hostname verification errors, ssl_error should be 0, only
  6912. // ssl_openssl_error should be set
  6913. EXPECT_EQ(0, res.ssl_error());
  6914. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6915. // This occurs when verify_host() fails due to hostname mismatch
  6916. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6917. res.ssl_openssl_error());
  6918. }
  6919. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6920. Client cli("https://google.com");
  6921. auto res = cli.Get("/");
  6922. ASSERT_TRUE(res);
  6923. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6924. }
  6925. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6926. SSLClient cli("google.com");
  6927. cli.set_ca_cert_path(CA_CERT_FILE);
  6928. auto res = cli.Get("/");
  6929. ASSERT_TRUE(res);
  6930. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6931. }
  6932. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6933. SSLClient cli("google.com");
  6934. cli.enable_server_certificate_verification(true);
  6935. cli.set_ca_cert_path("hello");
  6936. auto res = cli.Get("/");
  6937. ASSERT_TRUE(!res);
  6938. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6939. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6940. // should be set
  6941. EXPECT_EQ(0, res.ssl_error());
  6942. // Verify OpenSSL error is captured for SSLLoadingCerts
  6943. // This error occurs when SSL_CTX_load_verify_locations() fails
  6944. // > openssl errstr 0x80000002
  6945. // error:80000002:system library::No such file or directory
  6946. // > openssl errstr 0xA000126
  6947. // error:0A000126:SSL routines::unexpected eof while reading
  6948. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6949. res.ssl_openssl_error() == 0xA000126);
  6950. }
  6951. TEST(SSLClientTest, ServerCertificateVerification4) {
  6952. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6953. ASSERT_TRUE(svr.is_valid());
  6954. svr.Get("/test", [&](const Request &, Response &res) {
  6955. res.set_content("test", "text/plain");
  6956. svr.stop();
  6957. ASSERT_TRUE(true);
  6958. });
  6959. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6960. auto se = detail::scope_exit([&] {
  6961. t.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. SSLClient cli("127.0.0.1", PORT);
  6966. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6967. cli.enable_server_certificate_verification(true);
  6968. cli.set_connection_timeout(30);
  6969. auto res = cli.Get("/test");
  6970. ASSERT_TRUE(res);
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. }
  6973. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6974. std::string cert;
  6975. read_file(CA_CERT_FILE, cert);
  6976. SSLClient cli("google.com");
  6977. cli.load_ca_cert_store(cert.data(), cert.size());
  6978. const auto res = cli.Get("/");
  6979. ASSERT_TRUE(res);
  6980. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6981. }
  6982. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6983. // clang-format off
  6984. static constexpr char cert[] =
  6985. "GlobalSign Root CA\n"
  6986. "==================\n"
  6987. "-----BEGIN CERTIFICATE-----\n"
  6988. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6989. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6990. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6991. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6992. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6993. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6994. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6995. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6996. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6997. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6998. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6999. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7000. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7001. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7002. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7003. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7004. "-----END CERTIFICATE-----\n";
  7005. // clang-format on
  7006. SSLClient cli("google.com");
  7007. cli.load_ca_cert_store(cert, sizeof(cert));
  7008. const auto res = cli.Get("/");
  7009. ASSERT_TRUE(res);
  7010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7011. }
  7012. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7013. SSLClient cli("www.youtube.com");
  7014. cli.set_ca_cert_path(CA_CERT_FILE);
  7015. cli.enable_server_certificate_verification(true);
  7016. cli.set_follow_location(true);
  7017. auto res = cli.Get("/");
  7018. ASSERT_TRUE(res);
  7019. ASSERT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. TEST(SSLClientTest, Issue2004_Online) {
  7022. Client client("https://google.com");
  7023. client.set_follow_location(true);
  7024. auto res = client.Get("/");
  7025. ASSERT_TRUE(res);
  7026. ASSERT_EQ(StatusCode::OK_200, res->status);
  7027. auto body = res->body;
  7028. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7029. }
  7030. #if 0
  7031. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7032. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7033. ASSERT_TRUE(cli != nullptr);
  7034. cli->set_address_family(AF_INET6);
  7035. cli->set_interface("en0");
  7036. auto res = cli->Get("/get");
  7037. ASSERT_TRUE(res);
  7038. ASSERT_EQ(StatusCode::OK_200, res->status);
  7039. }
  7040. #endif
  7041. void ClientCertPresent(
  7042. const std::string &client_cert_file,
  7043. const std::string &client_private_key_file,
  7044. const std::string &client_encrypted_private_key_pass = std::string()) {
  7045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7046. CLIENT_CA_CERT_DIR);
  7047. ASSERT_TRUE(svr.is_valid());
  7048. svr.Get("/test", [&](const Request &req, Response &res) {
  7049. res.set_content("test", "text/plain");
  7050. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7051. ASSERT_TRUE(peer_cert != nullptr);
  7052. auto subject_name = X509_get_subject_name(peer_cert);
  7053. ASSERT_TRUE(subject_name != nullptr);
  7054. std::string common_name;
  7055. {
  7056. char name[BUFSIZ];
  7057. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7058. name, sizeof(name));
  7059. common_name.assign(name, static_cast<size_t>(name_len));
  7060. }
  7061. EXPECT_EQ("Common Name", common_name);
  7062. X509_free(peer_cert);
  7063. });
  7064. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7065. auto se = detail::scope_exit([&] {
  7066. svr.stop();
  7067. t.join();
  7068. ASSERT_FALSE(svr.is_running());
  7069. });
  7070. svr.wait_until_ready();
  7071. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7072. client_encrypted_private_key_pass);
  7073. cli.enable_server_certificate_verification(false);
  7074. cli.set_connection_timeout(30);
  7075. auto res = cli.Get("/test");
  7076. ASSERT_TRUE(res);
  7077. ASSERT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. TEST(SSLClientServerTest, ClientCertPresent) {
  7080. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7081. }
  7082. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7083. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7084. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7085. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7086. }
  7087. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7088. void MemoryClientCertPresent(
  7089. const std::string &client_cert_file,
  7090. const std::string &client_private_key_file,
  7091. const std::string &client_encrypted_private_key_pass = std::string()) {
  7092. auto f = fopen(SERVER_CERT_FILE, "r+");
  7093. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7094. fclose(f);
  7095. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7096. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7097. fclose(f);
  7098. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7099. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7100. auto client_ca_cert_store = X509_STORE_new();
  7101. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7102. X509_free(client_cert);
  7103. fclose(f);
  7104. f = fopen(client_cert_file.c_str(), "r+");
  7105. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7106. fclose(f);
  7107. f = fopen(client_private_key_file.c_str(), "r+");
  7108. auto client_private_key = PEM_read_PrivateKey(
  7109. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7110. fclose(f);
  7111. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7112. ASSERT_TRUE(svr.is_valid());
  7113. svr.Get("/test", [&](const Request &req, Response &res) {
  7114. res.set_content("test", "text/plain");
  7115. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7116. ASSERT_TRUE(peer_cert != nullptr);
  7117. auto subject_name = X509_get_subject_name(peer_cert);
  7118. ASSERT_TRUE(subject_name != nullptr);
  7119. std::string common_name;
  7120. {
  7121. char name[BUFSIZ];
  7122. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7123. name, sizeof(name));
  7124. common_name.assign(name, static_cast<size_t>(name_len));
  7125. }
  7126. EXPECT_EQ("Common Name", common_name);
  7127. X509_free(peer_cert);
  7128. });
  7129. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7130. auto se = detail::scope_exit([&] {
  7131. svr.stop();
  7132. t.join();
  7133. ASSERT_FALSE(svr.is_running());
  7134. });
  7135. svr.wait_until_ready();
  7136. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7137. client_encrypted_private_key_pass);
  7138. cli.enable_server_certificate_verification(false);
  7139. cli.set_connection_timeout(30);
  7140. auto res = cli.Get("/test");
  7141. ASSERT_TRUE(res);
  7142. ASSERT_EQ(StatusCode::OK_200, res->status);
  7143. X509_free(server_cert);
  7144. EVP_PKEY_free(server_private_key);
  7145. X509_free(client_cert);
  7146. EVP_PKEY_free(client_private_key);
  7147. }
  7148. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7149. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7150. }
  7151. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7152. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7153. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7154. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7155. }
  7156. #endif
  7157. TEST(SSLClientServerTest, ClientCertMissing) {
  7158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7159. CLIENT_CA_CERT_DIR);
  7160. ASSERT_TRUE(svr.is_valid());
  7161. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7162. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. t.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. SSLClient cli(HOST, PORT);
  7170. cli.set_connection_timeout(30);
  7171. auto res = cli.Get("/test");
  7172. ASSERT_TRUE(!res);
  7173. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7174. // For SSL server verification errors, ssl_error should be 0, only
  7175. // ssl_openssl_error should be set
  7176. EXPECT_EQ(0, res.ssl_error());
  7177. // Verify OpenSSL error is captured for SSLServerVerification
  7178. // Note: This test may have different error codes depending on the exact
  7179. // verification failure
  7180. EXPECT_NE(0UL, res.ssl_openssl_error());
  7181. }
  7182. TEST(SSLClientServerTest, TrustDirOptional) {
  7183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7184. ASSERT_TRUE(svr.is_valid());
  7185. svr.Get("/test", [&](const Request &, Response &res) {
  7186. res.set_content("test", "text/plain");
  7187. });
  7188. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7189. auto se = detail::scope_exit([&] {
  7190. svr.stop();
  7191. t.join();
  7192. ASSERT_FALSE(svr.is_running());
  7193. });
  7194. svr.wait_until_ready();
  7195. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7196. cli.enable_server_certificate_verification(false);
  7197. cli.set_connection_timeout(30);
  7198. auto res = cli.Get("/test");
  7199. ASSERT_TRUE(res);
  7200. ASSERT_EQ(StatusCode::OK_200, res->status);
  7201. }
  7202. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7203. class NoListenSSLServer : public SSLServer {
  7204. public:
  7205. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7206. const char *client_ca_cert_file_path,
  7207. const char *client_ca_cert_dir_path = nullptr)
  7208. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7209. client_ca_cert_dir_path),
  7210. stop_(false) {}
  7211. std::atomic_bool stop_;
  7212. private:
  7213. bool process_and_close_socket(socket_t /*sock*/) override {
  7214. // Don't create SSL context
  7215. while (!stop_.load()) {
  7216. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7217. }
  7218. return true;
  7219. }
  7220. };
  7221. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7222. CLIENT_CA_CERT_FILE);
  7223. ASSERT_TRUE(svr.is_valid());
  7224. svr.Get("/test", [&](const Request &, Response &res) {
  7225. res.set_content("test", "text/plain");
  7226. });
  7227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7228. auto se = detail::scope_exit([&] {
  7229. svr.stop_ = true;
  7230. svr.stop();
  7231. t.join();
  7232. ASSERT_FALSE(svr.is_running());
  7233. });
  7234. svr.wait_until_ready();
  7235. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7236. cli.enable_server_certificate_verification(false);
  7237. cli.set_connection_timeout(1);
  7238. auto res = cli.Get("/test");
  7239. ASSERT_TRUE(!res);
  7240. EXPECT_EQ(Error::SSLConnection, res.error());
  7241. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7242. }
  7243. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7244. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7245. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7246. SSL_CTX_set_options(&ssl_ctx,
  7247. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7248. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7249. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7250. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7251. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7252. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7253. "ECDHE-DSS-AES128-SHA256:"
  7254. "ECDHE-RSA-AES256-SHA256:"
  7255. "ECDHE-DSS-AES256-SHA256:";
  7256. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7257. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7258. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7259. SSL_FILETYPE_PEM) != 1) {
  7260. return false;
  7261. }
  7262. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7263. CLIENT_CA_CERT_DIR);
  7264. SSL_CTX_set_verify(
  7265. &ssl_ctx,
  7266. SSL_VERIFY_PEER |
  7267. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7268. nullptr);
  7269. return true;
  7270. };
  7271. SSLServer svr(setup_ssl_ctx_callback);
  7272. ASSERT_TRUE(svr.is_valid());
  7273. svr.Get("/test", [&](const Request &req, Response &res) {
  7274. res.set_content("test", "text/plain");
  7275. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7276. ASSERT_TRUE(peer_cert != nullptr);
  7277. auto subject_name = X509_get_subject_name(peer_cert);
  7278. ASSERT_TRUE(subject_name != nullptr);
  7279. std::string common_name;
  7280. {
  7281. char name[BUFSIZ];
  7282. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7283. name, sizeof(name));
  7284. common_name.assign(name, static_cast<size_t>(name_len));
  7285. }
  7286. EXPECT_EQ("Common Name", common_name);
  7287. X509_free(peer_cert);
  7288. });
  7289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. t.join();
  7293. ASSERT_FALSE(svr.is_running());
  7294. });
  7295. svr.wait_until_ready();
  7296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7297. cli.enable_server_certificate_verification(false);
  7298. cli.set_connection_timeout(30);
  7299. auto res = cli.Get("/test");
  7300. ASSERT_TRUE(res);
  7301. ASSERT_EQ(StatusCode::OK_200, res->status);
  7302. }
  7303. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7304. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7305. // prepare large data
  7306. std::random_device seed_gen;
  7307. std::mt19937 random(seed_gen());
  7308. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7309. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7310. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7311. // server
  7312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7313. ASSERT_TRUE(svr.is_valid());
  7314. svr.Post("/binary", [&](const Request &req, Response &res) {
  7315. EXPECT_EQ(large_size_byte, req.body.size());
  7316. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7317. res.set_content(req.body, "application/octet-stream");
  7318. });
  7319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7320. auto se = detail::scope_exit([&] {
  7321. svr.stop();
  7322. listen_thread.join();
  7323. ASSERT_FALSE(svr.is_running());
  7324. });
  7325. svr.wait_until_ready();
  7326. // client POST
  7327. SSLClient cli("localhost", PORT);
  7328. cli.enable_server_certificate_verification(false);
  7329. cli.set_read_timeout(std::chrono::seconds(100));
  7330. cli.set_write_timeout(std::chrono::seconds(100));
  7331. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7332. large_size_byte, "application/octet-stream");
  7333. // compare
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. EXPECT_EQ(large_size_byte, res->body.size());
  7336. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7337. }
  7338. #endif
  7339. #ifdef _WIN32
  7340. TEST(CleanupTest, WSACleanup) {
  7341. int ret = WSACleanup();
  7342. ASSERT_EQ(0, ret);
  7343. }
  7344. #endif
  7345. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7346. TEST(NoSSLSupport, SimpleInterface) {
  7347. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7348. }
  7349. #endif
  7350. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7351. TEST(InvalidScheme, SimpleInterface) {
  7352. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7353. }
  7354. #endif
  7355. TEST(NoScheme, SimpleInterface) {
  7356. Client cli("yahoo.com:80");
  7357. ASSERT_TRUE(cli.is_valid());
  7358. }
  7359. TEST(SendAPI, SimpleInterface_Online) {
  7360. Client cli("http://yahoo.com");
  7361. Request req;
  7362. req.method = "GET";
  7363. req.path = "/";
  7364. auto res = cli.send(req);
  7365. ASSERT_TRUE(res);
  7366. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7367. }
  7368. TEST(SendAPI, WithParamsInRequest) {
  7369. Server svr;
  7370. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7371. EXPECT_TRUE(req.has_param("test"));
  7372. EXPECT_EQ("test_value", req.get_param_value("test"));
  7373. });
  7374. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. Client cli(HOST, PORT);
  7382. {
  7383. Request req;
  7384. req.method = "GET";
  7385. req.path = "/";
  7386. req.params.emplace("test", "test_value");
  7387. auto res = cli.send(req);
  7388. ASSERT_TRUE(res);
  7389. }
  7390. {
  7391. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7392. ASSERT_TRUE(res);
  7393. }
  7394. }
  7395. TEST(ClientImplMethods, GetSocketTest) {
  7396. httplib::Server svr;
  7397. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7398. res.status = StatusCode::OK_200;
  7399. });
  7400. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7401. auto se = detail::scope_exit([&] {
  7402. svr.stop();
  7403. thread.join();
  7404. ASSERT_FALSE(svr.is_running());
  7405. });
  7406. svr.wait_until_ready();
  7407. {
  7408. httplib::Client cli("http://127.0.0.1:3333");
  7409. cli.set_keep_alive(true);
  7410. // Use the behavior of cpp-httplib of opening the connection
  7411. // only when the first request happens. If that changes,
  7412. // this test would be obsolete.
  7413. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7414. // This also implicitly tests the server. But other tests would fail much
  7415. // earlier than this one to be considered.
  7416. auto res = cli.Get("/");
  7417. ASSERT_TRUE(res);
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7420. }
  7421. }
  7422. // Disabled due to out-of-memory problem on GitHub Actions
  7423. #ifdef _WIN64
  7424. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7425. // allocate content size larger than 2GB in memory
  7426. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7427. char *content = (char *)malloc(content_size);
  7428. ASSERT_TRUE(content);
  7429. Server svr;
  7430. svr.Get("/foo",
  7431. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7432. res.set_content(content, content_size, "application/octet-stream");
  7433. });
  7434. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7435. auto se = detail::scope_exit([&] {
  7436. svr.stop();
  7437. listen_thread.join();
  7438. if (content) free(content);
  7439. ASSERT_FALSE(svr.is_running());
  7440. });
  7441. svr.wait_until_ready();
  7442. Client cli(HOST, PORT);
  7443. auto res = cli.Get("/foo");
  7444. ASSERT_TRUE(res);
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ(content_size, res->body.length());
  7447. }
  7448. #endif
  7449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7450. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7451. Client cli("http://yahoo.com");
  7452. auto res = cli.Get("/");
  7453. ASSERT_TRUE(res);
  7454. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7455. cli.set_follow_location(true);
  7456. res = cli.Get("/");
  7457. ASSERT_TRUE(res);
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7460. }
  7461. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7462. Client cli("https://yahoo.com");
  7463. auto res = cli.Get("/");
  7464. ASSERT_TRUE(res);
  7465. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7466. cli.set_follow_location(true);
  7467. res = cli.Get("/");
  7468. ASSERT_TRUE(res);
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7471. }
  7472. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7473. Client cli("https://yahoo.com");
  7474. auto res = cli.Get("/");
  7475. ASSERT_TRUE(res);
  7476. ASSERT_FALSE(!res);
  7477. ASSERT_TRUE(res);
  7478. ASSERT_FALSE(res == nullptr);
  7479. ASSERT_TRUE(res != nullptr);
  7480. EXPECT_EQ(Error::Success, res.error());
  7481. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7482. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7483. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7484. cli.set_follow_location(true);
  7485. res = cli.Get("/");
  7486. ASSERT_TRUE(res);
  7487. EXPECT_EQ(Error::Success, res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7489. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7492. }
  7493. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7494. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7495. Client cli("https://cdnjs.cloudflare.com");
  7496. auto res =
  7497. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7498. ASSERT_TRUE(res);
  7499. EXPECT_EQ(StatusCode::OK_200, res->status);
  7500. EXPECT_EQ(287630U, res->body.size());
  7501. EXPECT_EQ("application/javascript; charset=utf-8",
  7502. res->get_header_value("Content-Type"));
  7503. }
  7504. #endif
  7505. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7506. #undef REDIR_HOST // Silence compiler warning
  7507. #define REDIR_HOST "https://httpbingo.org"
  7508. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7509. Client cli(REDIR_HOST);
  7510. cli.set_follow_location(true);
  7511. auto res =
  7512. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7513. ASSERT_TRUE(res);
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. }
  7516. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7517. Client cli(REDIR_HOST);
  7518. cli.set_follow_location(true);
  7519. Params params;
  7520. params.emplace("url", "http://example.com");
  7521. params.emplace("status_code", "302");
  7522. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7523. ASSERT_TRUE(res);
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. }
  7526. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7527. Client cli(REDIR_HOST);
  7528. cli.set_follow_location(true);
  7529. Params params;
  7530. params.emplace("url", "http://example.com");
  7531. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7532. ASSERT_TRUE(res);
  7533. EXPECT_EQ(StatusCode::OK_200, res->status);
  7534. }
  7535. TEST(HttpToHttpsRedirectTest, CertFile) {
  7536. Server svr;
  7537. ASSERT_TRUE(svr.is_valid());
  7538. svr.Get("/index", [&](const Request &, Response &res) {
  7539. res.set_redirect("https://127.0.0.1:1235/index");
  7540. svr.stop();
  7541. });
  7542. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7543. ASSERT_TRUE(ssl_svr.is_valid());
  7544. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7545. res.set_content("test", "text/plain");
  7546. ssl_svr.stop();
  7547. });
  7548. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7549. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7550. auto se = detail::scope_exit([&] {
  7551. t2.join();
  7552. t.join();
  7553. ASSERT_FALSE(svr.is_running());
  7554. });
  7555. svr.wait_until_ready();
  7556. ssl_svr.wait_until_ready();
  7557. Client cli("127.0.0.1", PORT);
  7558. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7559. cli.enable_server_certificate_verification(true);
  7560. cli.set_follow_location(true);
  7561. cli.set_connection_timeout(30);
  7562. auto res = cli.Get("/index");
  7563. ASSERT_TRUE(res);
  7564. ASSERT_EQ(StatusCode::OK_200, res->status);
  7565. }
  7566. TEST(SSLClientRedirectTest, CertFile) {
  7567. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7568. ASSERT_TRUE(ssl_svr1.is_valid());
  7569. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7570. res.set_redirect("https://127.0.0.1:1235/index");
  7571. ssl_svr1.stop();
  7572. });
  7573. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7574. ASSERT_TRUE(ssl_svr2.is_valid());
  7575. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7576. res.set_content("test", "text/plain");
  7577. ssl_svr2.stop();
  7578. });
  7579. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7580. thread t2 =
  7581. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7582. auto se = detail::scope_exit([&] {
  7583. t2.join();
  7584. t.join();
  7585. ASSERT_FALSE(ssl_svr1.is_running());
  7586. });
  7587. ssl_svr1.wait_until_ready();
  7588. ssl_svr2.wait_until_ready();
  7589. SSLClient cli("127.0.0.1", PORT);
  7590. std::string cert;
  7591. read_file(SERVER_CERT2_FILE, cert);
  7592. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7593. cli.enable_server_certificate_verification(true);
  7594. cli.set_follow_location(true);
  7595. cli.set_connection_timeout(30);
  7596. auto res = cli.Get("/index");
  7597. ASSERT_TRUE(res);
  7598. ASSERT_EQ(StatusCode::OK_200, res->status);
  7599. }
  7600. TEST(MultipartFormDataTest, LargeData) {
  7601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7602. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7603. const ContentReader &content_reader) {
  7604. if (req.is_multipart_form_data()) {
  7605. std::vector<FormData> items;
  7606. content_reader(
  7607. [&](const FormData &file) {
  7608. items.push_back(file);
  7609. return true;
  7610. },
  7611. [&](const char *data, size_t data_length) {
  7612. items.back().content.append(data, data_length);
  7613. return true;
  7614. });
  7615. EXPECT_TRUE(std::string(items[0].name) == "document");
  7616. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7617. EXPECT_TRUE(items[0].filename == "2MB_data");
  7618. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7619. EXPECT_TRUE(items[1].name == "hello");
  7620. EXPECT_TRUE(items[1].content == "world");
  7621. EXPECT_TRUE(items[1].filename == "");
  7622. EXPECT_TRUE(items[1].content_type == "");
  7623. } else {
  7624. std::string body;
  7625. content_reader([&](const char *data, size_t data_length) {
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. }
  7630. });
  7631. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7632. auto se = detail::scope_exit([&] {
  7633. svr.stop();
  7634. t.join();
  7635. ASSERT_FALSE(svr.is_running());
  7636. });
  7637. svr.wait_until_ready();
  7638. {
  7639. std::string data(1024 * 1024 * 2, '.');
  7640. std::stringstream buffer;
  7641. buffer << data;
  7642. Client cli("https://localhost:8080");
  7643. cli.enable_server_certificate_verification(false);
  7644. UploadFormDataItems items{
  7645. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7646. {"hello", "world", "", ""},
  7647. };
  7648. auto res = cli.Post("/post", items);
  7649. ASSERT_TRUE(res);
  7650. ASSERT_EQ(StatusCode::OK_200, res->status);
  7651. }
  7652. }
  7653. TEST(MultipartFormDataTest, DataProviderItems) {
  7654. std::random_device seed_gen;
  7655. std::mt19937 random(seed_gen());
  7656. std::string rand1;
  7657. rand1.resize(1000);
  7658. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7659. std::string rand2;
  7660. rand2.resize(3000);
  7661. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7663. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7664. const ContentReader &content_reader) {
  7665. ASSERT_FALSE(req.is_multipart_form_data());
  7666. std::string body;
  7667. content_reader([&](const char *data, size_t data_length) {
  7668. body.append(data, data_length);
  7669. return true;
  7670. });
  7671. EXPECT_EQ(body, "");
  7672. });
  7673. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7674. const ContentReader &content_reader) {
  7675. ASSERT_TRUE(req.is_multipart_form_data());
  7676. std::vector<FormData> items;
  7677. content_reader(
  7678. [&](const FormData &file) {
  7679. items.push_back(file);
  7680. return true;
  7681. },
  7682. [&](const char *data, size_t data_length) {
  7683. items.back().content.append(data, data_length);
  7684. return true;
  7685. });
  7686. ASSERT_TRUE(items.size() == 2);
  7687. EXPECT_EQ(std::string(items[0].name), "name1");
  7688. EXPECT_EQ(items[0].content, "Testing123");
  7689. EXPECT_EQ(items[0].filename, "filename1");
  7690. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7691. EXPECT_EQ(items[1].name, "name2");
  7692. EXPECT_EQ(items[1].content, "Testing456");
  7693. EXPECT_EQ(items[1].filename, "");
  7694. EXPECT_EQ(items[1].content_type, "");
  7695. });
  7696. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7697. const ContentReader &content_reader) {
  7698. ASSERT_TRUE(req.is_multipart_form_data());
  7699. std::vector<FormData> items;
  7700. content_reader(
  7701. [&](const FormData &file) {
  7702. items.push_back(file);
  7703. return true;
  7704. },
  7705. [&](const char *data, size_t data_length) {
  7706. items.back().content.append(data, data_length);
  7707. return true;
  7708. });
  7709. ASSERT_TRUE(items.size() == 2);
  7710. EXPECT_EQ(items[0].name, "name3");
  7711. EXPECT_EQ(items[0].content, rand1);
  7712. EXPECT_EQ(items[0].filename, "filename3");
  7713. EXPECT_EQ(items[0].content_type, "");
  7714. EXPECT_EQ(items[1].name, "name4");
  7715. EXPECT_EQ(items[1].content, rand2);
  7716. EXPECT_EQ(items[1].filename, "filename4");
  7717. EXPECT_EQ(items[1].content_type, "");
  7718. });
  7719. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7720. const ContentReader &content_reader) {
  7721. ASSERT_TRUE(req.is_multipart_form_data());
  7722. std::vector<FormData> items;
  7723. content_reader(
  7724. [&](const FormData &file) {
  7725. items.push_back(file);
  7726. return true;
  7727. },
  7728. [&](const char *data, size_t data_length) {
  7729. items.back().content.append(data, data_length);
  7730. return true;
  7731. });
  7732. ASSERT_TRUE(items.size() == 4);
  7733. EXPECT_EQ(std::string(items[0].name), "name1");
  7734. EXPECT_EQ(items[0].content, "Testing123");
  7735. EXPECT_EQ(items[0].filename, "filename1");
  7736. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7737. EXPECT_EQ(items[1].name, "name2");
  7738. EXPECT_EQ(items[1].content, "Testing456");
  7739. EXPECT_EQ(items[1].filename, "");
  7740. EXPECT_EQ(items[1].content_type, "");
  7741. EXPECT_EQ(items[2].name, "name3");
  7742. EXPECT_EQ(items[2].content, rand1);
  7743. EXPECT_EQ(items[2].filename, "filename3");
  7744. EXPECT_EQ(items[2].content_type, "");
  7745. EXPECT_EQ(items[3].name, "name4");
  7746. EXPECT_EQ(items[3].content, rand2);
  7747. EXPECT_EQ(items[3].filename, "filename4");
  7748. EXPECT_EQ(items[3].content_type, "");
  7749. });
  7750. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7751. auto se = detail::scope_exit([&] {
  7752. svr.stop();
  7753. t.join();
  7754. ASSERT_FALSE(svr.is_running());
  7755. });
  7756. svr.wait_until_ready();
  7757. {
  7758. Client cli("https://localhost:8080");
  7759. cli.enable_server_certificate_verification(false);
  7760. UploadFormDataItems items{
  7761. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7762. {"name2", "Testing456", "", ""}, // not a file
  7763. };
  7764. {
  7765. auto res = cli.Post("/post-none", {}, {}, {});
  7766. ASSERT_TRUE(res);
  7767. ASSERT_EQ(StatusCode::OK_200, res->status);
  7768. }
  7769. FormDataProviderItems providers;
  7770. {
  7771. auto res =
  7772. cli.Post("/post-items", {}, items, providers); // empty providers
  7773. ASSERT_TRUE(res);
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. }
  7776. providers.push_back({"name3",
  7777. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7778. // test the offset is given correctly at each step
  7779. if (!offset)
  7780. sink.os.write(rand1.data(), 30);
  7781. else if (offset == 30)
  7782. sink.os.write(rand1.data() + 30, 300);
  7783. else if (offset == 330)
  7784. sink.os.write(rand1.data() + 330, 670);
  7785. else if (offset == rand1.size())
  7786. sink.done();
  7787. return true;
  7788. },
  7789. "filename3",
  7790. {}});
  7791. providers.push_back({"name4",
  7792. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7793. // test the offset is given correctly at each step
  7794. if (!offset)
  7795. sink.os.write(rand2.data(), 2000);
  7796. else if (offset == 2000)
  7797. sink.os.write(rand2.data() + 2000, 1);
  7798. else if (offset == 2001)
  7799. sink.os.write(rand2.data() + 2001, 999);
  7800. else if (offset == rand2.size())
  7801. sink.done();
  7802. return true;
  7803. },
  7804. "filename4",
  7805. {}});
  7806. {
  7807. auto res = cli.Post("/post-providers", {}, {}, providers);
  7808. ASSERT_TRUE(res);
  7809. ASSERT_EQ(StatusCode::OK_200, res->status);
  7810. }
  7811. {
  7812. auto res = cli.Post("/post-both", {}, items, providers);
  7813. ASSERT_TRUE(res);
  7814. ASSERT_EQ(StatusCode::OK_200, res->status);
  7815. }
  7816. }
  7817. }
  7818. TEST(MultipartFormDataTest, BadHeader) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7821. res.set_content("ok", "text/plain");
  7822. });
  7823. thread t = thread([&] { svr.listen(HOST, PORT); });
  7824. auto se = detail::scope_exit([&] {
  7825. svr.stop();
  7826. t.join();
  7827. ASSERT_FALSE(svr.is_running());
  7828. });
  7829. svr.wait_until_ready();
  7830. const std::string body =
  7831. "This is the preamble. It is to be ignored, though it\r\n"
  7832. "is a handy place for composition agents to include an\r\n"
  7833. "explanatory note to non-MIME conformant readers.\r\n"
  7834. "\r\n"
  7835. "\r\n"
  7836. "--simple boundary\r\n"
  7837. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7838. ": BAD...\r\n"
  7839. "\r\n"
  7840. "value1\r\n"
  7841. "--simple boundary\r\n"
  7842. "Content-Disposition: form-data; name=\"field2\"; "
  7843. "filename=\"example.txt\"\r\n"
  7844. "\r\n"
  7845. "value2\r\n"
  7846. "--simple boundary--\r\n"
  7847. "This is the epilogue. It is also to be ignored.\r\n";
  7848. std::string content_type =
  7849. R"(multipart/form-data; boundary="simple boundary")";
  7850. Client cli(HOST, PORT);
  7851. auto res = cli.Post("/post", body, content_type.c_str());
  7852. ASSERT_TRUE(res);
  7853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7854. }
  7855. TEST(MultipartFormDataTest, WithPreamble) {
  7856. Server svr;
  7857. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7858. res.set_content("ok", "text/plain");
  7859. });
  7860. thread t = thread([&] { svr.listen(HOST, PORT); });
  7861. auto se = detail::scope_exit([&] {
  7862. svr.stop();
  7863. t.join();
  7864. ASSERT_FALSE(svr.is_running());
  7865. });
  7866. svr.wait_until_ready();
  7867. const std::string body =
  7868. "This is the preamble. It is to be ignored, though it\r\n"
  7869. "is a handy place for composition agents to include an\r\n"
  7870. "explanatory note to non-MIME conformant readers.\r\n"
  7871. "\r\n"
  7872. "\r\n"
  7873. "--simple boundary\r\n"
  7874. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7875. "\r\n"
  7876. "value1\r\n"
  7877. "--simple boundary\r\n"
  7878. "Content-Disposition: form-data; name=\"field2\"; "
  7879. "filename=\"example.txt\"\r\n"
  7880. "\r\n"
  7881. "value2\r\n"
  7882. "--simple boundary--\r\n"
  7883. "This is the epilogue. It is also to be ignored.\r\n";
  7884. std::string content_type =
  7885. R"(multipart/form-data; boundary="simple boundary")";
  7886. Client cli(HOST, PORT);
  7887. auto res = cli.Post("/post", body, content_type.c_str());
  7888. ASSERT_TRUE(res);
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. }
  7891. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7893. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7894. const ContentReader &content_reader) {
  7895. if (req.is_multipart_form_data()) {
  7896. std::vector<FormData> items;
  7897. content_reader(
  7898. [&](const FormData &file) {
  7899. items.push_back(file);
  7900. return true;
  7901. },
  7902. [&](const char *data, size_t data_length) {
  7903. items.back().content.append(data, data_length);
  7904. return true;
  7905. });
  7906. EXPECT_TRUE(std::string(items[0].name) == "document");
  7907. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7908. EXPECT_TRUE(items[0].filename == "2MB_data");
  7909. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7910. EXPECT_TRUE(items[1].name == "hello");
  7911. EXPECT_TRUE(items[1].content == "world");
  7912. EXPECT_TRUE(items[1].filename == "");
  7913. EXPECT_TRUE(items[1].content_type == "");
  7914. } else {
  7915. std::string body;
  7916. content_reader([&](const char *data, size_t data_length) {
  7917. body.append(data, data_length);
  7918. return true;
  7919. });
  7920. }
  7921. });
  7922. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7923. auto se = detail::scope_exit([&] {
  7924. svr.stop();
  7925. t.join();
  7926. ASSERT_FALSE(svr.is_running());
  7927. });
  7928. svr.wait_until_ready();
  7929. {
  7930. std::string data(1024 * 1024 * 2, '.');
  7931. std::stringstream buffer;
  7932. buffer << data;
  7933. Client cli("https://localhost:8080");
  7934. cli.enable_server_certificate_verification(false);
  7935. UploadFormDataItems items{
  7936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7937. {"hello", "world", "", ""},
  7938. };
  7939. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7940. ASSERT_TRUE(res);
  7941. ASSERT_EQ(StatusCode::OK_200, res->status);
  7942. }
  7943. }
  7944. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7945. std::string data(1024 * 1024 * 2, '&');
  7946. std::stringstream buffer;
  7947. buffer << data;
  7948. Client cli("https://localhost:8080");
  7949. UploadFormDataItems items{
  7950. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7951. {"hello", "world", "", ""},
  7952. };
  7953. for (const char &c : " \t\r\n") {
  7954. auto res =
  7955. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7956. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7957. ASSERT_FALSE(res);
  7958. }
  7959. }
  7960. TEST(MultipartFormDataTest, PutFormData) {
  7961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7962. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7963. const ContentReader &content_reader) {
  7964. if (req.is_multipart_form_data()) {
  7965. std::vector<FormData> items;
  7966. content_reader(
  7967. [&](const FormData &file) {
  7968. items.push_back(file);
  7969. return true;
  7970. },
  7971. [&](const char *data, size_t data_length) {
  7972. items.back().content.append(data, data_length);
  7973. return true;
  7974. });
  7975. EXPECT_TRUE(std::string(items[0].name) == "document");
  7976. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7977. EXPECT_TRUE(items[0].filename == "2MB_data");
  7978. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7979. EXPECT_TRUE(items[1].name == "hello");
  7980. EXPECT_TRUE(items[1].content == "world");
  7981. EXPECT_TRUE(items[1].filename == "");
  7982. EXPECT_TRUE(items[1].content_type == "");
  7983. } else {
  7984. std::string body;
  7985. content_reader([&](const char *data, size_t data_length) {
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. }
  7990. });
  7991. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7992. auto se = detail::scope_exit([&] {
  7993. svr.stop();
  7994. t.join();
  7995. ASSERT_FALSE(svr.is_running());
  7996. });
  7997. svr.wait_until_ready();
  7998. {
  7999. std::string data(1024 * 1024 * 2, '&');
  8000. std::stringstream buffer;
  8001. buffer << data;
  8002. Client cli("https://localhost:8080");
  8003. cli.enable_server_certificate_verification(false);
  8004. UploadFormDataItems items{
  8005. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8006. {"hello", "world", "", ""},
  8007. };
  8008. auto res = cli.Put("/put", items);
  8009. ASSERT_TRUE(res);
  8010. ASSERT_EQ(StatusCode::OK_200, res->status);
  8011. }
  8012. }
  8013. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8015. svr.Put("/put_customboundary",
  8016. [&](const Request &req, const Response & /*res*/,
  8017. const ContentReader &content_reader) {
  8018. if (req.is_multipart_form_data()) {
  8019. std::vector<FormData> items;
  8020. content_reader(
  8021. [&](const FormData &file) {
  8022. items.push_back(file);
  8023. return true;
  8024. },
  8025. [&](const char *data, size_t data_length) {
  8026. items.back().content.append(data, data_length);
  8027. return true;
  8028. });
  8029. EXPECT_TRUE(std::string(items[0].name) == "document");
  8030. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8031. EXPECT_TRUE(items[0].filename == "2MB_data");
  8032. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8033. EXPECT_TRUE(items[1].name == "hello");
  8034. EXPECT_TRUE(items[1].content == "world");
  8035. EXPECT_TRUE(items[1].filename == "");
  8036. EXPECT_TRUE(items[1].content_type == "");
  8037. } else {
  8038. std::string body;
  8039. content_reader([&](const char *data, size_t data_length) {
  8040. body.append(data, data_length);
  8041. return true;
  8042. });
  8043. }
  8044. });
  8045. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8046. auto se = detail::scope_exit([&] {
  8047. svr.stop();
  8048. t.join();
  8049. ASSERT_FALSE(svr.is_running());
  8050. });
  8051. svr.wait_until_ready();
  8052. {
  8053. std::string data(1024 * 1024 * 2, '&');
  8054. std::stringstream buffer;
  8055. buffer << data;
  8056. Client cli("https://localhost:8080");
  8057. cli.enable_server_certificate_verification(false);
  8058. UploadFormDataItems items{
  8059. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8060. {"hello", "world", "", ""},
  8061. };
  8062. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8063. ASSERT_TRUE(res);
  8064. ASSERT_EQ(StatusCode::OK_200, res->status);
  8065. }
  8066. }
  8067. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8068. std::string data(1024 * 1024 * 2, '&');
  8069. std::stringstream buffer;
  8070. buffer << data;
  8071. Client cli("https://localhost:8080");
  8072. cli.enable_server_certificate_verification(false);
  8073. UploadFormDataItems items{
  8074. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8075. {"hello", "world", "", ""},
  8076. };
  8077. for (const char &c : " \t\r\n") {
  8078. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8079. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8080. ASSERT_FALSE(res);
  8081. }
  8082. }
  8083. TEST(MultipartFormDataTest, AlternateFilename) {
  8084. auto handled = false;
  8085. Server svr;
  8086. svr.Post("/test", [&](const Request &req, Response &res) {
  8087. ASSERT_EQ(2u, req.form.files.size());
  8088. ASSERT_EQ(1u, req.form.fields.size());
  8089. // Test files
  8090. const auto &file1 = req.form.get_file("file1");
  8091. ASSERT_EQ("file1", file1.name);
  8092. ASSERT_EQ("A.txt", file1.filename);
  8093. ASSERT_EQ("text/plain", file1.content_type);
  8094. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8095. const auto &file2 = req.form.get_file("file2");
  8096. ASSERT_EQ("file2", file2.name);
  8097. ASSERT_EQ("a.html", file2.filename);
  8098. ASSERT_EQ("text/html", file2.content_type);
  8099. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8100. file2.content);
  8101. // Test text field
  8102. const auto &text = req.form.get_field("text");
  8103. ASSERT_EQ("text default", text);
  8104. res.set_content("ok", "text/plain");
  8105. handled = true;
  8106. });
  8107. thread t = thread([&] { svr.listen(HOST, PORT); });
  8108. auto se = detail::scope_exit([&] {
  8109. svr.stop();
  8110. t.join();
  8111. ASSERT_FALSE(svr.is_running());
  8112. ASSERT_TRUE(handled);
  8113. });
  8114. svr.wait_until_ready();
  8115. auto req = "POST /test HTTP/1.1\r\n"
  8116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8117. "Content-Length: 399\r\n"
  8118. "\r\n"
  8119. "----------\r\n"
  8120. "Content-Disposition: form-data; name=\"text\"\r\n"
  8121. "\r\n"
  8122. "text default\r\n"
  8123. "----------\r\n"
  8124. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8125. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8126. "Content-Type: text/plain\r\n"
  8127. "\r\n"
  8128. "Content of a.txt.\r\n"
  8129. "\r\n"
  8130. "----------\r\n"
  8131. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8132. "\"a.html\"\r\n"
  8133. "Content-Type: text/html\r\n"
  8134. "\r\n"
  8135. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8136. "\r\n"
  8137. "------------\r\n";
  8138. ASSERT_TRUE(send_request(1, req));
  8139. }
  8140. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8141. auto handled = false;
  8142. Server svr;
  8143. svr.Post("/test", [&](const Request &req, Response &) {
  8144. ASSERT_EQ(2u, req.form.fields.size());
  8145. const auto &text1 = req.form.get_field("text1");
  8146. ASSERT_EQ("text1", text1);
  8147. const auto &text2 = req.form.get_field("text2");
  8148. ASSERT_EQ("text2", text2);
  8149. handled = true;
  8150. });
  8151. thread t = thread([&] { svr.listen(HOST, PORT); });
  8152. auto se = detail::scope_exit([&] {
  8153. svr.stop();
  8154. t.join();
  8155. ASSERT_FALSE(svr.is_running());
  8156. ASSERT_TRUE(handled);
  8157. });
  8158. svr.wait_until_ready();
  8159. auto req = "POST /test HTTP/1.1\r\n"
  8160. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8161. "Content-Length: 146\r\n"
  8162. "\r\n----------\r\n"
  8163. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8164. "\r\n"
  8165. "text1"
  8166. "\r\n----------\r\n"
  8167. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8168. "\r\n"
  8169. "text2"
  8170. "\r\n------------";
  8171. std::string response;
  8172. ASSERT_TRUE(send_request(1, req, &response));
  8173. ASSERT_EQ("200", response.substr(9, 3));
  8174. }
  8175. TEST(MultipartFormDataTest, ContentLength) {
  8176. auto handled = false;
  8177. Server svr;
  8178. svr.Post("/test", [&](const Request &req, Response &) {
  8179. ASSERT_EQ(2u, req.form.fields.size());
  8180. const auto &text1 = req.form.get_field("text1");
  8181. ASSERT_EQ("text1", text1);
  8182. const auto &text2 = req.form.get_field("text2");
  8183. ASSERT_EQ("text2", text2);
  8184. handled = true;
  8185. });
  8186. thread t = thread([&] { svr.listen(HOST, PORT); });
  8187. auto se = detail::scope_exit([&] {
  8188. svr.stop();
  8189. t.join();
  8190. ASSERT_FALSE(svr.is_running());
  8191. ASSERT_TRUE(handled);
  8192. });
  8193. svr.wait_until_ready();
  8194. auto req = "POST /test HTTP/1.1\r\n"
  8195. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8196. "Content-Length: 167\r\n"
  8197. "\r\n----------\r\n"
  8198. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8199. "Content-Length: 5\r\n"
  8200. "\r\n"
  8201. "text1"
  8202. "\r\n----------\r\n"
  8203. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8204. "\r\n"
  8205. "text2"
  8206. "\r\n------------\r\n";
  8207. std::string response;
  8208. ASSERT_TRUE(send_request(1, req, &response));
  8209. ASSERT_EQ("200", response.substr(9, 3));
  8210. }
  8211. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8212. auto handled = false;
  8213. Server svr;
  8214. svr.Post("/test", [&](const Request &req, Response &) {
  8215. ASSERT_EQ(2u, req.form.fields.size());
  8216. const auto &text1 = req.form.get_field("text1");
  8217. ASSERT_EQ("text1", text1);
  8218. // TODO: Add header access for text fields if needed
  8219. const auto &text2 = req.form.get_field("text2");
  8220. ASSERT_EQ("text2", text2);
  8221. // TODO: Header access for text fields needs to be implemented
  8222. // auto &headers = it->second.headers;
  8223. // ASSERT_EQ(3U, headers.size());
  8224. // auto custom_header = headers.find("x-whatever");
  8225. // ASSERT_TRUE(custom_header != headers.end());
  8226. // ASSERT_NE("customvalue", custom_header->second);
  8227. // ASSERT_EQ("CustomValue", custom_header->second);
  8228. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8229. handled = true;
  8230. });
  8231. thread t = thread([&] { svr.listen(HOST, PORT); });
  8232. auto se = detail::scope_exit([&] {
  8233. svr.stop();
  8234. t.join();
  8235. ASSERT_FALSE(svr.is_running());
  8236. ASSERT_TRUE(handled);
  8237. });
  8238. svr.wait_until_ready();
  8239. auto req = "POST /test HTTP/1.1\r\n"
  8240. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8241. "Content-Length: 232\r\n"
  8242. "\r\n----------\r\n"
  8243. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8244. "Content-Length: 5\r\n"
  8245. "X-Test: 1\r\n"
  8246. "\r\n"
  8247. "text1"
  8248. "\r\n----------\r\n"
  8249. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8250. "Content-Type: text/plain\r\n"
  8251. "X-Whatever: CustomValue\r\n"
  8252. "\r\n"
  8253. "text2"
  8254. "\r\n------------\r\n"
  8255. "That should be disregarded. Not even read";
  8256. std::string response;
  8257. ASSERT_TRUE(send_request(1, req, &response));
  8258. ASSERT_EQ("200", response.substr(9, 3));
  8259. }
  8260. #endif
  8261. TEST(MultipartFormDataTest, LargeHeader) {
  8262. auto handled = false;
  8263. Server svr;
  8264. svr.Post("/test", [&](const Request &req, Response &) {
  8265. ASSERT_EQ(1u, req.form.fields.size());
  8266. const auto &text = req.form.get_field("name1");
  8267. ASSERT_EQ("text1", text);
  8268. handled = true;
  8269. });
  8270. thread t = thread([&] { svr.listen(HOST, PORT); });
  8271. auto se = detail::scope_exit([&] {
  8272. svr.stop();
  8273. t.join();
  8274. ASSERT_FALSE(svr.is_running());
  8275. ASSERT_TRUE(handled);
  8276. });
  8277. svr.wait_until_ready();
  8278. auto boundary = std::string("cpp-httplib-multipart-data");
  8279. std::string content = "--" + boundary +
  8280. "\r\n"
  8281. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8282. "\r\n"
  8283. "text1\r\n"
  8284. "--" +
  8285. boundary + "--\r\n";
  8286. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8287. "Content-Type: multipart/form-data;boundary=" +
  8288. boundary +
  8289. "\r\n"
  8290. "Content-Length: " +
  8291. std::to_string(content.size()) +
  8292. "\r\n"
  8293. "Dummy-Header: ";
  8294. std::string header_suffix = "\r\n"
  8295. "\r\n";
  8296. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8297. size_t header_dummy_size =
  8298. read_buff_size -
  8299. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8300. auto header_dummy = std::string(header_dummy_size, '@');
  8301. auto req = header_prefix + header_dummy + header_suffix + content;
  8302. std::string response;
  8303. ASSERT_TRUE(send_request(1, req, &response));
  8304. ASSERT_EQ("200", response.substr(9, 3));
  8305. }
  8306. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8307. static constexpr unsigned int number_of_tasks{1000000};
  8308. std::atomic_uint count{0};
  8309. std::unique_ptr<TaskQueue> task_queue{
  8310. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8311. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8312. auto queued = task_queue->enqueue(
  8313. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8314. EXPECT_TRUE(queued);
  8315. }
  8316. EXPECT_NO_THROW(task_queue->shutdown());
  8317. EXPECT_EQ(number_of_tasks, count.load());
  8318. }
  8319. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8320. static constexpr unsigned int number_of_tasks{1000000};
  8321. static constexpr unsigned int qlimit{2};
  8322. unsigned int queued_count{0};
  8323. std::atomic_uint count{0};
  8324. std::unique_ptr<TaskQueue> task_queue{
  8325. new ThreadPool{/*num_threads=*/1, qlimit}};
  8326. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8327. if (task_queue->enqueue(
  8328. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8329. queued_count++;
  8330. }
  8331. }
  8332. EXPECT_NO_THROW(task_queue->shutdown());
  8333. EXPECT_EQ(queued_count, count.load());
  8334. EXPECT_TRUE(queued_count <= number_of_tasks);
  8335. EXPECT_TRUE(queued_count >= qlimit);
  8336. }
  8337. TEST(TaskQueueTest, MaxQueuedRequests) {
  8338. static constexpr unsigned int qlimit{3};
  8339. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8340. std::condition_variable sem_cv;
  8341. std::mutex sem_mtx;
  8342. int credits = 0;
  8343. bool queued;
  8344. /* Fill up the queue with tasks that will block until we give them credits to
  8345. * complete. */
  8346. for (unsigned int n = 0; n <= qlimit;) {
  8347. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8348. std::unique_lock<std::mutex> lock(sem_mtx);
  8349. while (credits <= 0) {
  8350. sem_cv.wait(lock);
  8351. }
  8352. /* Consume the credit and signal the test code if they are all gone. */
  8353. if (--credits == 0) { sem_cv.notify_one(); }
  8354. });
  8355. if (n < qlimit) {
  8356. /* The first qlimit enqueues must succeed. */
  8357. EXPECT_TRUE(queued);
  8358. } else {
  8359. /* The last one will succeed only when the worker thread
  8360. * starts and dequeues the first blocking task. Although
  8361. * not necessary for the correctness of this test, we sleep for
  8362. * a short while to avoid busy waiting. */
  8363. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8364. }
  8365. if (queued) { n++; }
  8366. }
  8367. /* Further enqueues must fail since the queue is full. */
  8368. for (auto i = 0; i < 4; i++) {
  8369. queued = task_queue->enqueue([] {});
  8370. EXPECT_FALSE(queued);
  8371. }
  8372. /* Give the credits to allow the previous tasks to complete. */
  8373. {
  8374. std::unique_lock<std::mutex> lock(sem_mtx);
  8375. credits += qlimit + 1;
  8376. }
  8377. sem_cv.notify_all();
  8378. /* Wait for all the credits to be consumed. */
  8379. {
  8380. std::unique_lock<std::mutex> lock(sem_mtx);
  8381. while (credits > 0) {
  8382. sem_cv.wait(lock);
  8383. }
  8384. }
  8385. /* Check that we are able again to enqueue at least qlimit tasks. */
  8386. for (unsigned int i = 0; i < qlimit; i++) {
  8387. queued = task_queue->enqueue([] {});
  8388. EXPECT_TRUE(queued);
  8389. }
  8390. EXPECT_NO_THROW(task_queue->shutdown());
  8391. }
  8392. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8393. Server svr;
  8394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8395. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8396. });
  8397. svr.Get("/hello", [](const Request &req, Response &res) {
  8398. res.set_content(req.get_param_value("key"), "text/plain");
  8399. });
  8400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8401. auto se = detail::scope_exit([&] {
  8402. svr.stop();
  8403. thread.join();
  8404. ASSERT_FALSE(svr.is_running());
  8405. });
  8406. svr.wait_until_ready();
  8407. {
  8408. Client cli(HOST, PORT);
  8409. cli.set_follow_location(true);
  8410. auto res = cli.Get("/");
  8411. ASSERT_TRUE(res);
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("val&key2=val2", res->body);
  8414. }
  8415. }
  8416. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8417. Server svr;
  8418. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8419. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8420. });
  8421. svr.Get("/hello", [](const Request &req, Response &res) {
  8422. res.set_content(req.get_param_value("key"), "text/plain");
  8423. });
  8424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8425. auto se = detail::scope_exit([&] {
  8426. svr.stop();
  8427. thread.join();
  8428. ASSERT_FALSE(svr.is_running());
  8429. });
  8430. svr.wait_until_ready();
  8431. {
  8432. Client cli(HOST, PORT);
  8433. cli.set_follow_location(true);
  8434. auto res = cli.Get("/");
  8435. ASSERT_TRUE(res);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8438. }
  8439. }
  8440. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8441. TEST(RedirectTest, Issue2185_Online) {
  8442. SSLClient client("github.com");
  8443. client.set_follow_location(true);
  8444. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8445. "Coollab-Windows.zip");
  8446. ASSERT_TRUE(res);
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. EXPECT_EQ(9920427U, res->body.size());
  8449. }
  8450. #endif
  8451. TEST(VulnerabilityTest, CRLFInjection) {
  8452. Server svr;
  8453. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8454. res.set_content("Hello 1", "text/plain");
  8455. });
  8456. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8457. res.set_content("Hello 2", "text/plain");
  8458. });
  8459. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8460. res.set_content("Hello 3", "text/plain");
  8461. });
  8462. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8463. res.set_content("Hello 4", "text/plain");
  8464. });
  8465. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8466. for (const auto &x : req.headers) {
  8467. auto key = x.first;
  8468. EXPECT_STRNE("evil", key.c_str());
  8469. }
  8470. });
  8471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8472. auto se = detail::scope_exit([&] {
  8473. svr.stop();
  8474. thread.join();
  8475. ASSERT_FALSE(svr.is_running());
  8476. });
  8477. svr.wait_until_ready();
  8478. {
  8479. Client cli(HOST, PORT);
  8480. cli.Post("/test1", "A=B",
  8481. "application/x-www-form-urlencoded\r\nevil: hello1");
  8482. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8483. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8484. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8485. }
  8486. }
  8487. TEST(PathParamsTest, StaticMatch) {
  8488. const auto pattern = "/users/all";
  8489. detail::PathParamsMatcher matcher(pattern);
  8490. Request request;
  8491. request.path = "/users/all";
  8492. ASSERT_TRUE(matcher.match(request));
  8493. std::unordered_map<std::string, std::string> expected_params = {};
  8494. EXPECT_EQ(request.path_params, expected_params);
  8495. }
  8496. TEST(PathParamsTest, StaticMismatch) {
  8497. const auto pattern = "/users/all";
  8498. detail::PathParamsMatcher matcher(pattern);
  8499. Request request;
  8500. request.path = "/users/1";
  8501. ASSERT_FALSE(matcher.match(request));
  8502. }
  8503. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8504. const auto pattern = "/users/:id/subscriptions";
  8505. detail::PathParamsMatcher matcher(pattern);
  8506. Request request;
  8507. request.path = "/users/42/subscriptions";
  8508. ASSERT_TRUE(matcher.match(request));
  8509. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8510. EXPECT_EQ(request.path_params, expected_params);
  8511. }
  8512. TEST(PathParamsTest, SingleParamInTheEnd) {
  8513. const auto pattern = "/users/:id";
  8514. detail::PathParamsMatcher matcher(pattern);
  8515. Request request;
  8516. request.path = "/users/24";
  8517. ASSERT_TRUE(matcher.match(request));
  8518. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8519. EXPECT_EQ(request.path_params, expected_params);
  8520. }
  8521. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8522. const auto pattern = "/users/:id/";
  8523. detail::PathParamsMatcher matcher(pattern);
  8524. Request request;
  8525. request.path = "/users/42/";
  8526. ASSERT_TRUE(matcher.match(request));
  8527. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8528. EXPECT_EQ(request.path_params, expected_params);
  8529. }
  8530. TEST(PathParamsTest, EmptyParam) {
  8531. const auto pattern = "/users/:id/";
  8532. detail::PathParamsMatcher matcher(pattern);
  8533. Request request;
  8534. request.path = "/users//";
  8535. ASSERT_TRUE(matcher.match(request));
  8536. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8537. EXPECT_EQ(request.path_params, expected_params);
  8538. }
  8539. TEST(PathParamsTest, FragmentMismatch) {
  8540. const auto pattern = "/users/:id/";
  8541. detail::PathParamsMatcher matcher(pattern);
  8542. Request request;
  8543. request.path = "/admins/24/";
  8544. ASSERT_FALSE(matcher.match(request));
  8545. }
  8546. TEST(PathParamsTest, ExtraFragments) {
  8547. const auto pattern = "/users/:id";
  8548. detail::PathParamsMatcher matcher(pattern);
  8549. Request request;
  8550. request.path = "/users/42/subscriptions";
  8551. ASSERT_FALSE(matcher.match(request));
  8552. }
  8553. TEST(PathParamsTest, MissingTrailingParam) {
  8554. const auto pattern = "/users/:id";
  8555. detail::PathParamsMatcher matcher(pattern);
  8556. Request request;
  8557. request.path = "/users";
  8558. ASSERT_FALSE(matcher.match(request));
  8559. }
  8560. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8561. const auto pattern = "/users/:id/subscriptions";
  8562. detail::PathParamsMatcher matcher(pattern);
  8563. Request request;
  8564. request.path = "/users/subscriptions";
  8565. ASSERT_FALSE(matcher.match(request));
  8566. }
  8567. TEST(PathParamsTest, MultipleParams) {
  8568. const auto pattern = "/users/:userid/subscriptions/:subid";
  8569. detail::PathParamsMatcher matcher(pattern);
  8570. Request request;
  8571. request.path = "/users/42/subscriptions/2";
  8572. ASSERT_TRUE(matcher.match(request));
  8573. std::unordered_map<std::string, std::string> expected_params = {
  8574. {"userid", "42"}, {"subid", "2"}};
  8575. EXPECT_EQ(request.path_params, expected_params);
  8576. }
  8577. TEST(PathParamsTest, SequenceOfParams) {
  8578. const auto pattern = "/values/:x/:y/:z";
  8579. detail::PathParamsMatcher matcher(pattern);
  8580. Request request;
  8581. request.path = "/values/1/2/3";
  8582. ASSERT_TRUE(matcher.match(request));
  8583. std::unordered_map<std::string, std::string> expected_params = {
  8584. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8585. EXPECT_EQ(request.path_params, expected_params);
  8586. }
  8587. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8588. const auto pattern = "/prefix:suffix";
  8589. detail::PathParamsMatcher matcher(pattern);
  8590. Request request;
  8591. request.path = "/prefix:suffix";
  8592. ASSERT_TRUE(matcher.match(request));
  8593. const std::unordered_map<std::string, std::string> expected_params = {};
  8594. EXPECT_EQ(request.path_params, expected_params);
  8595. }
  8596. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8597. // If ipv6 regex working, regex match codepath is taken.
  8598. // else port will default to 80 in Client impl
  8599. int clientImplMagicPort = 80;
  8600. int port = 4321;
  8601. // above ports must be different to avoid false negative
  8602. EXPECT_NE(clientImplMagicPort, port);
  8603. std::string ipV6TestURL = "http://[ff06::c3]";
  8604. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8605. CLIENT_PRIVATE_KEY_FILE);
  8606. EXPECT_EQ(cli.port(), port);
  8607. }
  8608. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8609. auto file_path = "./www/dir/index.html";
  8610. auto dir_path = "./www/dir";
  8611. detail::FileStat stat_file(file_path);
  8612. EXPECT_TRUE(stat_file.is_file());
  8613. EXPECT_FALSE(stat_file.is_dir());
  8614. detail::FileStat stat_dir(dir_path);
  8615. EXPECT_FALSE(stat_dir.is_file());
  8616. EXPECT_TRUE(stat_dir.is_dir());
  8617. }
  8618. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8619. Server svr;
  8620. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8621. EXPECT_EQ(res.status, 400);
  8622. });
  8623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8624. auto se = detail::scope_exit([&] {
  8625. svr.stop();
  8626. thread.join();
  8627. ASSERT_FALSE(svr.is_running());
  8628. });
  8629. svr.wait_until_ready();
  8630. Client cli(HOST, PORT);
  8631. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8632. }
  8633. TEST(InvalidHeaderCharsTest, is_field_name) {
  8634. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8635. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8636. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8637. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8638. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8639. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8640. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8641. EXPECT_FALSE(detail::fields::is_field_name(""));
  8642. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8643. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8644. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8645. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8646. }
  8647. TEST(InvalidHeaderCharsTest, is_field_value) {
  8648. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8649. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8650. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8651. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8652. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8653. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8654. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8655. EXPECT_TRUE(detail::fields::is_field_value(""));
  8656. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8657. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8658. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8659. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8660. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8661. }
  8662. TEST(InvalidHeaderCharsTest, OnServer) {
  8663. Server svr;
  8664. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8665. std::string header = "Not Set";
  8666. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8667. res.set_header(header, "value");
  8668. res.set_content("Page Content Page Content", "text/plain");
  8669. });
  8670. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8671. std::string header = "Not Set";
  8672. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8673. res.set_header("X-Test", header);
  8674. res.set_content("Page Content Page Content", "text/plain");
  8675. });
  8676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8677. auto se = detail::scope_exit([&] {
  8678. svr.stop();
  8679. thread.join();
  8680. ASSERT_FALSE(svr.is_running());
  8681. });
  8682. svr.wait_until_ready();
  8683. Client cli(HOST, PORT);
  8684. {
  8685. auto res = cli.Get(
  8686. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8687. ASSERT_TRUE(res);
  8688. EXPECT_EQ("Page Content Page Content", res->body);
  8689. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8690. }
  8691. {
  8692. auto res = cli.Get(
  8693. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8694. ASSERT_TRUE(res);
  8695. EXPECT_EQ("Page Content Page Content", res->body);
  8696. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8697. }
  8698. }
  8699. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8700. auto handled = false;
  8701. Server svr;
  8702. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8703. thread t = thread([&] { svr.listen(HOST, PORT); });
  8704. auto se = detail::scope_exit([&] {
  8705. svr.stop();
  8706. t.join();
  8707. ASSERT_FALSE(svr.is_running());
  8708. ASSERT_FALSE(handled);
  8709. });
  8710. svr.wait_until_ready();
  8711. auto req = "POST /test HTTP/1.1\r\n"
  8712. "Content-Length: x\r\n"
  8713. "\r\n";
  8714. std::string response;
  8715. ASSERT_TRUE(send_request(1, req, &response));
  8716. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8717. response.substr(0, response.find("\r\n")));
  8718. }
  8719. #ifndef _WIN32
  8720. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8721. static constexpr char reject[] = "Unauthorized";
  8722. static constexpr char accept[] = "Upload accepted";
  8723. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8724. Server svr;
  8725. svr.set_expect_100_continue_handler(
  8726. [](const Request & /*req*/, Response &res) {
  8727. res.status = StatusCode::Unauthorized_401;
  8728. res.set_content(reject, "text/plain");
  8729. return res.status;
  8730. });
  8731. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8732. res.set_content(accept, "text/plain");
  8733. });
  8734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8735. auto se = detail::scope_exit([&] {
  8736. svr.stop();
  8737. thread.join();
  8738. ASSERT_FALSE(svr.is_running());
  8739. });
  8740. svr.wait_until_ready();
  8741. {
  8742. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8743. curl_easy_init(), &curl_easy_cleanup};
  8744. ASSERT_NE(curl, nullptr);
  8745. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8746. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8747. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8748. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8749. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8750. &curl_slist_free_all};
  8751. ASSERT_NE(list, nullptr);
  8752. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8753. struct read_data {
  8754. size_t read_size;
  8755. size_t total_size;
  8756. } data = {0, total_size};
  8757. using read_callback_t =
  8758. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8759. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8760. void *userdata) -> size_t {
  8761. read_data *data = (read_data *)userdata;
  8762. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8763. std::fill_n(ptr, size * nmemb, 'A');
  8764. data->read_size += size * nmemb;
  8765. return size * nmemb;
  8766. };
  8767. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8768. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8769. std::vector<char> buffer;
  8770. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8771. using write_callback_t =
  8772. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8773. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8774. void *userdata) -> size_t {
  8775. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8776. buffer->reserve(buffer->size() + size * nmemb + 1);
  8777. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8778. return size * nmemb;
  8779. };
  8780. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8781. {
  8782. const auto res = curl_easy_perform(curl.get());
  8783. ASSERT_EQ(res, CURLE_OK);
  8784. }
  8785. {
  8786. auto response_code = long{};
  8787. const auto res =
  8788. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8789. ASSERT_EQ(res, CURLE_OK);
  8790. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8791. }
  8792. {
  8793. auto dl = curl_off_t{};
  8794. const auto res =
  8795. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8796. ASSERT_EQ(res, CURLE_OK);
  8797. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8798. }
  8799. {
  8800. buffer.push_back('\0');
  8801. ASSERT_STRCASEEQ(buffer.data(), reject);
  8802. }
  8803. }
  8804. }
  8805. #endif
  8806. template <typename S, typename C>
  8807. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8808. svr.Get("/stream", [&](const Request &, Response &res) {
  8809. auto data = new std::string("01234567890123456789");
  8810. res.set_content_provider(
  8811. data->size(), "text/plain",
  8812. [&, data](size_t offset, size_t length, DataSink &sink) {
  8813. const size_t DATA_CHUNK_SIZE = 4;
  8814. const auto &d = *data;
  8815. std::this_thread::sleep_for(std::chrono::seconds(1));
  8816. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8817. return true;
  8818. },
  8819. [data](bool success) {
  8820. EXPECT_FALSE(success);
  8821. delete data;
  8822. });
  8823. });
  8824. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8825. auto i = new size_t(0);
  8826. res.set_content_provider(
  8827. "text/plain",
  8828. [i](size_t, DataSink &sink) {
  8829. if (*i < 5) {
  8830. std::this_thread::sleep_for(std::chrono::seconds(1));
  8831. sink.write("abcd", 4);
  8832. (*i)++;
  8833. } else {
  8834. sink.done();
  8835. }
  8836. return true;
  8837. },
  8838. [i](bool success) {
  8839. EXPECT_FALSE(success);
  8840. delete i;
  8841. });
  8842. });
  8843. svr.Get("/chunked", [&](const Request &, Response &res) {
  8844. auto i = new size_t(0);
  8845. res.set_chunked_content_provider(
  8846. "text/plain",
  8847. [i](size_t, DataSink &sink) {
  8848. if (*i < 5) {
  8849. std::this_thread::sleep_for(std::chrono::seconds(1));
  8850. sink.os << "abcd";
  8851. (*i)++;
  8852. } else {
  8853. sink.done();
  8854. }
  8855. return true;
  8856. },
  8857. [i](bool success) {
  8858. EXPECT_FALSE(success);
  8859. delete i;
  8860. });
  8861. });
  8862. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8863. auto se = detail::scope_exit([&] {
  8864. svr.stop();
  8865. listen_thread.join();
  8866. ASSERT_FALSE(svr.is_running());
  8867. });
  8868. svr.wait_until_ready();
  8869. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8870. {
  8871. auto start = std::chrono::steady_clock::now();
  8872. auto res = cli.Get("/stream");
  8873. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8874. std::chrono::steady_clock::now() - start)
  8875. .count();
  8876. ASSERT_FALSE(res);
  8877. EXPECT_EQ(Error::Read, res.error());
  8878. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8879. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8880. }
  8881. {
  8882. auto start = std::chrono::steady_clock::now();
  8883. auto res = cli.Get("/stream_without_length");
  8884. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8885. std::chrono::steady_clock::now() - start)
  8886. .count();
  8887. ASSERT_FALSE(res);
  8888. EXPECT_EQ(Error::Read, res.error());
  8889. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8890. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8891. }
  8892. {
  8893. auto start = std::chrono::steady_clock::now();
  8894. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8895. EXPECT_EQ("abcd", string(data, data_length));
  8896. return true;
  8897. });
  8898. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8899. std::chrono::steady_clock::now() - start)
  8900. .count();
  8901. ASSERT_FALSE(res);
  8902. EXPECT_EQ(Error::Read, res.error());
  8903. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8904. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8905. }
  8906. }
  8907. TEST(MaxTimeoutTest, ContentStream) {
  8908. time_t timeout = 2000;
  8909. time_t threshold = 200;
  8910. Server svr;
  8911. Client cli("localhost", PORT);
  8912. max_timeout_test(svr, cli, timeout, threshold);
  8913. }
  8914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8915. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8916. time_t timeout = 2000;
  8917. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8919. SSLClient cli("localhost", PORT);
  8920. cli.enable_server_certificate_verification(false);
  8921. max_timeout_test(svr, cli, timeout, threshold);
  8922. }
  8923. #endif
  8924. class EventDispatcher {
  8925. public:
  8926. EventDispatcher() {}
  8927. void wait_event(DataSink *sink) {
  8928. unique_lock<mutex> lk(m_);
  8929. int id = id_;
  8930. cv_.wait(lk, [&] { return cid_ == id; });
  8931. sink->write(message_.data(), message_.size());
  8932. }
  8933. void send_event(const string &message) {
  8934. lock_guard<mutex> lk(m_);
  8935. cid_ = id_++;
  8936. message_ = message;
  8937. cv_.notify_all();
  8938. }
  8939. private:
  8940. mutex m_;
  8941. condition_variable cv_;
  8942. atomic_int id_{0};
  8943. atomic_int cid_{-1};
  8944. string message_;
  8945. };
  8946. TEST(ClientInThreadTest, Issue2068) {
  8947. EventDispatcher ed;
  8948. Server svr;
  8949. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8950. res.set_chunked_content_provider("text/event-stream",
  8951. [&](size_t /*offset*/, DataSink &sink) {
  8952. ed.wait_event(&sink);
  8953. return true;
  8954. });
  8955. });
  8956. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8957. svr.wait_until_ready();
  8958. thread event_thread([&] {
  8959. int id = 0;
  8960. while (svr.is_running()) {
  8961. this_thread::sleep_for(chrono::milliseconds(500));
  8962. std::stringstream ss;
  8963. ss << "data: " << id << "\n\n";
  8964. ed.send_event(ss.str());
  8965. id++;
  8966. }
  8967. });
  8968. auto se = detail::scope_exit([&] {
  8969. svr.stop();
  8970. listen_thread.join();
  8971. event_thread.join();
  8972. ASSERT_FALSE(svr.is_running());
  8973. });
  8974. {
  8975. auto client = detail::make_unique<Client>(HOST, PORT);
  8976. client->set_read_timeout(std::chrono::minutes(10));
  8977. std::atomic<bool> stop{false};
  8978. std::thread t([&] {
  8979. client->Get("/event1",
  8980. [&](const char *, size_t) -> bool { return !stop; });
  8981. });
  8982. std::this_thread::sleep_for(std::chrono::seconds(2));
  8983. stop = true;
  8984. client->stop();
  8985. client.reset();
  8986. t.join();
  8987. }
  8988. }
  8989. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8990. Server svr;
  8991. svr.Get("/", [](const Request &req, Response &res) {
  8992. EXPECT_EQ(2U, req.trailers.size());
  8993. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8994. // Denied
  8995. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8996. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8997. // Accepted
  8998. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8999. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9000. EXPECT_TRUE(req.has_trailer("X-World"));
  9001. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9002. res.set_content("ok", "text/plain");
  9003. });
  9004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9005. auto se = detail::scope_exit([&] {
  9006. svr.stop();
  9007. t.join();
  9008. ASSERT_FALSE(svr.is_running());
  9009. });
  9010. svr.wait_until_ready();
  9011. const std::string req = "GET / HTTP/1.1\r\n"
  9012. "Transfer-Encoding: chunked\r\n"
  9013. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9014. "\r\n"
  9015. "0\r\n"
  9016. "Content-Length: 10\r\n"
  9017. "Host: internal.local\r\n"
  9018. "Content-Type: malicious/content\r\n"
  9019. "Cookie: any\r\n"
  9020. "Set-Cookie: any\r\n"
  9021. "X-Forwarded-For: attacker.com\r\n"
  9022. "X-Real-Ip: 1.1.1.1\r\n"
  9023. "X-Hello: hello\r\n"
  9024. "X-World: world\r\n"
  9025. "\r\n";
  9026. std::string res;
  9027. ASSERT_TRUE(send_request(1, req, &res));
  9028. }