test.cc 314 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314
  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. #ifndef _WIN32
  147. TEST(SocketStream, wait_writable_UNIX) {
  148. int fds[2];
  149. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  150. const auto asSocketStream = [&](socket_t fd,
  151. std::function<bool(Stream &)> func) {
  152. return detail::process_client_socket(
  153. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  154. };
  155. asSocketStream(fds[0], [&](Stream &s0) {
  156. EXPECT_EQ(s0.socket(), fds[0]);
  157. EXPECT_TRUE(s0.wait_writable());
  158. EXPECT_EQ(0, close(fds[1]));
  159. EXPECT_FALSE(s0.wait_writable());
  160. return true;
  161. });
  162. EXPECT_EQ(0, close(fds[0]));
  163. }
  164. TEST(SocketStream, wait_writable_INET) {
  165. sockaddr_in addr;
  166. memset(&addr, 0, sizeof(addr));
  167. addr.sin_family = AF_INET;
  168. addr.sin_port = htons(PORT + 1);
  169. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  170. int disconnected_svr_sock = -1;
  171. std::thread svr{[&] {
  172. const int s = socket(AF_INET, SOCK_STREAM, 0);
  173. ASSERT_LE(0, s);
  174. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  175. ASSERT_EQ(0, listen(s, 1));
  176. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  177. ASSERT_EQ(0, close(s));
  178. }};
  179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  180. std::thread cli{[&] {
  181. const int s = socket(AF_INET, SOCK_STREAM, 0);
  182. ASSERT_LE(0, s);
  183. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  184. ASSERT_EQ(0, close(s));
  185. }};
  186. cli.join();
  187. svr.join();
  188. ASSERT_NE(disconnected_svr_sock, -1);
  189. const auto asSocketStream = [&](socket_t fd,
  190. std::function<bool(Stream &)> func) {
  191. return detail::process_client_socket(
  192. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  193. };
  194. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  195. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  196. EXPECT_FALSE(ss.wait_writable());
  197. return true;
  198. });
  199. ASSERT_EQ(0, close(disconnected_svr_sock));
  200. }
  201. #endif // #ifndef _WIN32
  202. TEST(ClientTest, MoveConstructible) {
  203. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  204. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  205. }
  206. TEST(ClientTest, MoveAssignable) {
  207. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  208. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  209. }
  210. #ifdef _WIN32
  211. TEST(StartupTest, WSAStartup) {
  212. WSADATA wsaData;
  213. int ret = WSAStartup(0x0002, &wsaData);
  214. ASSERT_EQ(0, ret);
  215. }
  216. #endif
  217. TEST(DecodePathTest, PercentCharacter) {
  218. EXPECT_EQ(
  219. detail::decode_path(
  220. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  221. false),
  222. u8"descrip=Gastos áéíóúñÑ 6");
  223. }
  224. TEST(DecodePathTest, PercentCharacterNUL) {
  225. string expected;
  226. expected.push_back('x');
  227. expected.push_back('\0');
  228. expected.push_back('x');
  229. EXPECT_EQ(detail::decode_path("x%00x", false), expected);
  230. }
  231. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  232. string unescapedCharacters = "-_.!~*'()";
  233. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  234. }
  235. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  236. string reservedCharacters = ";,/?:@&=+$";
  237. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  238. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  239. }
  240. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  241. string chineseCharacters = u8"中国語";
  242. string russianCharacters = u8"дом";
  243. string brazilianCharacters = u8"óculos";
  244. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  245. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  246. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  247. "%D0%B4%D0%BE%D0%BC");
  248. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  249. }
  250. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  251. string unescapedCharacters = "-_.!~*'()";
  252. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  253. }
  254. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  255. string reservedCharacters = ";,/?:@&=+$";
  256. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  257. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  258. }
  259. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  260. string chineseCharacters = u8"中国語";
  261. string russianCharacters = u8"дом";
  262. string brazilianCharacters = u8"óculos";
  263. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  264. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  265. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  266. "%D0%B4%D0%BE%D0%BC");
  267. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  268. }
  269. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  270. // Issue #2082 use case: encoding path component with ampersand
  271. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  272. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  273. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  274. }
  275. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  276. string unescapedCharacters = "-_.!~*'()";
  277. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  278. }
  279. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  280. string reservedCharacters = ";,/?:@&=+$#";
  281. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  282. }
  283. TEST(EncodeUriTest, TestUTF8Characters) {
  284. string chineseCharacters = u8"中国語";
  285. string russianCharacters = u8"дом";
  286. string brazilianCharacters = u8"óculos";
  287. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  288. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  289. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  290. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  291. }
  292. TEST(EncodeUriTest, TestCompleteUri) {
  293. string uri =
  294. "https://example.com/path/to/resource?query=value&param=test#fragment";
  295. EXPECT_EQ(
  296. httplib::encode_uri(uri),
  297. "https://example.com/path/to/resource?query=value&param=test#fragment");
  298. }
  299. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  300. string uri =
  301. "https://example.com/path with spaces/file name.html?q=hello world";
  302. EXPECT_EQ(httplib::encode_uri(uri),
  303. "https://example.com/path%20with%20spaces/"
  304. "file%20name.html?q=hello%20world");
  305. }
  306. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  307. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  308. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  309. }
  310. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  311. string unescapedCharacters = "-_.!~*'()";
  312. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  313. }
  314. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  315. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  316. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  317. string encodedBrazilian = "%C3%B3culos";
  318. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  319. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  320. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  321. }
  322. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  323. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  324. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  325. "Piri Tommy Villiers - on & on");
  326. }
  327. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  328. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  329. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  330. }
  331. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  333. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  334. }
  335. TEST(DecodeUriTest, TestUTF8Characters) {
  336. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  337. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  338. string encodedBrazilian = "%C3%B3culos";
  339. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  340. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  341. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  342. }
  343. TEST(DecodeUriTest, TestCompleteUri) {
  344. string encodedUri = "https://example.com/path%20with%20spaces/"
  345. "file%20name.html?q=hello%20world";
  346. EXPECT_EQ(
  347. httplib::decode_uri(encodedUri),
  348. "https://example.com/path with spaces/file name.html?q=hello world");
  349. }
  350. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  351. string original =
  352. "https://example.com/path with spaces/file name.html?q=hello world";
  353. string encoded = httplib::encode_uri(original);
  354. string decoded = httplib::decode_uri(encoded);
  355. EXPECT_EQ(decoded, original);
  356. }
  357. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  358. string original = "Piri Tommy Villiers - on & on";
  359. string encoded = httplib::encode_uri_component(original);
  360. string decoded = httplib::decode_uri_component(encoded);
  361. EXPECT_EQ(decoded, original);
  362. }
  363. TEST(TrimTests, TrimStringTests) {
  364. EXPECT_EQ("abc", detail::trim_copy("abc"));
  365. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  366. EXPECT_TRUE(detail::trim_copy("").empty());
  367. }
  368. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  369. // Simple case without quality values
  370. std::vector<std::string> result1;
  371. EXPECT_TRUE(detail::parse_accept_header(
  372. "text/html,application/json,text/plain", result1));
  373. EXPECT_EQ(result1.size(), 3U);
  374. EXPECT_EQ(result1[0], "text/html");
  375. EXPECT_EQ(result1[1], "application/json");
  376. EXPECT_EQ(result1[2], "text/plain");
  377. // With quality values
  378. std::vector<std::string> result2;
  379. EXPECT_TRUE(detail::parse_accept_header(
  380. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  381. EXPECT_EQ(result2.size(), 3U);
  382. EXPECT_EQ(result2[0], "application/json"); // highest q value
  383. EXPECT_EQ(result2[1], "text/html");
  384. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  385. }
  386. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  387. // Mixed with and without quality values
  388. std::vector<std::string> result;
  389. EXPECT_TRUE(detail::parse_accept_header(
  390. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  391. EXPECT_EQ(result.size(), 3U);
  392. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  393. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  394. EXPECT_EQ(result[2], "application/json"); // q=0.5
  395. }
  396. TEST(ParseAcceptHeaderTest, EdgeCases) {
  397. // Empty header
  398. std::vector<std::string> empty_result;
  399. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  400. EXPECT_TRUE(empty_result.empty());
  401. // Single type
  402. std::vector<std::string> single_result;
  403. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  404. EXPECT_EQ(single_result.size(), 1U);
  405. EXPECT_EQ(single_result[0], "application/json");
  406. // Wildcard types
  407. std::vector<std::string> wildcard_result;
  408. EXPECT_TRUE(detail::parse_accept_header(
  409. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  410. EXPECT_EQ(wildcard_result.size(), 3U);
  411. EXPECT_EQ(wildcard_result[0], "application/json");
  412. EXPECT_EQ(wildcard_result[1], "text/*");
  413. EXPECT_EQ(wildcard_result[2], "*/*");
  414. }
  415. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  416. // Common browser Accept header
  417. std::vector<std::string> browser_result;
  418. EXPECT_TRUE(
  419. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  420. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  421. browser_result));
  422. EXPECT_EQ(browser_result.size(), 6U);
  423. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  424. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  425. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  426. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  427. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  428. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  429. // API client header
  430. std::vector<std::string> api_result;
  431. EXPECT_TRUE(detail::parse_accept_header(
  432. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  433. api_result));
  434. EXPECT_EQ(api_result.size(), 3U);
  435. EXPECT_EQ(api_result[0], "application/json");
  436. EXPECT_EQ(api_result[1], "application/xml");
  437. EXPECT_EQ(api_result[2], "text/plain");
  438. }
  439. TEST(ParseAcceptHeaderTest, SpecialCases) {
  440. // Quality value with 3 decimal places
  441. std::vector<std::string> decimal_result;
  442. EXPECT_TRUE(detail::parse_accept_header(
  443. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  444. EXPECT_EQ(decimal_result.size(), 2U);
  445. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  446. EXPECT_EQ(decimal_result[1], "text/html");
  447. // Zero quality (should still be included but with lowest priority)
  448. std::vector<std::string> zero_q_result;
  449. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  450. zero_q_result));
  451. EXPECT_EQ(zero_q_result.size(), 2U);
  452. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  453. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  454. // No spaces around commas
  455. std::vector<std::string> no_space_result;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  458. no_space_result));
  459. EXPECT_EQ(no_space_result.size(), 3U);
  460. EXPECT_EQ(no_space_result[0], "text/html");
  461. EXPECT_EQ(no_space_result[1], "application/json");
  462. EXPECT_EQ(no_space_result[2], "text/plain");
  463. }
  464. TEST(ParseAcceptHeaderTest, InvalidCases) {
  465. std::vector<std::string> result;
  466. // Invalid quality value (> 1.0)
  467. EXPECT_FALSE(
  468. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  469. // Invalid quality value (< 0.0)
  470. EXPECT_FALSE(
  471. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  472. // Invalid quality value (not a number)
  473. EXPECT_FALSE(detail::parse_accept_header(
  474. "text/html;q=invalid,application/json", result));
  475. // Empty quality value
  476. EXPECT_FALSE(
  477. detail::parse_accept_header("text/html;q=,application/json", result));
  478. // Invalid media type format (no slash and not wildcard)
  479. EXPECT_FALSE(
  480. detail::parse_accept_header("invalidtype,application/json", result));
  481. // Empty media type
  482. result.clear();
  483. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  484. // Only commas
  485. result.clear();
  486. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  487. // Valid cases should still work
  488. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  489. EXPECT_EQ(result.size(), 1U);
  490. EXPECT_EQ(result[0], "*/*");
  491. EXPECT_TRUE(detail::parse_accept_header("*", result));
  492. EXPECT_EQ(result.size(), 1U);
  493. EXPECT_EQ(result[0], "*");
  494. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  495. EXPECT_EQ(result.size(), 1U);
  496. EXPECT_EQ(result[0], "text/*");
  497. }
  498. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  499. Server svr;
  500. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  501. EXPECT_EQ(req.accept_content_types.size(), 3U);
  502. EXPECT_EQ(req.accept_content_types[0], "application/json");
  503. EXPECT_EQ(req.accept_content_types[1], "text/html");
  504. EXPECT_EQ(req.accept_content_types[2], "*/*");
  505. res.set_content("ok", "text/plain");
  506. });
  507. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  508. EXPECT_TRUE(false);
  509. res.set_content("bad request", "text/plain");
  510. });
  511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  512. auto se = detail::scope_exit([&] {
  513. svr.stop();
  514. listen_thread.join();
  515. ASSERT_FALSE(svr.is_running());
  516. });
  517. svr.wait_until_ready();
  518. Client cli("localhost", PORT);
  519. {
  520. auto res =
  521. cli.Get("/accept_ok",
  522. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  523. ASSERT_TRUE(res);
  524. EXPECT_EQ(StatusCode::OK_200, res->status);
  525. }
  526. {
  527. auto res = cli.Get("/accept_bad_request",
  528. {{"Accept", "text/html;q=abc,application/json"}});
  529. ASSERT_TRUE(res);
  530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  531. }
  532. }
  533. TEST(DivideTest, DivideStringTests) {
  534. auto divide = [](const std::string &str, char d) {
  535. std::string lhs;
  536. std::string rhs;
  537. detail::divide(str, d,
  538. [&](const char *lhs_data, std::size_t lhs_size,
  539. const char *rhs_data, std::size_t rhs_size) {
  540. lhs.assign(lhs_data, lhs_size);
  541. rhs.assign(rhs_data, rhs_size);
  542. });
  543. return std::make_pair(std::move(lhs), std::move(rhs));
  544. };
  545. {
  546. const auto res = divide("", '=');
  547. EXPECT_EQ(res.first, "");
  548. EXPECT_EQ(res.second, "");
  549. }
  550. {
  551. const auto res = divide("=", '=');
  552. EXPECT_EQ(res.first, "");
  553. EXPECT_EQ(res.second, "");
  554. }
  555. {
  556. const auto res = divide(" ", '=');
  557. EXPECT_EQ(res.first, " ");
  558. EXPECT_EQ(res.second, "");
  559. }
  560. {
  561. const auto res = divide("a", '=');
  562. EXPECT_EQ(res.first, "a");
  563. EXPECT_EQ(res.second, "");
  564. }
  565. {
  566. const auto res = divide("a=", '=');
  567. EXPECT_EQ(res.first, "a");
  568. EXPECT_EQ(res.second, "");
  569. }
  570. {
  571. const auto res = divide("=b", '=');
  572. EXPECT_EQ(res.first, "");
  573. EXPECT_EQ(res.second, "b");
  574. }
  575. {
  576. const auto res = divide("a=b", '=');
  577. EXPECT_EQ(res.first, "a");
  578. EXPECT_EQ(res.second, "b");
  579. }
  580. {
  581. const auto res = divide("a=b=", '=');
  582. EXPECT_EQ(res.first, "a");
  583. EXPECT_EQ(res.second, "b=");
  584. }
  585. {
  586. const auto res = divide("a=b=c", '=');
  587. EXPECT_EQ(res.first, "a");
  588. EXPECT_EQ(res.second, "b=c");
  589. }
  590. }
  591. TEST(SplitTest, ParseQueryString) {
  592. string s = "key1=val1&key2=val2&key3=val3";
  593. Params dic;
  594. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  595. [&](const char *b, const char *e) {
  596. string key, val;
  597. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  598. if (key.empty()) {
  599. key.assign(b2, e2);
  600. } else {
  601. val.assign(b2, e2);
  602. }
  603. });
  604. dic.emplace(key, val);
  605. });
  606. EXPECT_EQ("val1", dic.find("key1")->second);
  607. EXPECT_EQ("val2", dic.find("key2")->second);
  608. EXPECT_EQ("val3", dic.find("key3")->second);
  609. }
  610. TEST(SplitTest, ParseInvalidQueryTests) {
  611. {
  612. string s = " ";
  613. Params dict;
  614. detail::parse_query_text(s, dict);
  615. EXPECT_TRUE(dict.empty());
  616. }
  617. {
  618. string s = " = =";
  619. Params dict;
  620. detail::parse_query_text(s, dict);
  621. EXPECT_TRUE(dict.empty());
  622. }
  623. }
  624. TEST(ParseQueryTest, ParseQueryString) {
  625. {
  626. std::string s = "key1=val1&key2=val2&key3=val3";
  627. Params dic;
  628. detail::parse_query_text(s, dic);
  629. EXPECT_EQ("val1", dic.find("key1")->second);
  630. EXPECT_EQ("val2", dic.find("key2")->second);
  631. EXPECT_EQ("val3", dic.find("key3")->second);
  632. }
  633. {
  634. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  635. Params dic;
  636. detail::parse_query_text(s, dic);
  637. EXPECT_EQ("", dic.find("key1")->second);
  638. EXPECT_EQ("val1", dic.find("key2")->second);
  639. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  640. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  641. }
  642. }
  643. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  644. Params dic;
  645. EXPECT_EQ(detail::params_to_query_str(dic), "");
  646. dic.emplace("key1", "val1");
  647. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  648. dic.emplace("key2", "val2");
  649. dic.emplace("key3", "val3");
  650. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  651. }
  652. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  653. string content_type = "multipart/form-data; boundary=something";
  654. string boundary;
  655. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  656. EXPECT_TRUE(ret);
  657. EXPECT_EQ(boundary, "something");
  658. }
  659. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  660. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  661. string boundary;
  662. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  665. }
  666. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  667. string content_type =
  668. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  669. string boundary;
  670. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  671. EXPECT_TRUE(ret);
  672. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  673. }
  674. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  675. string content_type =
  676. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  677. string boundary;
  678. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  679. EXPECT_TRUE(ret);
  680. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  681. }
  682. TEST(GetHeaderValueTest, DefaultValue) {
  683. Headers headers = {{"Dummy", "Dummy"}};
  684. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  685. EXPECT_STREQ("text/plain", val);
  686. }
  687. TEST(GetHeaderValueTest, DefaultValueInt) {
  688. Headers headers = {{"Dummy", "Dummy"}};
  689. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  690. EXPECT_EQ(100ull, val);
  691. }
  692. TEST(GetHeaderValueTest, RegularValue) {
  693. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  694. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  695. EXPECT_STREQ("text/html", val);
  696. }
  697. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  698. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  699. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  700. EXPECT_STREQ("text/html", val);
  701. }
  702. TEST(GetHeaderValueTest, SetContent) {
  703. Response res;
  704. res.set_content("html", "text/html");
  705. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  706. res.set_content("text", "text/plain");
  707. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  708. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  709. }
  710. TEST(GetHeaderValueTest, RegularValueInt) {
  711. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  712. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  713. EXPECT_EQ(100ull, val);
  714. }
  715. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  716. Headers headers = {{"Content-Length", "x"}};
  717. auto is_invalid_value = false;
  718. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  719. is_invalid_value);
  720. EXPECT_EQ(0ull, val);
  721. EXPECT_TRUE(is_invalid_value);
  722. }
  723. TEST(GetHeaderValueTest, Range) {
  724. {
  725. Headers headers = {make_range_header({{1, -1}})};
  726. auto val = detail::get_header_value(headers, "Range", 0, 0);
  727. EXPECT_STREQ("bytes=1-", val);
  728. }
  729. {
  730. Headers headers = {make_range_header({{-1, 1}})};
  731. auto val = detail::get_header_value(headers, "Range", 0, 0);
  732. EXPECT_STREQ("bytes=-1", val);
  733. }
  734. {
  735. Headers headers = {make_range_header({{1, 10}})};
  736. auto val = detail::get_header_value(headers, "Range", 0, 0);
  737. EXPECT_STREQ("bytes=1-10", val);
  738. }
  739. {
  740. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  741. auto val = detail::get_header_value(headers, "Range", 0, 0);
  742. EXPECT_STREQ("bytes=1-10, 100-", val);
  743. }
  744. {
  745. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  746. auto val = detail::get_header_value(headers, "Range", 0, 0);
  747. EXPECT_STREQ("bytes=1-10, 100-200", val);
  748. }
  749. {
  750. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  751. auto val = detail::get_header_value(headers, "Range", 0, 0);
  752. EXPECT_STREQ("bytes=0-0, -1", val);
  753. }
  754. }
  755. TEST(ParseHeaderValueTest, Range) {
  756. {
  757. Ranges ranges;
  758. auto ret = detail::parse_range_header("bytes=1-", ranges);
  759. EXPECT_TRUE(ret);
  760. EXPECT_EQ(1u, ranges.size());
  761. EXPECT_EQ(1u, ranges[0].first);
  762. EXPECT_EQ(-1, ranges[0].second);
  763. }
  764. {
  765. Ranges ranges;
  766. auto ret = detail::parse_range_header("bytes=-1", ranges);
  767. EXPECT_TRUE(ret);
  768. EXPECT_EQ(1u, ranges.size());
  769. EXPECT_EQ(-1, ranges[0].first);
  770. EXPECT_EQ(1u, ranges[0].second);
  771. }
  772. {
  773. Ranges ranges;
  774. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(1u, ranges.size());
  777. EXPECT_EQ(1u, ranges[0].first);
  778. EXPECT_EQ(10u, ranges[0].second);
  779. }
  780. {
  781. Ranges ranges;
  782. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  783. EXPECT_FALSE(ret);
  784. }
  785. {
  786. Ranges ranges;
  787. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(2u, ranges.size());
  790. EXPECT_EQ(1u, ranges[0].first);
  791. EXPECT_EQ(10u, ranges[0].second);
  792. EXPECT_EQ(100u, ranges[1].first);
  793. EXPECT_EQ(-1, ranges[1].second);
  794. }
  795. {
  796. Ranges ranges;
  797. auto ret =
  798. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(3u, ranges.size());
  801. EXPECT_EQ(1u, ranges[0].first);
  802. EXPECT_EQ(10u, ranges[0].second);
  803. EXPECT_EQ(100u, ranges[1].first);
  804. EXPECT_EQ(200u, ranges[1].second);
  805. EXPECT_EQ(300u, ranges[2].first);
  806. EXPECT_EQ(400u, ranges[2].second);
  807. }
  808. {
  809. Ranges ranges;
  810. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  811. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  812. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  813. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  814. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  815. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  816. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  817. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  818. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  819. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  820. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  821. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  822. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  823. EXPECT_TRUE(ranges.empty());
  824. }
  825. }
  826. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  827. Request req;
  828. req.set_header("Accept-Encoding", "gzip");
  829. Response res;
  830. res.set_header("Content-Type", "text/plain");
  831. auto ret = detail::encoding_type(req, res);
  832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  833. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  834. #else
  835. EXPECT_TRUE(ret == detail::EncodingType::None);
  836. #endif
  837. }
  838. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  839. Request req;
  840. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  841. Response res;
  842. res.set_header("Content-Type", "text/plain");
  843. auto ret = detail::encoding_type(req, res);
  844. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  845. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  846. #elif CPPHTTPLIB_ZLIB_SUPPORT
  847. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  848. #elif CPPHTTPLIB_ZSTD_SUPPORT
  849. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  850. #else
  851. EXPECT_TRUE(ret == detail::EncodingType::None);
  852. #endif
  853. }
  854. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  855. Request req;
  856. req.set_header("Accept-Encoding",
  857. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  858. Response res;
  859. res.set_header("Content-Type", "text/plain");
  860. auto ret = detail::encoding_type(req, res);
  861. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  862. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  863. #elif CPPHTTPLIB_ZLIB_SUPPORT
  864. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  865. #elif CPPHTTPLIB_ZSTD_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(BufferStreamTest, read) {
  872. detail::BufferStream strm1;
  873. Stream &strm = strm1;
  874. EXPECT_EQ(5, strm.write("hello"));
  875. char buf[512];
  876. EXPECT_EQ(2, strm.read(buf, 2));
  877. EXPECT_EQ('h', buf[0]);
  878. EXPECT_EQ('e', buf[1]);
  879. EXPECT_EQ(2, strm.read(buf, 2));
  880. EXPECT_EQ('l', buf[0]);
  881. EXPECT_EQ('l', buf[1]);
  882. EXPECT_EQ(1, strm.read(buf, 1));
  883. EXPECT_EQ('o', buf[0]);
  884. EXPECT_EQ(0, strm.read(buf, 1));
  885. }
  886. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  887. auto host = "www.httpwatch.com";
  888. auto ip = hosted_at(host);
  889. EXPECT_EQ("23.96.13.243", ip);
  890. std::vector<std::string> addrs;
  891. hosted_at(host, addrs);
  892. EXPECT_EQ(1u, addrs.size());
  893. }
  894. #if 0 // It depends on each test environment...
  895. TEST(HostnameToIPConversionTest, YouTube_Online) {
  896. auto host = "www.youtube.com";
  897. std::vector<std::string> addrs;
  898. hosted_at(host, addrs);
  899. EXPECT_EQ(20u, addrs.size());
  900. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  901. EXPECT_TRUE(it != addrs.end());
  902. }
  903. #endif
  904. class ChunkedEncodingTest : public ::testing::Test {
  905. protected:
  906. ChunkedEncodingTest()
  907. : cli_(HOST, PORT)
  908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  909. ,
  910. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  911. #endif
  912. {
  913. cli_.set_connection_timeout(2);
  914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  915. cli_.enable_server_certificate_verification(false);
  916. #endif
  917. }
  918. virtual void SetUp() {
  919. read_file("./image.jpg", image_data_);
  920. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  921. res.set_content("Hello World!", "text/plain");
  922. });
  923. svr_.Get(
  924. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  925. res.set_chunked_content_provider(
  926. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  927. size_t remaining = image_data_.size() - offset;
  928. if (remaining == 0) {
  929. sink.done();
  930. } else {
  931. constexpr size_t CHUNK_SIZE = 1024;
  932. size_t send_size = std::min(CHUNK_SIZE, remaining);
  933. sink.write(&image_data_[offset], send_size);
  934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  935. }
  936. return true;
  937. });
  938. });
  939. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  940. svr_.wait_until_ready();
  941. }
  942. virtual void TearDown() {
  943. svr_.stop();
  944. if (!request_threads_.empty()) {
  945. std::this_thread::sleep_for(std::chrono::seconds(1));
  946. for (auto &t : request_threads_) {
  947. t.join();
  948. }
  949. }
  950. t_.join();
  951. }
  952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  953. SSLClient cli_;
  954. SSLServer svr_;
  955. #else
  956. Client cli_;
  957. Server svr_;
  958. #endif
  959. thread t_;
  960. std::vector<thread> request_threads_;
  961. std::string image_data_;
  962. };
  963. TEST_F(ChunkedEncodingTest, NormalGet) {
  964. auto res = cli_.Get("/chunked");
  965. ASSERT_TRUE(res);
  966. std::string out;
  967. read_file("./image.jpg", out);
  968. EXPECT_EQ(StatusCode::OK_200, res->status);
  969. EXPECT_EQ(out, res->body);
  970. }
  971. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  972. std::string body;
  973. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  974. body.append(data, data_length);
  975. return true;
  976. });
  977. ASSERT_TRUE(res);
  978. std::string out;
  979. read_file("./image.jpg", out);
  980. EXPECT_EQ(StatusCode::OK_200, res->status);
  981. EXPECT_EQ(out, body);
  982. }
  983. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  984. std::string body;
  985. auto res = cli_.Get(
  986. "/chunked",
  987. [&](const Response &response) {
  988. EXPECT_EQ(StatusCode::OK_200, response.status);
  989. return true;
  990. },
  991. [&](const char *data, size_t data_length) {
  992. body.append(data, data_length);
  993. return true;
  994. });
  995. ASSERT_TRUE(res);
  996. std::string out;
  997. read_file("./image.jpg", out);
  998. EXPECT_EQ(StatusCode::OK_200, res->status);
  999. EXPECT_EQ(out, body);
  1000. }
  1001. TEST(RangeTest, FromHTTPBin_Online) {
  1002. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1003. auto host = "httpbin.org";
  1004. auto path = std::string{"/range/32"};
  1005. #else
  1006. auto host = "nghttp2.org";
  1007. auto path = std::string{"/httpbin/range/32"};
  1008. #endif
  1009. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1010. auto port = 443;
  1011. SSLClient cli(host, port);
  1012. #else
  1013. auto port = 80;
  1014. Client cli(host, port);
  1015. #endif
  1016. cli.set_connection_timeout(5);
  1017. {
  1018. auto res = cli.Get(path);
  1019. ASSERT_TRUE(res);
  1020. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1021. EXPECT_EQ(StatusCode::OK_200, res->status);
  1022. }
  1023. {
  1024. Headers headers = {make_range_header({{1, -1}})};
  1025. auto res = cli.Get(path, headers);
  1026. ASSERT_TRUE(res);
  1027. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1029. }
  1030. {
  1031. Headers headers = {make_range_header({{1, 10}})};
  1032. auto res = cli.Get(path, headers);
  1033. ASSERT_TRUE(res);
  1034. EXPECT_EQ("bcdefghijk", res->body);
  1035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1036. }
  1037. {
  1038. Headers headers = {make_range_header({{0, 31}})};
  1039. auto res = cli.Get(path, headers);
  1040. ASSERT_TRUE(res);
  1041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1042. EXPECT_EQ(StatusCode::OK_200, res->status);
  1043. }
  1044. {
  1045. Headers headers = {make_range_header({{0, -1}})};
  1046. auto res = cli.Get(path, headers);
  1047. ASSERT_TRUE(res);
  1048. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1049. EXPECT_EQ(StatusCode::OK_200, res->status);
  1050. }
  1051. {
  1052. Headers headers = {make_range_header({{0, 32}})};
  1053. auto res = cli.Get(path, headers);
  1054. ASSERT_TRUE(res);
  1055. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1056. }
  1057. }
  1058. TEST(ConnectionErrorTest, InvalidHost) {
  1059. auto host = "-abcde.com";
  1060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1061. auto port = 443;
  1062. SSLClient cli(host, port);
  1063. #else
  1064. auto port = 80;
  1065. Client cli(host, port);
  1066. #endif
  1067. cli.set_connection_timeout(std::chrono::seconds(2));
  1068. auto res = cli.Get("/");
  1069. ASSERT_TRUE(!res);
  1070. EXPECT_EQ(Error::Connection, res.error());
  1071. }
  1072. TEST(ConnectionErrorTest, InvalidHost2) {
  1073. auto host = "httpbin.org/";
  1074. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1075. SSLClient cli(host);
  1076. #else
  1077. Client cli(host);
  1078. #endif
  1079. cli.set_connection_timeout(std::chrono::seconds(2));
  1080. auto res = cli.Get("/");
  1081. ASSERT_TRUE(!res);
  1082. EXPECT_EQ(Error::Connection, res.error());
  1083. }
  1084. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1085. auto host = "httpbin.org/";
  1086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1087. SSLClient cli(host);
  1088. #else
  1089. Client cli(host);
  1090. #endif
  1091. cli.set_connection_timeout(std::chrono::seconds(2));
  1092. auto res = cli.Get("/");
  1093. ASSERT_TRUE(!res);
  1094. stringstream s;
  1095. s << "error code: " << res.error();
  1096. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1097. }
  1098. TEST(ConnectionErrorTest, InvalidPort) {
  1099. auto host = "localhost";
  1100. auto port = 44380;
  1101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1102. SSLClient cli(host, port);
  1103. #else
  1104. Client cli(host, port);
  1105. #endif
  1106. cli.set_connection_timeout(std::chrono::seconds(2));
  1107. auto res = cli.Get("/");
  1108. ASSERT_TRUE(!res);
  1109. EXPECT_TRUE(Error::Connection == res.error() ||
  1110. Error::ConnectionTimeout == res.error());
  1111. }
  1112. TEST(ConnectionErrorTest, Timeout_Online) {
  1113. auto host = "google.com";
  1114. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1115. auto port = 44380;
  1116. SSLClient cli(host, port);
  1117. #else
  1118. auto port = 8080;
  1119. Client cli(host, port);
  1120. #endif
  1121. cli.set_connection_timeout(std::chrono::seconds(2));
  1122. // only probe one address type so that the error reason
  1123. // correlates to the timed-out IPv4, not the unsupported
  1124. // IPv6 connection attempt
  1125. cli.set_address_family(AF_INET);
  1126. auto res = cli.Get("/");
  1127. ASSERT_TRUE(!res);
  1128. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1129. }
  1130. TEST(CancelTest, NoCancel_Online) {
  1131. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1132. auto host = "httpbin.org";
  1133. auto path = std::string{"/range/32"};
  1134. #else
  1135. auto host = "nghttp2.org";
  1136. auto path = std::string{"/httpbin/range/32"};
  1137. #endif
  1138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1139. auto port = 443;
  1140. SSLClient cli(host, port);
  1141. #else
  1142. auto port = 80;
  1143. Client cli(host, port);
  1144. #endif
  1145. cli.set_connection_timeout(std::chrono::seconds(5));
  1146. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1147. ASSERT_TRUE(res);
  1148. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1149. EXPECT_EQ(StatusCode::OK_200, res->status);
  1150. }
  1151. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1152. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1153. auto host = "httpbin.org";
  1154. auto path = std::string{"/range/32"};
  1155. #else
  1156. auto host = "nghttp2.org";
  1157. auto path = std::string{"/httpbin/range/32"};
  1158. #endif
  1159. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1160. auto port = 443;
  1161. SSLClient cli(host, port);
  1162. #else
  1163. auto port = 80;
  1164. Client cli(host, port);
  1165. #endif
  1166. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1167. cli.set_connection_timeout(std::chrono::seconds(5));
  1168. ASSERT_TRUE(!res);
  1169. EXPECT_EQ(Error::Canceled, res.error());
  1170. }
  1171. TEST(CancelTest, WithCancelLargePayload_Online) {
  1172. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1173. auto host = "httpbin.org";
  1174. auto path = std::string{"/range/65536"};
  1175. #else
  1176. auto host = "nghttp2.org";
  1177. auto path = std::string{"/httpbin/range/65536"};
  1178. #endif
  1179. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1180. auto port = 443;
  1181. SSLClient cli(host, port);
  1182. #else
  1183. auto port = 80;
  1184. Client cli(host, port);
  1185. #endif
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. uint32_t count = 0;
  1188. auto res =
  1189. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1190. ASSERT_TRUE(!res);
  1191. EXPECT_EQ(Error::Canceled, res.error());
  1192. }
  1193. TEST(CancelTest, NoCancelPost) {
  1194. Server svr;
  1195. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1196. res.set_content("Hello World!", "text/plain");
  1197. });
  1198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1199. auto se = detail::scope_exit([&] {
  1200. svr.stop();
  1201. thread.join();
  1202. ASSERT_FALSE(svr.is_running());
  1203. });
  1204. svr.wait_until_ready();
  1205. Client cli(HOST, PORT);
  1206. cli.set_connection_timeout(std::chrono::seconds(5));
  1207. auto res =
  1208. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1209. "application/json", [](uint64_t, uint64_t) { return true; });
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("Hello World!", res->body);
  1212. EXPECT_EQ(StatusCode::OK_200, res->status);
  1213. }
  1214. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1215. Server svr;
  1216. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1217. res.set_content("Hello World!", "text/plain");
  1218. });
  1219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1220. auto se = detail::scope_exit([&] {
  1221. svr.stop();
  1222. thread.join();
  1223. ASSERT_FALSE(svr.is_running());
  1224. });
  1225. svr.wait_until_ready();
  1226. Client cli(HOST, PORT);
  1227. cli.set_connection_timeout(std::chrono::seconds(5));
  1228. auto res =
  1229. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1230. "application/json", [](uint64_t, uint64_t) { return false; });
  1231. ASSERT_TRUE(!res);
  1232. EXPECT_EQ(Error::Canceled, res.error());
  1233. }
  1234. TEST(CancelTest, WithCancelLargePayloadPost) {
  1235. Server svr;
  1236. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1237. res.set_content(LARGE_DATA, "text/plain");
  1238. });
  1239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1240. auto se = detail::scope_exit([&] {
  1241. svr.stop();
  1242. thread.join();
  1243. ASSERT_FALSE(svr.is_running());
  1244. });
  1245. svr.wait_until_ready();
  1246. Client cli(HOST, PORT);
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res =
  1249. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1250. "application/json", [](uint64_t, uint64_t) { return false; });
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_EQ(Error::Canceled, res.error());
  1253. }
  1254. TEST(CancelTest, NoCancelPut) {
  1255. Server svr;
  1256. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1257. res.set_content("Hello World!", "text/plain");
  1258. });
  1259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1260. auto se = detail::scope_exit([&] {
  1261. svr.stop();
  1262. thread.join();
  1263. ASSERT_FALSE(svr.is_running());
  1264. });
  1265. svr.wait_until_ready();
  1266. Client cli(HOST, PORT);
  1267. cli.set_connection_timeout(std::chrono::seconds(5));
  1268. auto res =
  1269. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1270. "application/json", [](uint64_t, uint64_t) { return true; });
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ("Hello World!", res->body);
  1273. EXPECT_EQ(StatusCode::OK_200, res->status);
  1274. }
  1275. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1276. Server svr;
  1277. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1278. res.set_content("Hello World!", "text/plain");
  1279. });
  1280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1281. auto se = detail::scope_exit([&] {
  1282. svr.stop();
  1283. thread.join();
  1284. ASSERT_FALSE(svr.is_running());
  1285. });
  1286. svr.wait_until_ready();
  1287. Client cli(HOST, PORT);
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res =
  1290. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1291. "application/json", [](uint64_t, uint64_t) { return false; });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, WithCancelLargePayloadPut) {
  1296. Server svr;
  1297. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content(LARGE_DATA, "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return false; });
  1312. ASSERT_TRUE(!res);
  1313. EXPECT_EQ(Error::Canceled, res.error());
  1314. }
  1315. TEST(CancelTest, NoCancelPatch) {
  1316. Server svr;
  1317. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1318. res.set_content("Hello World!", "text/plain");
  1319. });
  1320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1321. auto se = detail::scope_exit([&] {
  1322. svr.stop();
  1323. thread.join();
  1324. ASSERT_FALSE(svr.is_running());
  1325. });
  1326. svr.wait_until_ready();
  1327. Client cli(HOST, PORT);
  1328. cli.set_connection_timeout(std::chrono::seconds(5));
  1329. auto res =
  1330. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1331. "application/json", [](uint64_t, uint64_t) { return true; });
  1332. ASSERT_TRUE(res);
  1333. EXPECT_EQ("Hello World!", res->body);
  1334. EXPECT_EQ(StatusCode::OK_200, res->status);
  1335. }
  1336. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1337. Server svr;
  1338. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1357. Server svr;
  1358. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content(LARGE_DATA, "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return false; });
  1373. ASSERT_TRUE(!res);
  1374. EXPECT_EQ(Error::Canceled, res.error());
  1375. }
  1376. TEST(CancelTest, NoCancelDelete) {
  1377. Server svr;
  1378. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1379. res.set_content("Hello World!", "text/plain");
  1380. });
  1381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. thread.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, PORT);
  1389. cli.set_connection_timeout(std::chrono::seconds(5));
  1390. auto res =
  1391. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1392. "application/json", [](uint64_t, uint64_t) { return true; });
  1393. ASSERT_TRUE(res);
  1394. EXPECT_EQ("Hello World!", res->body);
  1395. EXPECT_EQ(StatusCode::OK_200, res->status);
  1396. }
  1397. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1398. Server svr;
  1399. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content("Hello World!", "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1418. Server svr;
  1419. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content(LARGE_DATA, "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return false; });
  1434. ASSERT_TRUE(!res);
  1435. EXPECT_EQ(Error::Canceled, res.error());
  1436. }
  1437. static std::string remove_whitespace(const std::string &input) {
  1438. std::string output;
  1439. output.reserve(input.size());
  1440. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1441. [](unsigned char c) { return !std::isspace(c); });
  1442. return output;
  1443. }
  1444. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1445. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1446. auto host = "httpbin.org";
  1447. auto path = std::string{"/basic-auth/hello/world"};
  1448. #else
  1449. auto host = "nghttp2.org";
  1450. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1451. #endif
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. auto port = 443;
  1454. SSLClient cli(host, port);
  1455. #else
  1456. auto port = 80;
  1457. Client cli(host, port);
  1458. #endif
  1459. {
  1460. auto res = cli.Get(path);
  1461. ASSERT_TRUE(res);
  1462. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1463. }
  1464. {
  1465. auto res =
  1466. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1467. ASSERT_TRUE(res);
  1468. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1469. remove_whitespace(res->body));
  1470. EXPECT_EQ(StatusCode::OK_200, res->status);
  1471. }
  1472. {
  1473. cli.set_basic_auth("hello", "world");
  1474. auto res = cli.Get(path);
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1477. remove_whitespace(res->body));
  1478. EXPECT_EQ(StatusCode::OK_200, res->status);
  1479. }
  1480. {
  1481. cli.set_basic_auth("hello", "bad");
  1482. auto res = cli.Get(path);
  1483. ASSERT_TRUE(res);
  1484. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1485. }
  1486. {
  1487. cli.set_basic_auth("bad", "world");
  1488. auto res = cli.Get(path);
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1491. }
  1492. }
  1493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1494. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1495. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1496. auto host = "httpbin.org";
  1497. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1498. auto paths = std::vector<std::string>{
  1499. "/digest-auth/auth/hello/world/MD5",
  1500. "/digest-auth/auth/hello/world/SHA-256",
  1501. "/digest-auth/auth/hello/world/SHA-512",
  1502. "/digest-auth/auth-int/hello/world/MD5",
  1503. };
  1504. #else
  1505. auto host = "nghttp2.org";
  1506. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1507. auto paths = std::vector<std::string>{
  1508. "/httpbin/digest-auth/auth/hello/world/MD5",
  1509. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1510. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1511. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1512. };
  1513. #endif
  1514. auto port = 443;
  1515. SSLClient cli(host, port);
  1516. {
  1517. auto res = cli.Get(unauth_path);
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1520. }
  1521. {
  1522. cli.set_digest_auth("hello", "world");
  1523. for (const auto &path : paths) {
  1524. auto res = cli.Get(path.c_str());
  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. cli.set_digest_auth("hello", "bad");
  1531. for (const auto &path : paths) {
  1532. auto res = cli.Get(path.c_str());
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1535. }
  1536. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1537. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1538. // cli.set_digest_auth("bad", "world");
  1539. // for (const auto& path : paths) {
  1540. // auto res = cli.Get(path.c_str());
  1541. // ASSERT_TRUE(res);
  1542. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1543. // }
  1544. }
  1545. }
  1546. #endif
  1547. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1548. auto host = "google.com";
  1549. auto another_host = "example.com";
  1550. auto wrong_ip = "0.0.0.0";
  1551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1552. SSLClient cli(host);
  1553. #else
  1554. Client cli(host);
  1555. #endif
  1556. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1557. auto res = cli.Get("/");
  1558. ASSERT_TRUE(res);
  1559. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1560. }
  1561. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1562. auto host = "google.com";
  1563. auto wrong_ip = "0.0.0.0";
  1564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1565. SSLClient cli(host);
  1566. #else
  1567. Client cli(host);
  1568. #endif
  1569. cli.set_hostname_addr_map({{host, wrong_ip}});
  1570. auto res = cli.Get("/");
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Connection, res.error());
  1573. }
  1574. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1575. auto host = "nghttp2.org";
  1576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1577. SSLClient cli(host);
  1578. #else
  1579. Client cli(host);
  1580. #endif
  1581. cli.set_follow_location(true);
  1582. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1583. ASSERT_TRUE(res);
  1584. EXPECT_EQ(StatusCode::OK_200, res->status);
  1585. }
  1586. TEST(RedirectTest, Redirect_Online) {
  1587. auto host = "nghttp2.org";
  1588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1589. SSLClient cli(host);
  1590. #else
  1591. Client cli(host);
  1592. #endif
  1593. cli.set_follow_location(true);
  1594. auto res = cli.Get("/httpbin/redirect/3");
  1595. ASSERT_TRUE(res);
  1596. EXPECT_EQ(StatusCode::OK_200, res->status);
  1597. }
  1598. TEST(RelativeRedirectTest, Redirect_Online) {
  1599. auto host = "nghttp2.org";
  1600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1601. SSLClient cli(host);
  1602. #else
  1603. Client cli(host);
  1604. #endif
  1605. cli.set_follow_location(true);
  1606. auto res = cli.Get("/httpbin/relative-redirect/3");
  1607. ASSERT_TRUE(res);
  1608. EXPECT_EQ(StatusCode::OK_200, res->status);
  1609. }
  1610. TEST(TooManyRedirectTest, Redirect_Online) {
  1611. auto host = "nghttp2.org";
  1612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1613. SSLClient cli(host);
  1614. #else
  1615. Client cli(host);
  1616. #endif
  1617. cli.set_follow_location(true);
  1618. auto res = cli.Get("/httpbin/redirect/21");
  1619. ASSERT_TRUE(!res);
  1620. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1621. }
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. TEST(YahooRedirectTest, Redirect_Online) {
  1624. Client cli("yahoo.com");
  1625. auto res = cli.Get("/");
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1628. cli.set_follow_location(true);
  1629. res = cli.Get("/");
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ(StatusCode::OK_200, res->status);
  1632. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1633. }
  1634. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1635. #define REDIR_HOST "httpbingo.org"
  1636. #define REDIR_PATH "/redirect-to"
  1637. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1638. SSLClient cli(REDIR_HOST);
  1639. cli.set_follow_location(true);
  1640. auto res =
  1641. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1642. ASSERT_TRUE(res);
  1643. EXPECT_EQ(StatusCode::OK_200, res->status);
  1644. }
  1645. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1646. SSLClient cli(REDIR_HOST);
  1647. cli.set_follow_location(true);
  1648. Params params;
  1649. params.emplace("url", "http://example.com");
  1650. params.emplace("status_code", "302");
  1651. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::OK_200, res->status);
  1654. }
  1655. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1656. SSLClient cli(REDIR_HOST);
  1657. cli.set_follow_location(true);
  1658. Params params;
  1659. params.emplace("url", "http://example.com");
  1660. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ(StatusCode::OK_200, res->status);
  1663. }
  1664. TEST(UrlWithSpace, Redirect_Online) {
  1665. SSLClient cli("edge.forgecdn.net");
  1666. cli.set_follow_location(true);
  1667. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ(StatusCode::OK_200, res->status);
  1670. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1671. }
  1672. #endif
  1673. #if !defined(_WIN32) && !defined(_WIN64)
  1674. TEST(ReceiveSignals, Signal) {
  1675. auto setupSignalHandlers = []() {
  1676. struct sigaction act;
  1677. sigemptyset(&act.sa_mask);
  1678. act.sa_flags = SA_SIGINFO;
  1679. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1680. switch (sig) {
  1681. case SIGINT:
  1682. default: break;
  1683. }
  1684. };
  1685. ::sigaction(SIGINT, &act, nullptr);
  1686. };
  1687. Server svr;
  1688. int port = 0;
  1689. auto thread = std::thread([&]() {
  1690. setupSignalHandlers();
  1691. port = svr.bind_to_any_port("localhost");
  1692. svr.listen_after_bind();
  1693. });
  1694. auto se = detail::scope_exit([&] {
  1695. svr.stop();
  1696. thread.join();
  1697. ASSERT_FALSE(svr.is_running());
  1698. });
  1699. svr.wait_until_ready();
  1700. ASSERT_TRUE(svr.is_running());
  1701. pthread_kill(thread.native_handle(), SIGINT);
  1702. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1703. ASSERT_TRUE(svr.is_running());
  1704. }
  1705. #endif
  1706. TEST(RedirectToDifferentPort, Redirect) {
  1707. Server svr1;
  1708. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1709. res.set_content("Hello World!", "text/plain");
  1710. });
  1711. int svr1_port = 0;
  1712. auto thread1 = std::thread([&]() {
  1713. svr1_port = svr1.bind_to_any_port("localhost");
  1714. svr1.listen_after_bind();
  1715. });
  1716. Server svr2;
  1717. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1718. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1719. });
  1720. int svr2_port = 0;
  1721. auto thread2 = std::thread([&]() {
  1722. svr2_port = svr2.bind_to_any_port("localhost");
  1723. svr2.listen_after_bind();
  1724. });
  1725. auto se = detail::scope_exit([&] {
  1726. svr2.stop();
  1727. thread2.join();
  1728. svr1.stop();
  1729. thread1.join();
  1730. ASSERT_FALSE(svr2.is_running());
  1731. ASSERT_FALSE(svr1.is_running());
  1732. });
  1733. svr1.wait_until_ready();
  1734. svr2.wait_until_ready();
  1735. Client cli("localhost", svr2_port);
  1736. cli.set_follow_location(true);
  1737. auto res = cli.Get("/2");
  1738. ASSERT_TRUE(res);
  1739. EXPECT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_EQ("Hello World!", res->body);
  1741. }
  1742. TEST(RedirectFromPageWithContent, Redirect) {
  1743. Server svr;
  1744. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("___", "text/plain");
  1746. res.set_redirect("/2");
  1747. });
  1748. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1749. res.set_content("Hello World!", "text/plain");
  1750. });
  1751. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1752. auto se = detail::scope_exit([&] {
  1753. svr.stop();
  1754. th.join();
  1755. ASSERT_FALSE(svr.is_running());
  1756. });
  1757. svr.wait_until_ready();
  1758. {
  1759. Client cli("localhost", PORT);
  1760. cli.set_follow_location(true);
  1761. std::string body;
  1762. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1763. body.append(data, data_length);
  1764. return true;
  1765. });
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(StatusCode::OK_200, res->status);
  1768. EXPECT_EQ("Hello World!", body);
  1769. }
  1770. {
  1771. Client cli("localhost", PORT);
  1772. std::string body;
  1773. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1774. body.append(data, data_length);
  1775. return true;
  1776. });
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(StatusCode::Found_302, res->status);
  1779. EXPECT_EQ("___", body);
  1780. }
  1781. }
  1782. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1783. Server svr;
  1784. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1785. res.set_content("___", "text/plain");
  1786. // res.set_redirect("/2");
  1787. res.set_redirect("http://[::1]:1234/2");
  1788. });
  1789. svr.Get("/2", [&](const Request &req, Response &res) {
  1790. auto host_header = req.headers.find("Host");
  1791. ASSERT_TRUE(host_header != req.headers.end());
  1792. EXPECT_EQ("[::1]:1234", host_header->second);
  1793. res.set_content("Hello World!", "text/plain");
  1794. });
  1795. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. th.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1802. // actually starts anything, so the condition !svr.is_running() will
  1803. // always remain true, and the loop never stops.
  1804. // This basically counts how many milliseconds have passed since the
  1805. // call to svr.listen(), and if after 5 seconds nothing started yet
  1806. // aborts the test.
  1807. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1808. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1809. ASSERT_LT(milliseconds, 5000U);
  1810. }
  1811. {
  1812. Client cli("http://[::1]:1234");
  1813. cli.set_follow_location(true);
  1814. std::string body;
  1815. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1816. body.append(data, data_length);
  1817. return true;
  1818. });
  1819. ASSERT_TRUE(res);
  1820. EXPECT_EQ(StatusCode::OK_200, res->status);
  1821. EXPECT_EQ("Hello World!", body);
  1822. }
  1823. {
  1824. Client cli("http://[::1]:1234");
  1825. std::string body;
  1826. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1827. body.append(data, data_length);
  1828. return true;
  1829. });
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Found_302, res->status);
  1832. EXPECT_EQ("___", body);
  1833. }
  1834. }
  1835. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1836. Server svr;
  1837. svr.Get("/foo", [](const Request &req, Response &res) {
  1838. auto a = req.params.find("a");
  1839. if (a != req.params.end()) {
  1840. res.set_content((*a).second, "text/plain");
  1841. res.status = StatusCode::OK_200;
  1842. } else {
  1843. res.status = StatusCode::BadRequest_400;
  1844. }
  1845. });
  1846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1847. auto se = detail::scope_exit([&] {
  1848. svr.stop();
  1849. thread.join();
  1850. ASSERT_FALSE(svr.is_running());
  1851. });
  1852. svr.wait_until_ready();
  1853. {
  1854. Client cli(HOST, PORT);
  1855. cli.set_path_encode(false);
  1856. auto res = cli.Get("/foo?a=explicitly+encoded");
  1857. ASSERT_TRUE(res);
  1858. EXPECT_EQ(StatusCode::OK_200, res->status);
  1859. // This expects it back with a space, as the `+` won't have been
  1860. // url-encoded, and server-side the params get decoded turning `+`
  1861. // into spaces.
  1862. EXPECT_EQ("explicitly encoded", res->body);
  1863. }
  1864. }
  1865. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1866. Server svr;
  1867. svr.Get("/", [](const Request &req, Response &) {
  1868. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1869. });
  1870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1871. auto se = detail::scope_exit([&] {
  1872. svr.stop();
  1873. thread.join();
  1874. ASSERT_FALSE(svr.is_running());
  1875. });
  1876. svr.wait_until_ready();
  1877. {
  1878. Client cli(HOST, PORT);
  1879. cli.set_path_encode(false);
  1880. auto res = cli.Get("/?something=%0A");
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(StatusCode::OK_200, res->status);
  1883. }
  1884. }
  1885. TEST(BindServerTest, DISABLED_BindDualStack) {
  1886. Server svr;
  1887. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1888. res.set_content("Hello World!", "text/plain");
  1889. });
  1890. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1891. auto se = detail::scope_exit([&] {
  1892. svr.stop();
  1893. thread.join();
  1894. ASSERT_FALSE(svr.is_running());
  1895. });
  1896. svr.wait_until_ready();
  1897. {
  1898. Client cli("127.0.0.1", PORT);
  1899. auto res = cli.Get("/1");
  1900. ASSERT_TRUE(res);
  1901. EXPECT_EQ(StatusCode::OK_200, res->status);
  1902. EXPECT_EQ("Hello World!", res->body);
  1903. }
  1904. {
  1905. Client cli("::1", PORT);
  1906. auto res = cli.Get("/1");
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ("Hello World!", res->body);
  1910. }
  1911. }
  1912. TEST(BindServerTest, BindAndListenSeparately) {
  1913. Server svr;
  1914. int port = svr.bind_to_any_port("0.0.0.0");
  1915. ASSERT_TRUE(svr.is_valid());
  1916. ASSERT_TRUE(port > 0);
  1917. svr.stop();
  1918. }
  1919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1920. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1922. CLIENT_CA_CERT_DIR);
  1923. int port = svr.bind_to_any_port("0.0.0.0");
  1924. ASSERT_TRUE(svr.is_valid());
  1925. ASSERT_TRUE(port > 0);
  1926. svr.stop();
  1927. }
  1928. #endif
  1929. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1930. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1931. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1932. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1933. int port = svr.bind_to_any_port("0.0.0.0");
  1934. ASSERT_TRUE(svr.is_valid());
  1935. ASSERT_TRUE(port > 0);
  1936. svr.stop();
  1937. }
  1938. #endif
  1939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1940. X509 *readCertificate(const std::string &strFileName) {
  1941. std::ifstream inStream(strFileName);
  1942. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1943. std::istreambuf_iterator<char>());
  1944. if (strCertPEM.empty()) return (nullptr);
  1945. BIO *pbCert = BIO_new(BIO_s_mem());
  1946. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1947. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1948. BIO_free(pbCert);
  1949. return (pCert);
  1950. }
  1951. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1952. std::ifstream inStream(strFileName);
  1953. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1954. std::istreambuf_iterator<char>());
  1955. if (strPrivateKeyPEM.empty()) return (nullptr);
  1956. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1957. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1958. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1959. BIO_free(pbPrivKey);
  1960. return (pPrivateKey);
  1961. }
  1962. TEST(BindServerTest, UpdateCerts) {
  1963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1964. int port = svr.bind_to_any_port("0.0.0.0");
  1965. ASSERT_TRUE(svr.is_valid());
  1966. ASSERT_TRUE(port > 0);
  1967. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1968. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1969. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1970. ASSERT_TRUE(cert != nullptr);
  1971. ASSERT_TRUE(ca_cert != nullptr);
  1972. ASSERT_TRUE(key != nullptr);
  1973. X509_STORE *cert_store = X509_STORE_new();
  1974. X509_STORE_add_cert(cert_store, ca_cert);
  1975. svr.update_certs(cert, key, cert_store);
  1976. ASSERT_TRUE(svr.is_valid());
  1977. svr.stop();
  1978. X509_free(cert);
  1979. X509_free(ca_cert);
  1980. EVP_PKEY_free(key);
  1981. }
  1982. #endif
  1983. TEST(ErrorHandlerTest, ContentLength) {
  1984. Server svr;
  1985. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1986. res.status = StatusCode::OK_200;
  1987. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1988. "text/html"); // <= Content-Length still 13
  1989. });
  1990. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1991. res.set_content("Hello World!\n", "text/plain");
  1992. res.status = 524;
  1993. });
  1994. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1995. auto se = detail::scope_exit([&] {
  1996. svr.stop();
  1997. thread.join();
  1998. ASSERT_FALSE(svr.is_running());
  1999. });
  2000. svr.wait_until_ready();
  2001. {
  2002. Client cli(HOST, PORT);
  2003. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2004. ASSERT_TRUE(res);
  2005. EXPECT_EQ(StatusCode::OK_200, res->status);
  2006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2007. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2008. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2009. }
  2010. }
  2011. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2012. TEST(ExceptionTest, WithoutExceptionHandler) {
  2013. Server svr;
  2014. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2015. throw std::runtime_error("exception...");
  2016. });
  2017. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2018. throw std::runtime_error("exception\r\n...");
  2019. });
  2020. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. listen_thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. Client cli("localhost", PORT);
  2028. {
  2029. auto res = cli.Get("/exception");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2032. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2033. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2034. }
  2035. {
  2036. auto res = cli.Get("/unknown");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2039. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2040. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2041. }
  2042. }
  2043. TEST(ExceptionTest, WithExceptionHandler) {
  2044. Server svr;
  2045. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2046. std::exception_ptr ep) {
  2047. EXPECT_FALSE(ep == nullptr);
  2048. try {
  2049. std::rethrow_exception(ep);
  2050. } catch (std::exception &e) {
  2051. EXPECT_EQ("abc", std::string(e.what()));
  2052. } catch (...) {}
  2053. res.status = StatusCode::InternalServerError_500;
  2054. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2055. "text/html"); // <= Content-Length still 13 at this point
  2056. });
  2057. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2058. res.set_content("Hello World!\n", "text/plain");
  2059. throw std::runtime_error("abc");
  2060. });
  2061. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2062. auto se = detail::scope_exit([&] {
  2063. svr.stop();
  2064. thread.join();
  2065. ASSERT_FALSE(svr.is_running());
  2066. });
  2067. svr.wait_until_ready();
  2068. for (size_t i = 0; i < 10; i++) {
  2069. Client cli(HOST, PORT);
  2070. for (size_t j = 0; j < 100; j++) {
  2071. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2072. ASSERT_TRUE(res);
  2073. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2074. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2075. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2076. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2077. }
  2078. cli.set_keep_alive(true);
  2079. for (size_t j = 0; j < 100; j++) {
  2080. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2083. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2084. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2085. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2086. }
  2087. }
  2088. }
  2089. TEST(ExceptionTest, AndErrorHandler) {
  2090. Server svr;
  2091. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2092. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2093. });
  2094. svr.set_exception_handler(
  2095. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2096. EXPECT_FALSE(ep == nullptr);
  2097. try {
  2098. std::rethrow_exception(ep);
  2099. } catch (std::exception &e) {
  2100. res.set_content(e.what(), "text/html");
  2101. } catch (...) {}
  2102. res.status = StatusCode::InternalServerError_500;
  2103. });
  2104. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2105. throw std::runtime_error("EXCEPTION");
  2106. });
  2107. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2108. res.set_content("ERROR", "text/html");
  2109. res.status = StatusCode::InternalServerError_500;
  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. Client cli(HOST, PORT);
  2119. {
  2120. auto res = cli.Get("/exception");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2123. EXPECT_EQ("EXCEPTION", res->body);
  2124. }
  2125. {
  2126. auto res = cli.Get("/error");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2129. EXPECT_EQ("ERROR", res->body);
  2130. }
  2131. {
  2132. auto res = cli.Get("/invalid");
  2133. ASSERT_TRUE(res);
  2134. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2135. EXPECT_EQ("NOT_FOUND", res->body);
  2136. }
  2137. }
  2138. #endif
  2139. TEST(NoContentTest, ContentLength) {
  2140. Server svr;
  2141. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2142. res.status = StatusCode::NoContent_204;
  2143. });
  2144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2145. auto se = detail::scope_exit([&] {
  2146. svr.stop();
  2147. thread.join();
  2148. ASSERT_FALSE(svr.is_running());
  2149. });
  2150. svr.wait_until_ready();
  2151. {
  2152. Client cli(HOST, PORT);
  2153. auto res = cli.Get("/hi");
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2157. }
  2158. }
  2159. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2162. ASSERT_TRUE(svr.is_valid());
  2163. #else
  2164. Server svr;
  2165. #endif
  2166. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2167. if (req.path == "/routing_handler") {
  2168. res.set_header("PRE_ROUTING", "on");
  2169. res.set_content("Routing Handler", "text/plain");
  2170. return httplib::Server::HandlerResponse::Handled;
  2171. }
  2172. return httplib::Server::HandlerResponse::Unhandled;
  2173. });
  2174. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2175. res.set_content("Error", "text/html");
  2176. });
  2177. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2178. if (req.path == "/routing_handler") {
  2179. res.set_header("POST_ROUTING", "on");
  2180. }
  2181. });
  2182. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2183. res.set_content("Hello World!\n", "text/plain");
  2184. });
  2185. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2186. auto se = detail::scope_exit([&] {
  2187. svr.stop();
  2188. thread.join();
  2189. ASSERT_FALSE(svr.is_running());
  2190. });
  2191. svr.wait_until_ready();
  2192. {
  2193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2194. SSLClient cli(HOST, PORT);
  2195. cli.enable_server_certificate_verification(false);
  2196. #else
  2197. Client cli(HOST, PORT);
  2198. #endif
  2199. auto res = cli.Get("/routing_handler");
  2200. ASSERT_TRUE(res);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ("Routing Handler", res->body);
  2203. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2204. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2205. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2206. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2207. }
  2208. {
  2209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2210. SSLClient cli(HOST, PORT);
  2211. cli.enable_server_certificate_verification(false);
  2212. #else
  2213. Client cli(HOST, PORT);
  2214. #endif
  2215. auto res = cli.Get("/hi");
  2216. ASSERT_TRUE(res);
  2217. EXPECT_EQ(StatusCode::OK_200, res->status);
  2218. EXPECT_EQ("Hello World!\n", res->body);
  2219. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2220. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2221. }
  2222. {
  2223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2224. SSLClient cli(HOST, PORT);
  2225. cli.enable_server_certificate_verification(false);
  2226. #else
  2227. Client cli(HOST, PORT);
  2228. #endif
  2229. auto res = cli.Get("/aaa");
  2230. ASSERT_TRUE(res);
  2231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2232. EXPECT_EQ("Error", res->body);
  2233. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2234. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2235. }
  2236. }
  2237. TEST(RequestHandlerTest, PreRequestHandler) {
  2238. auto route_path = "/user/:user";
  2239. Server svr;
  2240. svr.Get("/hi", [](const Request &, Response &res) {
  2241. res.set_content("hi", "text/plain");
  2242. });
  2243. svr.Get(route_path, [](const Request &req, Response &res) {
  2244. res.set_content(req.path_params.at("user"), "text/plain");
  2245. });
  2246. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2247. if (req.matched_route == route_path) {
  2248. auto user = req.path_params.at("user");
  2249. if (user != "john") {
  2250. res.status = StatusCode::Forbidden_403;
  2251. res.set_content("error", "text/html");
  2252. return Server::HandlerResponse::Handled;
  2253. }
  2254. }
  2255. return Server::HandlerResponse::Unhandled;
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. {
  2266. auto res = cli.Get("/hi");
  2267. ASSERT_TRUE(res);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ("hi", res->body);
  2270. }
  2271. {
  2272. auto res = cli.Get("/user/john");
  2273. ASSERT_TRUE(res);
  2274. EXPECT_EQ(StatusCode::OK_200, res->status);
  2275. EXPECT_EQ("john", res->body);
  2276. }
  2277. {
  2278. auto res = cli.Get("/user/invalid-user");
  2279. ASSERT_TRUE(res);
  2280. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2281. EXPECT_EQ("error", res->body);
  2282. }
  2283. }
  2284. TEST(InvalidFormatTest, StatusCode) {
  2285. Server svr;
  2286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2287. res.set_content("Hello World!\n", "text/plain");
  2288. res.status = 9999; // Status should be a three-digit code...
  2289. });
  2290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2291. auto se = detail::scope_exit([&] {
  2292. svr.stop();
  2293. thread.join();
  2294. ASSERT_FALSE(svr.is_running());
  2295. });
  2296. svr.wait_until_ready();
  2297. {
  2298. Client cli(HOST, PORT);
  2299. auto res = cli.Get("/hi");
  2300. ASSERT_FALSE(res);
  2301. }
  2302. }
  2303. TEST(URLFragmentTest, WithFragment) {
  2304. Server svr;
  2305. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2306. EXPECT_TRUE(req.target == "/hi");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. {
  2316. Client cli(HOST, PORT);
  2317. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2318. EXPECT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. res = cli.Get("/hi%23key1=val1=key2=val2");
  2321. EXPECT_TRUE(res);
  2322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2323. }
  2324. }
  2325. TEST(HeaderWriter, SetHeaderWriter) {
  2326. Server svr;
  2327. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2328. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2329. return detail::write_headers(strm, hdrs);
  2330. });
  2331. svr.Get("/hi", [](const Request &req, Response &res) {
  2332. auto it = req.headers.find("CustomClientHeader");
  2333. EXPECT_TRUE(it != req.headers.end());
  2334. EXPECT_EQ(it->second, "CustomClientValue");
  2335. res.set_content("Hello World!\n", "text/plain");
  2336. });
  2337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. thread.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. {
  2345. Client cli(HOST, PORT);
  2346. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2347. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2348. return detail::write_headers(strm, hdrs);
  2349. });
  2350. auto res = cli.Get("/hi");
  2351. EXPECT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. auto it = res->headers.find("CustomServerHeader");
  2354. EXPECT_TRUE(it != res->headers.end());
  2355. EXPECT_EQ(it->second, "CustomServerValue");
  2356. }
  2357. }
  2358. class ServerTest : public ::testing::Test {
  2359. protected:
  2360. ServerTest()
  2361. : cli_(HOST, PORT)
  2362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2363. ,
  2364. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2365. #endif
  2366. {
  2367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2368. cli_.enable_server_certificate_verification(false);
  2369. #endif
  2370. }
  2371. virtual void SetUp() {
  2372. svr_.set_mount_point("/", "./www");
  2373. svr_.set_mount_point("/mount", "./www2");
  2374. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2375. svr_.Get("/hi",
  2376. [&](const Request & /*req*/, Response &res) {
  2377. res.set_content("Hello World!", "text/plain");
  2378. })
  2379. .Get("/file_content",
  2380. [&](const Request & /*req*/, Response &res) {
  2381. res.set_file_content("./www/dir/test.html");
  2382. })
  2383. .Get("/file_content_with_content_type",
  2384. [&](const Request & /*req*/, Response &res) {
  2385. res.set_file_content("./www/file", "text/plain");
  2386. })
  2387. .Get("/invalid_file_content",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. res.set_file_content("./www/dir/invalid_file_path");
  2390. })
  2391. .Get("/http_response_splitting",
  2392. [&](const Request & /*req*/, Response &res) {
  2393. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2394. EXPECT_EQ(0U, res.headers.size());
  2395. EXPECT_FALSE(res.has_header("a"));
  2396. res.set_header("a", "1\nSet-Cookie: a=1");
  2397. EXPECT_EQ(0U, res.headers.size());
  2398. EXPECT_FALSE(res.has_header("a"));
  2399. res.set_header("a", "1\rSet-Cookie: a=1");
  2400. EXPECT_EQ(0U, res.headers.size());
  2401. EXPECT_FALSE(res.has_header("a"));
  2402. res.set_header("a\r\nb", "0");
  2403. EXPECT_EQ(0U, res.headers.size());
  2404. EXPECT_FALSE(res.has_header("a"));
  2405. res.set_header("a\rb", "0");
  2406. EXPECT_EQ(0U, res.headers.size());
  2407. EXPECT_FALSE(res.has_header("a"));
  2408. res.set_header("a\nb", "0");
  2409. EXPECT_EQ(0U, res.headers.size());
  2410. EXPECT_FALSE(res.has_header("a"));
  2411. res.set_redirect("1\r\nSet-Cookie: a=1");
  2412. EXPECT_EQ(0U, res.headers.size());
  2413. EXPECT_FALSE(res.has_header("Location"));
  2414. })
  2415. .Get("/slow",
  2416. [&](const Request & /*req*/, Response &res) {
  2417. std::this_thread::sleep_for(std::chrono::seconds(2));
  2418. res.set_content("slow", "text/plain");
  2419. })
  2420. #if 0
  2421. .Post("/slowpost",
  2422. [&](const Request & /*req*/, Response &res) {
  2423. std::this_thread::sleep_for(std::chrono::seconds(2));
  2424. res.set_content("slow", "text/plain");
  2425. })
  2426. #endif
  2427. .Get("/remote_addr",
  2428. [&](const Request &req, Response &res) {
  2429. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2430. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2431. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2432. EXPECT_EQ(req.remote_port,
  2433. std::stoi(req.get_header_value("REMOTE_PORT")));
  2434. res.set_content(remote_addr.c_str(), "text/plain");
  2435. })
  2436. .Get("/local_addr",
  2437. [&](const Request &req, Response &res) {
  2438. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2439. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2440. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2441. auto local_port = req.get_header_value("LOCAL_PORT");
  2442. EXPECT_EQ(req.local_addr, local_addr);
  2443. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2444. res.set_content(local_addr.append(":").append(local_port),
  2445. "text/plain");
  2446. })
  2447. .Get("/endwith%",
  2448. [&](const Request & /*req*/, Response &res) {
  2449. res.set_content("Hello World!", "text/plain");
  2450. })
  2451. .Get("/a\\+\\+b",
  2452. [&](const Request &req, Response &res) {
  2453. ASSERT_TRUE(req.has_param("a +b"));
  2454. auto val = req.get_param_value("a +b");
  2455. res.set_content(val, "text/plain");
  2456. })
  2457. .Get("/", [&](const Request & /*req*/,
  2458. Response &res) { res.set_redirect("/hi"); })
  2459. .Post("/1",
  2460. [](const Request & /*req*/, Response &res) {
  2461. res.set_redirect("/2", StatusCode::SeeOther_303);
  2462. })
  2463. .Get("/2",
  2464. [](const Request & /*req*/, Response &res) {
  2465. res.set_content("redirected.", "text/plain");
  2466. res.status = StatusCode::OK_200;
  2467. })
  2468. .Post("/person",
  2469. [&](const Request &req, Response &res) {
  2470. if (req.has_param("name") && req.has_param("note")) {
  2471. persons_[req.get_param_value("name")] =
  2472. req.get_param_value("note");
  2473. } else {
  2474. res.status = StatusCode::BadRequest_400;
  2475. }
  2476. })
  2477. .Put("/person",
  2478. [&](const Request &req, Response &res) {
  2479. if (req.has_param("name") && req.has_param("note")) {
  2480. persons_[req.get_param_value("name")] =
  2481. req.get_param_value("note");
  2482. } else {
  2483. res.status = StatusCode::BadRequest_400;
  2484. }
  2485. })
  2486. .Get("/person/(.*)",
  2487. [&](const Request &req, Response &res) {
  2488. string name = req.matches[1];
  2489. if (persons_.find(name) != persons_.end()) {
  2490. auto note = persons_[name];
  2491. res.set_content(note, "text/plain");
  2492. } else {
  2493. res.status = StatusCode::NotFound_404;
  2494. }
  2495. })
  2496. .Delete("/person",
  2497. [&](const Request &req, Response &res) {
  2498. if (req.has_param("name")) {
  2499. string name = req.get_param_value("name");
  2500. if (persons_.find(name) != persons_.end()) {
  2501. persons_.erase(name);
  2502. res.set_content("DELETED", "text/plain");
  2503. } else {
  2504. res.status = StatusCode::NotFound_404;
  2505. }
  2506. } else {
  2507. res.status = StatusCode::BadRequest_400;
  2508. }
  2509. })
  2510. .Post("/x-www-form-urlencoded-json",
  2511. [&](const Request &req, Response &res) {
  2512. auto json = req.get_param_value("json");
  2513. ASSERT_EQ(JSON_DATA, json);
  2514. res.set_content(json, "appliation/json");
  2515. res.status = StatusCode::OK_200;
  2516. })
  2517. .Get("/streamed-chunked",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_chunked_content_provider(
  2520. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2521. sink.os << "123";
  2522. sink.os << "456";
  2523. sink.os << "789";
  2524. sink.done();
  2525. return true;
  2526. });
  2527. })
  2528. .Get("/streamed-chunked2",
  2529. [&](const Request & /*req*/, Response &res) {
  2530. auto i = new int(0);
  2531. res.set_chunked_content_provider(
  2532. "text/plain",
  2533. [i](size_t /*offset*/, DataSink &sink) {
  2534. switch (*i) {
  2535. case 0: sink.os << "123"; break;
  2536. case 1: sink.os << "456"; break;
  2537. case 2: sink.os << "789"; break;
  2538. case 3: sink.done(); break;
  2539. }
  2540. (*i)++;
  2541. return true;
  2542. },
  2543. [i](bool success) {
  2544. EXPECT_TRUE(success);
  2545. delete i;
  2546. });
  2547. })
  2548. .Get("/streamed-chunked-with-trailer",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. auto i = new int(0);
  2551. res.set_header("Trailer", "Dummy1, Dummy2");
  2552. res.set_chunked_content_provider(
  2553. "text/plain",
  2554. [i](size_t /*offset*/, DataSink &sink) {
  2555. switch (*i) {
  2556. case 0: sink.os << "123"; break;
  2557. case 1: sink.os << "456"; break;
  2558. case 2: sink.os << "789"; break;
  2559. case 3: {
  2560. sink.done_with_trailer(
  2561. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2562. } break;
  2563. }
  2564. (*i)++;
  2565. return true;
  2566. },
  2567. [i](bool success) {
  2568. EXPECT_TRUE(success);
  2569. delete i;
  2570. });
  2571. })
  2572. .Get("/streamed",
  2573. [&](const Request & /*req*/, Response &res) {
  2574. res.set_content_provider(
  2575. 6, "text/plain",
  2576. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2577. sink.os << (offset < 3 ? "a" : "b");
  2578. return true;
  2579. });
  2580. })
  2581. .Get("/streamed-with-range",
  2582. [&](const Request &req, Response &res) {
  2583. auto data = new std::string("abcdefg");
  2584. res.set_content_provider(
  2585. data->size(), "text/plain",
  2586. [data](size_t offset, size_t length, DataSink &sink) {
  2587. size_t DATA_CHUNK_SIZE = 4;
  2588. const auto &d = *data;
  2589. auto out_len =
  2590. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2591. auto ret =
  2592. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2593. EXPECT_TRUE(ret);
  2594. return true;
  2595. },
  2596. [data, &req](bool success) {
  2597. EXPECT_EQ(success, !req.has_param("error"));
  2598. delete data;
  2599. });
  2600. })
  2601. .Get("/streamed-cancel",
  2602. [&](const Request & /*req*/, Response &res) {
  2603. res.set_content_provider(
  2604. size_t(-1), "text/plain",
  2605. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2606. sink.os << "data_chunk";
  2607. return true;
  2608. });
  2609. })
  2610. .Get("/regex-with-delimiter",
  2611. [&](const Request &req, Response & /*res*/) {
  2612. ASSERT_TRUE(req.has_param("key"));
  2613. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2614. })
  2615. .Get("/with-range",
  2616. [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("abcdefg", "text/plain");
  2618. })
  2619. .Get("/with-range-customized-response",
  2620. [&](const Request & /*req*/, Response &res) {
  2621. res.status = StatusCode::BadRequest_400;
  2622. res.set_content(JSON_DATA, "application/json");
  2623. })
  2624. .Post("/chunked",
  2625. [&](const Request &req, Response & /*res*/) {
  2626. EXPECT_EQ(req.body, "dechunked post body");
  2627. })
  2628. .Post("/large-chunked",
  2629. [&](const Request &req, Response & /*res*/) {
  2630. std::string expected(6 * 30 * 1024u, 'a');
  2631. EXPECT_EQ(req.body, expected);
  2632. })
  2633. .Post("/multipart",
  2634. [&](const Request &req, Response & /*res*/) {
  2635. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2636. req.form.get_field_count("text2") +
  2637. req.form.get_field_count("file3") +
  2638. req.form.get_field_count("file4"));
  2639. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2640. req.form.get_file_count("file2"));
  2641. ASSERT_TRUE(!req.form.has_file("???"));
  2642. ASSERT_TRUE(!req.form.has_field("???"));
  2643. ASSERT_TRUE(req.body.empty());
  2644. {
  2645. const auto &text = req.form.get_field("text1");
  2646. EXPECT_EQ("text default", text);
  2647. }
  2648. {
  2649. const auto &text = req.form.get_field("text2");
  2650. EXPECT_EQ("aωb", text);
  2651. }
  2652. {
  2653. const auto &file = req.form.get_file("file1");
  2654. EXPECT_EQ("hello.txt", file.filename);
  2655. EXPECT_EQ("text/plain", file.content_type);
  2656. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2657. }
  2658. {
  2659. const auto &file = req.form.get_file("file2");
  2660. EXPECT_EQ("world.json", file.filename);
  2661. EXPECT_EQ("application/json", file.content_type);
  2662. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2663. }
  2664. {
  2665. const auto &text = req.form.get_field("file3");
  2666. EXPECT_EQ(0u, text.size());
  2667. }
  2668. {
  2669. const auto &text = req.form.get_field("file4");
  2670. EXPECT_EQ(0u, text.size());
  2671. }
  2672. })
  2673. .Post("/multipart/multi_file_values",
  2674. [&](const Request &req, Response & /*res*/) {
  2675. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2676. req.form.get_field_count("multi_text1"));
  2677. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2678. ASSERT_TRUE(!req.form.has_file("???"));
  2679. ASSERT_TRUE(!req.form.has_field("???"));
  2680. ASSERT_TRUE(req.body.empty());
  2681. {
  2682. const auto &text = req.form.get_field("text");
  2683. EXPECT_EQ("default text", text);
  2684. }
  2685. {
  2686. const auto &text1_values = req.form.get_fields("multi_text1");
  2687. EXPECT_EQ(2u, text1_values.size());
  2688. EXPECT_EQ("aaaaa", text1_values[0]);
  2689. EXPECT_EQ("bbbbb", text1_values[1]);
  2690. }
  2691. {
  2692. const auto &file1_values = req.form.get_files("multi_file1");
  2693. EXPECT_EQ(2u, file1_values.size());
  2694. auto file1 = file1_values[0];
  2695. EXPECT_EQ(file1.filename, "hello.txt");
  2696. EXPECT_EQ(file1.content_type, "text/plain");
  2697. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2698. auto file2 = file1_values[1];
  2699. EXPECT_EQ(file2.filename, "world.json");
  2700. EXPECT_EQ(file2.content_type, "application/json");
  2701. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2702. }
  2703. })
  2704. .Post("/empty",
  2705. [&](const Request &req, Response &res) {
  2706. EXPECT_EQ(req.body, "");
  2707. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2708. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2709. res.set_content("empty", "text/plain");
  2710. })
  2711. .Post("/empty-no-content-type",
  2712. [&](const Request &req, Response &res) {
  2713. EXPECT_EQ(req.body, "");
  2714. EXPECT_FALSE(req.has_header("Content-Type"));
  2715. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2716. res.set_content("empty-no-content-type", "text/plain");
  2717. })
  2718. .Post("/path-only",
  2719. [&](const Request &req, Response &res) {
  2720. EXPECT_EQ(req.body, "");
  2721. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2723. res.set_content("path-only", "text/plain");
  2724. })
  2725. .Post("/path-headers-only",
  2726. [&](const Request &req, Response &res) {
  2727. EXPECT_EQ(req.body, "");
  2728. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2729. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2730. EXPECT_EQ("world", req.get_header_value("hello"));
  2731. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2732. res.set_content("path-headers-only", "text/plain");
  2733. })
  2734. .Post("/post-large",
  2735. [&](const Request &req, Response &res) {
  2736. EXPECT_EQ(req.body, LARGE_DATA);
  2737. res.set_content(req.body, "text/plain");
  2738. })
  2739. .Put("/empty-no-content-type",
  2740. [&](const Request &req, Response &res) {
  2741. EXPECT_EQ(req.body, "");
  2742. EXPECT_FALSE(req.has_header("Content-Type"));
  2743. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2744. res.set_content("empty-no-content-type", "text/plain");
  2745. })
  2746. .Put("/put",
  2747. [&](const Request &req, Response &res) {
  2748. EXPECT_EQ(req.body, "PUT");
  2749. res.set_content(req.body, "text/plain");
  2750. })
  2751. .Put("/put-large",
  2752. [&](const Request &req, Response &res) {
  2753. EXPECT_EQ(req.body, LARGE_DATA);
  2754. res.set_content(req.body, "text/plain");
  2755. })
  2756. .Patch("/patch",
  2757. [&](const Request &req, Response &res) {
  2758. EXPECT_EQ(req.body, "PATCH");
  2759. res.set_content(req.body, "text/plain");
  2760. })
  2761. .Delete("/delete",
  2762. [&](const Request & /*req*/, Response &res) {
  2763. res.set_content("DELETE", "text/plain");
  2764. })
  2765. .Delete("/delete-body",
  2766. [&](const Request &req, Response &res) {
  2767. EXPECT_EQ(req.body, "content");
  2768. res.set_content(req.body, "text/plain");
  2769. })
  2770. .Options(R"(\*)",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2773. })
  2774. .Get("/request-target",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2777. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2778. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2779. })
  2780. .Get("/long-query-value",
  2781. [&](const Request &req, Response & /*res*/) {
  2782. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2783. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2784. })
  2785. .Get("/too-long-query-value",
  2786. [&](const Request &req, Response & /*res*/) {
  2787. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2788. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2789. })
  2790. .Get("/array-param",
  2791. [&](const Request &req, Response & /*res*/) {
  2792. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2793. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2794. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2795. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2796. })
  2797. .Post("/validate-no-multiple-headers",
  2798. [&](const Request &req, Response & /*res*/) {
  2799. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2800. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2801. })
  2802. .Post("/content_receiver",
  2803. [&](const Request &req, Response &res,
  2804. const ContentReader &content_reader) {
  2805. if (req.is_multipart_form_data()) {
  2806. std::vector<FormData> items;
  2807. content_reader(
  2808. [&](const FormData &file) {
  2809. items.push_back(file);
  2810. return true;
  2811. },
  2812. [&](const char *data, size_t data_length) {
  2813. items.back().content.append(data, data_length);
  2814. return true;
  2815. });
  2816. EXPECT_EQ(5u, items.size());
  2817. {
  2818. const auto &file = get_file_value(items, "text1");
  2819. EXPECT_TRUE(file.filename.empty());
  2820. EXPECT_EQ("text default", file.content);
  2821. }
  2822. {
  2823. const auto &file = get_file_value(items, "text2");
  2824. EXPECT_TRUE(file.filename.empty());
  2825. EXPECT_EQ("aωb", file.content);
  2826. }
  2827. {
  2828. const auto &file = get_file_value(items, "file1");
  2829. EXPECT_EQ("hello.txt", file.filename);
  2830. EXPECT_EQ("text/plain", file.content_type);
  2831. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2832. }
  2833. {
  2834. const auto &file = get_file_value(items, "file2");
  2835. EXPECT_EQ("world.json", file.filename);
  2836. EXPECT_EQ("application/json", file.content_type);
  2837. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2838. }
  2839. {
  2840. const auto &file = get_file_value(items, "file3");
  2841. EXPECT_TRUE(file.filename.empty());
  2842. EXPECT_EQ("application/octet-stream", file.content_type);
  2843. EXPECT_EQ(0u, file.content.size());
  2844. }
  2845. } else {
  2846. std::string body;
  2847. content_reader([&](const char *data, size_t data_length) {
  2848. EXPECT_EQ(7U, data_length);
  2849. body.append(data, data_length);
  2850. return true;
  2851. });
  2852. EXPECT_EQ(body, "content");
  2853. res.set_content(body, "text/plain");
  2854. }
  2855. })
  2856. .Put("/content_receiver",
  2857. [&](const Request & /*req*/, Response &res,
  2858. const ContentReader &content_reader) {
  2859. std::string body;
  2860. content_reader([&](const char *data, size_t data_length) {
  2861. body.append(data, data_length);
  2862. return true;
  2863. });
  2864. EXPECT_EQ(body, "content");
  2865. res.set_content(body, "text/plain");
  2866. })
  2867. .Patch("/content_receiver",
  2868. [&](const Request & /*req*/, Response &res,
  2869. const ContentReader &content_reader) {
  2870. std::string body;
  2871. content_reader([&](const char *data, size_t data_length) {
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. EXPECT_EQ(body, "content");
  2876. res.set_content(body, "text/plain");
  2877. })
  2878. .Post("/query-string-and-body",
  2879. [&](const Request &req, Response & /*res*/) {
  2880. ASSERT_TRUE(req.has_param("key"));
  2881. EXPECT_EQ(req.get_param_value("key"), "value");
  2882. EXPECT_EQ(req.body, "content");
  2883. })
  2884. .Get("/last-request",
  2885. [&](const Request &req, Response & /*res*/) {
  2886. EXPECT_EQ("close", req.get_header_value("Connection"));
  2887. })
  2888. .Get(R"(/redirect/(\d+))",
  2889. [&](const Request &req, Response &res) {
  2890. auto num = std::stoi(req.matches[1]) + 1;
  2891. std::string url = "/redirect/" + std::to_string(num);
  2892. res.set_redirect(url);
  2893. })
  2894. .Post("/binary",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(4U, req.body.size());
  2897. EXPECT_EQ("application/octet-stream",
  2898. req.get_header_value("Content-Type"));
  2899. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2900. res.set_content(req.body, "application/octet-stream");
  2901. })
  2902. .Put("/binary",
  2903. [&](const Request &req, Response &res) {
  2904. EXPECT_EQ(4U, req.body.size());
  2905. EXPECT_EQ("application/octet-stream",
  2906. req.get_header_value("Content-Type"));
  2907. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2908. res.set_content(req.body, "application/octet-stream");
  2909. })
  2910. .Patch("/binary",
  2911. [&](const Request &req, Response &res) {
  2912. EXPECT_EQ(4U, req.body.size());
  2913. EXPECT_EQ("application/octet-stream",
  2914. req.get_header_value("Content-Type"));
  2915. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2916. res.set_content(req.body, "application/octet-stream");
  2917. })
  2918. .Delete("/binary",
  2919. [&](const Request &req, Response &res) {
  2920. EXPECT_EQ(4U, req.body.size());
  2921. EXPECT_EQ("application/octet-stream",
  2922. req.get_header_value("Content-Type"));
  2923. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2924. res.set_content(req.body, "application/octet-stream");
  2925. })
  2926. .Get("/issue1772",
  2927. [&](const Request & /*req*/, Response &res) {
  2928. res.status = 401;
  2929. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2930. })
  2931. .Delete("/issue609",
  2932. [](const httplib::Request &, httplib::Response &res,
  2933. const httplib::ContentReader &) {
  2934. res.set_content("ok", "text/plain");
  2935. })
  2936. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2937. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2938. .Get("/compress",
  2939. [&](const Request & /*req*/, Response &res) {
  2940. res.set_content(
  2941. "12345678901234567890123456789012345678901234567890123456789"
  2942. "01234567890123456789012345678901234567890",
  2943. "text/plain");
  2944. })
  2945. .Get("/nocompress",
  2946. [&](const Request & /*req*/, Response &res) {
  2947. res.set_content(
  2948. "12345678901234567890123456789012345678901234567890123456789"
  2949. "01234567890123456789012345678901234567890",
  2950. "application/octet-stream");
  2951. })
  2952. .Post("/compress-multipart",
  2953. [&](const Request &req, Response & /*res*/) {
  2954. EXPECT_EQ(2u, req.form.fields.size());
  2955. ASSERT_TRUE(!req.form.has_field("???"));
  2956. {
  2957. const auto &text = req.form.get_field("key1");
  2958. EXPECT_EQ("test", text);
  2959. }
  2960. {
  2961. const auto &text = req.form.get_field("key2");
  2962. EXPECT_EQ("--abcdefg123", text);
  2963. }
  2964. })
  2965. #endif
  2966. ;
  2967. persons_["john"] = "programmer";
  2968. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2969. svr_.wait_until_ready();
  2970. }
  2971. virtual void TearDown() {
  2972. svr_.stop();
  2973. if (!request_threads_.empty()) {
  2974. std::this_thread::sleep_for(std::chrono::seconds(1));
  2975. for (auto &t : request_threads_) {
  2976. t.join();
  2977. }
  2978. }
  2979. t_.join();
  2980. }
  2981. map<string, string> persons_;
  2982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2983. SSLClient cli_;
  2984. SSLServer svr_;
  2985. #else
  2986. Client cli_;
  2987. Server svr_;
  2988. #endif
  2989. thread t_;
  2990. std::vector<thread> request_threads_;
  2991. };
  2992. TEST_F(ServerTest, GetMethod200) {
  2993. auto res = cli_.Get("/hi");
  2994. ASSERT_TRUE(res);
  2995. EXPECT_EQ("HTTP/1.1", res->version);
  2996. EXPECT_EQ(StatusCode::OK_200, res->status);
  2997. EXPECT_EQ("OK", res->reason);
  2998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2999. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3000. EXPECT_EQ("Hello World!", res->body);
  3001. }
  3002. void performance_test(const char *host) {
  3003. auto port = 1234;
  3004. Server svr;
  3005. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3006. res.set_content("Benchmark Response", "text/plain");
  3007. });
  3008. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. listen_thread.join();
  3012. ASSERT_FALSE(svr.is_running());
  3013. });
  3014. svr.wait_until_ready();
  3015. Client cli(host, port);
  3016. auto start = std::chrono::high_resolution_clock::now();
  3017. auto res = cli.Get("/benchmark");
  3018. ASSERT_TRUE(res);
  3019. EXPECT_EQ(StatusCode::OK_200, res->status);
  3020. auto end = std::chrono::high_resolution_clock::now();
  3021. auto elapsed =
  3022. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3023. .count();
  3024. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3025. << "ms (Issue #1777)";
  3026. }
  3027. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3028. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3029. TEST_F(ServerTest, GetEmptyFile) {
  3030. auto res = cli_.Get("/empty_file");
  3031. ASSERT_TRUE(res);
  3032. EXPECT_EQ(StatusCode::OK_200, res->status);
  3033. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3034. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3035. EXPECT_EQ("", res->body);
  3036. }
  3037. TEST_F(ServerTest, GetFileContent) {
  3038. auto res = cli_.Get("/file_content");
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(StatusCode::OK_200, res->status);
  3041. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3042. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3043. EXPECT_EQ("test.html", res->body);
  3044. }
  3045. TEST_F(ServerTest, GetFileContentWithRange) {
  3046. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3047. ASSERT_TRUE(res);
  3048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3050. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3051. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3052. EXPECT_EQ("est", res->body);
  3053. }
  3054. TEST_F(ServerTest, GetFileContentWithContentType) {
  3055. auto res = cli_.Get("/file_content_with_content_type");
  3056. ASSERT_TRUE(res);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3059. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3060. EXPECT_EQ("file\n", res->body);
  3061. }
  3062. TEST_F(ServerTest, GetInvalidFileContent) {
  3063. auto res = cli_.Get("/invalid_file_content");
  3064. ASSERT_TRUE(res);
  3065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3066. }
  3067. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3068. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ("HTTP/1.1", res->version);
  3071. EXPECT_EQ(StatusCode::OK_200, res->status);
  3072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3073. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3074. EXPECT_EQ("Hello World!", res->body);
  3075. }
  3076. TEST_F(ServerTest, GetMethod302) {
  3077. auto res = cli_.Get("/");
  3078. ASSERT_TRUE(res);
  3079. EXPECT_EQ(StatusCode::Found_302, res->status);
  3080. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3081. }
  3082. TEST_F(ServerTest, GetMethod302Redirect) {
  3083. cli_.set_follow_location(true);
  3084. auto res = cli_.Get("/");
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. EXPECT_EQ("Hello World!", res->body);
  3088. EXPECT_EQ("/hi", res->location);
  3089. }
  3090. TEST_F(ServerTest, GetMethod404) {
  3091. auto res = cli_.Get("/invalid");
  3092. ASSERT_TRUE(res);
  3093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3094. }
  3095. TEST_F(ServerTest, HeadMethod200) {
  3096. auto res = cli_.Head("/hi");
  3097. ASSERT_TRUE(res);
  3098. EXPECT_EQ(StatusCode::OK_200, res->status);
  3099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3100. EXPECT_TRUE(res->body.empty());
  3101. }
  3102. TEST_F(ServerTest, HeadMethod200Static) {
  3103. auto res = cli_.Head("/mount/dir/index.html");
  3104. ASSERT_TRUE(res);
  3105. EXPECT_EQ(StatusCode::OK_200, res->status);
  3106. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3107. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3108. EXPECT_TRUE(res->body.empty());
  3109. }
  3110. TEST_F(ServerTest, HeadMethod404) {
  3111. auto res = cli_.Head("/invalid");
  3112. ASSERT_TRUE(res);
  3113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3114. EXPECT_TRUE(res->body.empty());
  3115. }
  3116. TEST_F(ServerTest, GetMethodPersonJohn) {
  3117. auto res = cli_.Get("/person/john");
  3118. ASSERT_TRUE(res);
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3121. EXPECT_EQ("programmer", res->body);
  3122. }
  3123. TEST_F(ServerTest, PostMethod1) {
  3124. auto res = cli_.Get("/person/john1");
  3125. ASSERT_TRUE(res);
  3126. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3127. res = cli_.Post("/person", "name=john1&note=coder",
  3128. "application/x-www-form-urlencoded");
  3129. ASSERT_TRUE(res);
  3130. ASSERT_EQ(StatusCode::OK_200, res->status);
  3131. res = cli_.Get("/person/john1");
  3132. ASSERT_TRUE(res);
  3133. ASSERT_EQ(StatusCode::OK_200, res->status);
  3134. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3135. ASSERT_EQ("coder", res->body);
  3136. }
  3137. TEST_F(ServerTest, PostMethod2) {
  3138. auto res = cli_.Get("/person/john2");
  3139. ASSERT_TRUE(res);
  3140. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3141. Params params;
  3142. params.emplace("name", "john2");
  3143. params.emplace("note", "coder");
  3144. res = cli_.Post("/person", params);
  3145. ASSERT_TRUE(res);
  3146. ASSERT_EQ(StatusCode::OK_200, res->status);
  3147. res = cli_.Get("/person/john2");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3151. ASSERT_EQ("coder", res->body);
  3152. }
  3153. TEST_F(ServerTest, PutMethod3) {
  3154. auto res = cli_.Get("/person/john3");
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3157. Params params;
  3158. params.emplace("name", "john3");
  3159. params.emplace("note", "coder");
  3160. res = cli_.Put("/person", params);
  3161. ASSERT_TRUE(res);
  3162. ASSERT_EQ(StatusCode::OK_200, res->status);
  3163. res = cli_.Get("/person/john3");
  3164. ASSERT_TRUE(res);
  3165. ASSERT_EQ(StatusCode::OK_200, res->status);
  3166. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. ASSERT_EQ("coder", res->body);
  3168. }
  3169. TEST_F(ServerTest, DeleteMethod1) {
  3170. auto res = cli_.Get("/person/john4");
  3171. ASSERT_TRUE(res);
  3172. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3173. Params params;
  3174. params.emplace("name", "john4");
  3175. params.emplace("note", "coder");
  3176. res = cli_.Post("/person", params);
  3177. ASSERT_TRUE(res);
  3178. ASSERT_EQ(StatusCode::OK_200, res->status);
  3179. res = cli_.Get("/person/john4");
  3180. ASSERT_TRUE(res);
  3181. ASSERT_EQ(StatusCode::OK_200, res->status);
  3182. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3183. ASSERT_EQ("coder", res->body);
  3184. Params delete_params;
  3185. delete_params.emplace("name", "john4");
  3186. res = cli_.Delete("/person", delete_params);
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::OK_200, res->status);
  3189. ASSERT_EQ("DELETED", res->body);
  3190. res = cli_.Get("/person/john4");
  3191. ASSERT_TRUE(res);
  3192. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3193. }
  3194. TEST_F(ServerTest, DeleteMethod2) {
  3195. auto res = cli_.Get("/person/john5");
  3196. ASSERT_TRUE(res);
  3197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3198. Params params;
  3199. params.emplace("name", "john5");
  3200. params.emplace("note", "developer");
  3201. res = cli_.Post("/person", params);
  3202. ASSERT_TRUE(res);
  3203. ASSERT_EQ(StatusCode::OK_200, res->status);
  3204. res = cli_.Get("/person/john5");
  3205. ASSERT_TRUE(res);
  3206. ASSERT_EQ(StatusCode::OK_200, res->status);
  3207. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3208. ASSERT_EQ("developer", res->body);
  3209. Params delete_params;
  3210. delete_params.emplace("name", "john5");
  3211. Headers headers;
  3212. headers.emplace("Custom-Header", "test-value");
  3213. res = cli_.Delete("/person", headers, delete_params);
  3214. ASSERT_TRUE(res);
  3215. ASSERT_EQ(StatusCode::OK_200, res->status);
  3216. ASSERT_EQ("DELETED", res->body);
  3217. res = cli_.Get("/person/john5");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3220. }
  3221. TEST_F(ServerTest, DeleteMethod3) {
  3222. auto res = cli_.Get("/person/john6");
  3223. ASSERT_TRUE(res);
  3224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3225. Params params;
  3226. params.emplace("name", "john6");
  3227. params.emplace("note", "tester");
  3228. res = cli_.Post("/person", params);
  3229. ASSERT_TRUE(res);
  3230. ASSERT_EQ(StatusCode::OK_200, res->status);
  3231. res = cli_.Get("/person/john6");
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3235. ASSERT_EQ("tester", res->body);
  3236. Params delete_params;
  3237. delete_params.emplace("name", "john6");
  3238. Headers headers;
  3239. headers.emplace("Custom-Header", "test-value");
  3240. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. ASSERT_EQ("DELETED", res->body);
  3244. res = cli_.Get("/person/john6");
  3245. ASSERT_TRUE(res);
  3246. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3247. }
  3248. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3249. Params params;
  3250. params.emplace("json", JSON_DATA);
  3251. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::OK_200, res->status);
  3254. ASSERT_EQ(JSON_DATA, res->body);
  3255. }
  3256. TEST_F(ServerTest, PostEmptyContent) {
  3257. auto res = cli_.Post("/empty", "", "text/plain");
  3258. ASSERT_TRUE(res);
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. ASSERT_EQ("empty", res->body);
  3261. }
  3262. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3263. auto res = cli_.Post("/empty-no-content-type");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::OK_200, res->status);
  3266. ASSERT_EQ("empty-no-content-type", res->body);
  3267. }
  3268. TEST_F(ServerTest, PostPathOnly) {
  3269. auto res = cli_.Post("/path-only");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. ASSERT_EQ("path-only", res->body);
  3273. }
  3274. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3275. auto res = cli_.Post("/path-headers-only",
  3276. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3277. ASSERT_TRUE(res);
  3278. ASSERT_EQ(StatusCode::OK_200, res->status);
  3279. ASSERT_EQ("path-headers-only", res->body);
  3280. }
  3281. TEST_F(ServerTest, PostLarge) {
  3282. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::OK_200, res->status);
  3285. EXPECT_EQ(LARGE_DATA, res->body);
  3286. }
  3287. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3288. auto res = cli_.Put("/empty-no-content-type");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::OK_200, res->status);
  3291. ASSERT_EQ("empty-no-content-type", res->body);
  3292. }
  3293. TEST_F(ServerTest, GetMethodDir) {
  3294. auto res = cli_.Get("/dir/");
  3295. ASSERT_TRUE(res);
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3298. auto body = R"(<html>
  3299. <head>
  3300. </head>
  3301. <body>
  3302. <a href="/dir/test.html">Test</a>
  3303. <a href="/hi">hi</a>
  3304. </body>
  3305. </html>
  3306. )";
  3307. EXPECT_EQ(body, res->body);
  3308. }
  3309. TEST_F(ServerTest, GetMethodDirTest) {
  3310. auto res = cli_.Get("/dir/test.html");
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(StatusCode::OK_200, res->status);
  3313. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3314. EXPECT_EQ("test.html", res->body);
  3315. }
  3316. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3317. auto res = cli_.Get("/dir/../dir/test.html");
  3318. ASSERT_TRUE(res);
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3321. EXPECT_EQ("test.html", res->body);
  3322. }
  3323. TEST_F(ServerTest, GetMethodInvalidPath) {
  3324. auto res = cli_.Get("/dir/../test.html");
  3325. ASSERT_TRUE(res);
  3326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3327. }
  3328. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3329. auto res = cli_.Get("/../www/dir/test.html");
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3332. }
  3333. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3334. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3335. ASSERT_TRUE(res);
  3336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3337. }
  3338. TEST_F(ServerTest, GetMethodDirMountTest) {
  3339. auto res = cli_.Get("/mount/dir/test.html");
  3340. ASSERT_TRUE(res);
  3341. EXPECT_EQ(StatusCode::OK_200, res->status);
  3342. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3343. EXPECT_EQ("test.html", res->body);
  3344. }
  3345. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3346. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::OK_200, res->status);
  3349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3350. EXPECT_EQ("test.html", res->body);
  3351. }
  3352. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3353. auto res = cli_.Get("/mount/dir/../test.html");
  3354. ASSERT_TRUE(res);
  3355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3358. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3359. ASSERT_TRUE(res);
  3360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3361. }
  3362. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3363. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3364. ASSERT_TRUE(res);
  3365. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3366. }
  3367. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3368. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3369. ASSERT_TRUE(res);
  3370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3371. }
  3372. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3373. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3376. }
  3377. TEST_F(ServerTest, PostMethod303) {
  3378. auto res = cli_.Post("/1", "body", "text/plain");
  3379. ASSERT_TRUE(res);
  3380. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3381. EXPECT_EQ("/2", res->get_header_value("Location"));
  3382. }
  3383. TEST_F(ServerTest, PostMethod303Redirect) {
  3384. cli_.set_follow_location(true);
  3385. auto res = cli_.Post("/1", "body", "text/plain");
  3386. ASSERT_TRUE(res);
  3387. EXPECT_EQ(StatusCode::OK_200, res->status);
  3388. EXPECT_EQ("redirected.", res->body);
  3389. EXPECT_EQ("/2", res->location);
  3390. }
  3391. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3392. auto res = cli_.Get("/dir/test.abcde");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ(StatusCode::OK_200, res->status);
  3395. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3396. EXPECT_EQ("abcde", res->body);
  3397. }
  3398. TEST_F(ServerTest, StaticFileRange) {
  3399. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3400. ASSERT_TRUE(res);
  3401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3402. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3403. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3404. EXPECT_EQ(true, res->has_header("Content-Range"));
  3405. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3406. EXPECT_EQ(std::string("cd"), res->body);
  3407. }
  3408. TEST_F(ServerTest, StaticFileRanges) {
  3409. auto res =
  3410. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3413. EXPECT_TRUE(
  3414. res->get_header_value("Content-Type")
  3415. .find(
  3416. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3417. 0);
  3418. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3419. }
  3420. TEST_F(ServerTest, StaticFileRangeHead) {
  3421. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3422. ASSERT_TRUE(res);
  3423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3424. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3425. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3426. EXPECT_EQ(true, res->has_header("Content-Range"));
  3427. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3428. }
  3429. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3430. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3435. EXPECT_EQ(true, res->has_header("Content-Range"));
  3436. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3437. res->get_header_value("Content-Range"));
  3438. EXPECT_EQ("LAST\n", res->body);
  3439. }
  3440. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3441. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3446. EXPECT_EQ(true, res->has_header("Content-Range"));
  3447. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3448. }
  3449. TEST_F(ServerTest, StaticFileBigFile) {
  3450. auto res = cli_.Get("/dir/1MB.txt");
  3451. ASSERT_TRUE(res);
  3452. EXPECT_EQ(StatusCode::OK_200, res->status);
  3453. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3454. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3455. }
  3456. TEST_F(ServerTest, InvalidBaseDirMount) {
  3457. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3458. }
  3459. TEST_F(ServerTest, Binary) {
  3460. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3461. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3462. "application/octet-stream");
  3463. ASSERT_TRUE(res);
  3464. ASSERT_EQ(StatusCode::OK_200, res->status);
  3465. ASSERT_EQ(4U, res->body.size());
  3466. res = cli_.Put("/binary", binary.data(), binary.size(),
  3467. "application/octet-stream");
  3468. ASSERT_TRUE(res);
  3469. ASSERT_EQ(StatusCode::OK_200, res->status);
  3470. ASSERT_EQ(4U, res->body.size());
  3471. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3472. "application/octet-stream");
  3473. ASSERT_TRUE(res);
  3474. ASSERT_EQ(StatusCode::OK_200, res->status);
  3475. ASSERT_EQ(4U, res->body.size());
  3476. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3477. "application/octet-stream");
  3478. ASSERT_TRUE(res);
  3479. ASSERT_EQ(StatusCode::OK_200, res->status);
  3480. ASSERT_EQ(4U, res->body.size());
  3481. }
  3482. TEST_F(ServerTest, BinaryString) {
  3483. auto binary = std::string("\x00\x01\x02\x03", 4);
  3484. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3485. ASSERT_TRUE(res);
  3486. ASSERT_EQ(StatusCode::OK_200, res->status);
  3487. ASSERT_EQ(4U, res->body.size());
  3488. res = cli_.Put("/binary", binary, "application/octet-stream");
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. ASSERT_EQ(4U, res->body.size());
  3492. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ(4U, res->body.size());
  3496. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::OK_200, res->status);
  3499. ASSERT_EQ(4U, res->body.size());
  3500. }
  3501. TEST_F(ServerTest, EmptyRequest) {
  3502. auto res = cli_.Get("");
  3503. ASSERT_TRUE(!res);
  3504. EXPECT_EQ(Error::Connection, res.error());
  3505. }
  3506. TEST_F(ServerTest, LongRequest) {
  3507. std::string request;
  3508. for (size_t i = 0; i < 545; i++) {
  3509. request += "/TooLongRequest";
  3510. }
  3511. request += "OK";
  3512. auto res = cli_.Get(request.c_str());
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3515. }
  3516. TEST_F(ServerTest, TooLongRequest) {
  3517. std::string request;
  3518. for (size_t i = 0; i < 546; i++) {
  3519. request += "/TooLongRequest";
  3520. }
  3521. request += "_NG";
  3522. auto res = cli_.Get(request.c_str());
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3525. }
  3526. TEST_F(ServerTest, AlmostTooLongRequest) {
  3527. // test for #2046 - URI length check shouldn't include other content on req
  3528. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3529. // leading /, space, HTTP/1.1)
  3530. std::string request =
  3531. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3532. auto res = cli_.Get(request.c_str());
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3535. }
  3536. TEST_F(ServerTest, LongHeader) {
  3537. Request req;
  3538. req.method = "GET";
  3539. req.path = "/hi";
  3540. std::string host_and_port;
  3541. host_and_port += HOST;
  3542. host_and_port += ":";
  3543. host_and_port += std::to_string(PORT);
  3544. req.headers.emplace("Host", host_and_port.c_str());
  3545. req.headers.emplace("Accept", "*/*");
  3546. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3547. req.headers.emplace(
  3548. "Header-Name",
  3549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3577. "@@@@@@@@@@@@@@@@");
  3578. auto res = std::make_shared<Response>();
  3579. auto error = Error::Success;
  3580. auto ret = cli_.send(req, *res, error);
  3581. ASSERT_TRUE(ret);
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. }
  3584. TEST_F(ServerTest, LongQueryValue) {
  3585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3588. }
  3589. TEST_F(ServerTest, TooLongQueryValue) {
  3590. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3591. ASSERT_FALSE(res);
  3592. EXPECT_EQ(Error::Read, res.error());
  3593. }
  3594. TEST_F(ServerTest, TooLongHeader) {
  3595. Request req;
  3596. req.method = "GET";
  3597. req.path = "/hi";
  3598. std::string host_and_port;
  3599. host_and_port += HOST;
  3600. host_and_port += ":";
  3601. host_and_port += std::to_string(PORT);
  3602. req.headers.emplace("Host", host_and_port.c_str());
  3603. req.headers.emplace("Accept", "*/*");
  3604. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3605. req.headers.emplace(
  3606. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3635. "@@@@@@@@@@@@@@@@@");
  3636. auto res = std::make_shared<Response>();
  3637. auto error = Error::Success;
  3638. auto ret = cli_.send(req, *res, error);
  3639. ASSERT_TRUE(ret);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. }
  3642. TEST_F(ServerTest, HeaderCountAtLimit) {
  3643. // Test with headers just under the 100 limit
  3644. httplib::Headers headers;
  3645. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3646. // This should keep us just under the 100 header limit
  3647. for (int i = 0; i < 95; i++) {
  3648. std::string name = "X-Test-Header-" + std::to_string(i);
  3649. std::string value = "value" + std::to_string(i);
  3650. headers.emplace(name, value);
  3651. }
  3652. // This should work fine as we're under the limit
  3653. auto res = cli_.Get("/hi", headers);
  3654. EXPECT_TRUE(res);
  3655. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3656. }
  3657. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3658. // Test with many headers to exceed the 100 limit
  3659. httplib::Headers headers;
  3660. // Add 150 headers to definitely exceed the 100 limit
  3661. for (int i = 0; i < 150; i++) {
  3662. std::string name = "X-Test-Header-" + std::to_string(i);
  3663. std::string value = "value" + std::to_string(i);
  3664. headers.emplace(name, value);
  3665. }
  3666. // This should fail due to exceeding header count limit
  3667. auto res = cli_.Get("/hi", headers);
  3668. // The request should either fail or return 400 Bad Request
  3669. if (res) {
  3670. // If we get a response, it should be 400 Bad Request
  3671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3672. } else {
  3673. // Or the request should fail entirely
  3674. EXPECT_FALSE(res);
  3675. }
  3676. }
  3677. TEST_F(ServerTest, PercentEncoding) {
  3678. auto res = cli_.Get("/e%6edwith%");
  3679. ASSERT_TRUE(res);
  3680. EXPECT_EQ(StatusCode::OK_200, res->status);
  3681. }
  3682. TEST_F(ServerTest, PercentEncodingUnicode) {
  3683. auto res = cli_.Get("/e%u006edwith%");
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::OK_200, res->status);
  3686. }
  3687. TEST_F(ServerTest, InvalidPercentEncoding) {
  3688. auto res = cli_.Get("/%endwith%");
  3689. ASSERT_TRUE(res);
  3690. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3691. }
  3692. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3693. auto res = cli_.Get("/%uendwith%");
  3694. ASSERT_TRUE(res);
  3695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3696. }
  3697. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3698. auto res = cli_.Get("/hello?aaa=bbb%");
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3701. }
  3702. TEST_F(ServerTest, PlusSignEncoding) {
  3703. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3704. ASSERT_TRUE(res);
  3705. EXPECT_EQ(StatusCode::OK_200, res->status);
  3706. EXPECT_EQ("a +b", res->body);
  3707. }
  3708. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3709. // This test simulates a potential DoS attack using many headers
  3710. // to verify our security fix prevents memory exhaustion
  3711. httplib::Headers attack_headers;
  3712. // Attempt to add many headers like an attacker would (200 headers to far
  3713. // exceed limit)
  3714. for (int i = 0; i < 200; i++) {
  3715. std::string name = "X-Attack-Header-" + std::to_string(i);
  3716. std::string value = "attack_payload_" + std::to_string(i);
  3717. attack_headers.emplace(name, value);
  3718. }
  3719. // Try to POST with excessive headers
  3720. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3721. // Should either fail or return 400 Bad Request due to security limit
  3722. if (res) {
  3723. // If we get a response, it should be 400 Bad Request
  3724. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3725. } else {
  3726. // Request failed, which is the expected behavior for DoS protection
  3727. EXPECT_FALSE(res);
  3728. }
  3729. }
  3730. TEST_F(ServerTest, MultipartFormData) {
  3731. UploadFormDataItems items = {
  3732. {"text1", "text default", "", ""},
  3733. {"text2", "aωb", "", ""},
  3734. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3735. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3736. {"file3", "", "", "application/octet-stream"},
  3737. {"file4", "", "", " application/json tmp-string "}};
  3738. auto res = cli_.Post("/multipart", items);
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3743. UploadFormDataItems items = {
  3744. {"text", "default text", "", ""},
  3745. {"multi_text1", "aaaaa", "", ""},
  3746. {"multi_text1", "bbbbb", "", ""},
  3747. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3748. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3749. "application/json"},
  3750. };
  3751. auto res = cli_.Post("/multipart/multi_file_values", items);
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::OK_200, res->status);
  3754. }
  3755. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3756. auto res = cli_.Get("/hi");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3760. EXPECT_EQ("Hello World!", res->body);
  3761. }
  3762. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3763. Request req;
  3764. req.method = "POST";
  3765. req.path = "/chunked";
  3766. std::string host_and_port;
  3767. host_and_port += HOST;
  3768. host_and_port += ":";
  3769. host_and_port += std::to_string(PORT);
  3770. req.headers.emplace("Host", host_and_port.c_str());
  3771. req.headers.emplace("Accept", "*/*");
  3772. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3773. req.headers.emplace("Content-Type", "text/plain");
  3774. req.headers.emplace("Content-Length", "0");
  3775. req.headers.emplace(
  3776. "Transfer-Encoding",
  3777. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3778. // Client does not chunk, so make a chunked body manually.
  3779. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3780. auto res = std::make_shared<Response>();
  3781. auto error = Error::Success;
  3782. auto ret = cli_.send(req, *res, error);
  3783. ASSERT_TRUE(ret);
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. }
  3786. TEST_F(ServerTest, GetStreamed2) {
  3787. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3790. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3791. EXPECT_EQ(true, res->has_header("Content-Range"));
  3792. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3793. EXPECT_EQ(std::string("ab"), res->body);
  3794. }
  3795. TEST_F(ServerTest, GetStreamed) {
  3796. auto res = cli_.Get("/streamed");
  3797. ASSERT_TRUE(res);
  3798. EXPECT_EQ(StatusCode::OK_200, res->status);
  3799. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3800. EXPECT_EQ(std::string("aaabbb"), res->body);
  3801. }
  3802. TEST_F(ServerTest, GetStreamedWithRange1) {
  3803. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3804. ASSERT_TRUE(res);
  3805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3806. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3809. EXPECT_EQ(std::string("def"), res->body);
  3810. }
  3811. TEST_F(ServerTest, GetStreamedWithRange2) {
  3812. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3815. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3816. EXPECT_EQ(true, res->has_header("Content-Range"));
  3817. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3818. EXPECT_EQ(std::string("bcdefg"), res->body);
  3819. }
  3820. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3821. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3824. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3825. EXPECT_EQ(true, res->has_header("Content-Range"));
  3826. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3827. EXPECT_EQ(std::string("efg"), res->body);
  3828. }
  3829. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3830. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3833. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3834. EXPECT_EQ(false, res->has_header("Content-Range"));
  3835. EXPECT_EQ(0U, res->body.size());
  3836. }
  3837. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3838. auto res = cli_.Get("/streamed-with-range",
  3839. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3840. "92233720368547758079223372036854775807"}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3843. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3844. EXPECT_EQ(false, res->has_header("Content-Range"));
  3845. EXPECT_EQ(0U, res->body.size());
  3846. }
  3847. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3848. auto res = cli_.Get(
  3849. "/with-range",
  3850. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3851. {"Accept-Encoding", ""}});
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3854. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3855. EXPECT_EQ(true, res->has_header("Content-Range"));
  3856. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3857. EXPECT_EQ(std::string("abcdefg"), res->body);
  3858. }
  3859. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3860. auto res = cli_.Get("/with-range", {
  3861. {"Range", "bytes=0-"},
  3862. {"Accept-Encoding", ""},
  3863. });
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3866. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3867. EXPECT_EQ(true, res->has_header("Content-Range"));
  3868. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3869. EXPECT_EQ(std::string("abcdefg"), res->body);
  3870. }
  3871. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3872. auto res =
  3873. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3876. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(false, res->has_header("Content-Range"));
  3878. EXPECT_EQ(267U, res->body.size());
  3879. // Check that both range contents are present
  3880. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3881. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3882. // Check that Content-Range headers are present for both ranges
  3883. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3884. std::string::npos);
  3885. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3886. std::string::npos);
  3887. }
  3888. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3889. Ranges ranges;
  3890. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3891. ranges.emplace_back(0, -1);
  3892. }
  3893. auto res =
  3894. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3895. ASSERT_TRUE(res);
  3896. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3897. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3898. EXPECT_EQ(false, res->has_header("Content-Range"));
  3899. EXPECT_EQ(0U, res->body.size());
  3900. }
  3901. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3902. auto res =
  3903. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3906. EXPECT_EQ(5U, res->body.size());
  3907. // Check that overlapping ranges are coalesced into a single range
  3908. EXPECT_EQ("bcdef", res->body);
  3909. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3910. // Should be single range, not multipart
  3911. EXPECT_TRUE(res->has_header("Content-Range"));
  3912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3913. }
  3914. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3915. auto res =
  3916. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3919. EXPECT_EQ(268U, res->body.size());
  3920. // Check that both range contents are present
  3921. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3922. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3923. // Check that Content-Range headers are present for both ranges
  3924. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3925. std::string::npos);
  3926. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3927. std::string::npos);
  3928. }
  3929. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3930. auto res =
  3931. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3934. EXPECT_EQ(269U, res->body.size());
  3935. // Check that both duplicate range contents are present
  3936. size_t first_abc = res->body.find("abc\r\n");
  3937. EXPECT_TRUE(first_abc != std::string::npos);
  3938. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3939. EXPECT_TRUE(second_abc != std::string::npos);
  3940. // Check that Content-Range headers are present for both ranges
  3941. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3942. EXPECT_TRUE(first_range != std::string::npos);
  3943. size_t second_range =
  3944. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3945. EXPECT_TRUE(second_range != std::string::npos);
  3946. }
  3947. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3948. auto res = cli_.Get("/streamed-with-range?error",
  3949. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  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, GetStreamedEndless) {
  3957. uint64_t offset = 0;
  3958. auto res = cli_.Get("/streamed-cancel",
  3959. [&](const char * /*data*/, uint64_t data_length) {
  3960. if (offset < 100) {
  3961. offset += data_length;
  3962. return true;
  3963. }
  3964. return false;
  3965. });
  3966. ASSERT_TRUE(!res);
  3967. EXPECT_EQ(Error::Canceled, res.error());
  3968. }
  3969. TEST_F(ServerTest, ClientStop) {
  3970. std::atomic_size_t count{4};
  3971. std::vector<std::thread> threads;
  3972. for (auto i = count.load(); i != 0; --i) {
  3973. threads.emplace_back([&]() {
  3974. auto res = cli_.Get("/streamed-cancel",
  3975. [&](const char *, uint64_t) { return true; });
  3976. --count;
  3977. ASSERT_TRUE(!res);
  3978. EXPECT_TRUE(res.error() == Error::Canceled ||
  3979. res.error() == Error::Read || res.error() == Error::Write);
  3980. });
  3981. }
  3982. std::this_thread::sleep_for(std::chrono::seconds(2));
  3983. while (count != 0) {
  3984. cli_.stop();
  3985. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3986. }
  3987. for (auto &t : threads) {
  3988. t.join();
  3989. }
  3990. }
  3991. TEST_F(ServerTest, GetWithRange1) {
  3992. auto res = cli_.Get("/with-range", {
  3993. make_range_header({{3, 5}}),
  3994. {"Accept-Encoding", ""},
  3995. });
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3998. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3999. EXPECT_EQ(true, res->has_header("Content-Range"));
  4000. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4001. EXPECT_EQ(std::string("def"), res->body);
  4002. }
  4003. TEST_F(ServerTest, GetWithRange2) {
  4004. auto res = cli_.Get("/with-range", {
  4005. make_range_header({{1, -1}}),
  4006. {"Accept-Encoding", ""},
  4007. });
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4010. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4011. EXPECT_EQ(true, res->has_header("Content-Range"));
  4012. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4013. EXPECT_EQ(std::string("bcdefg"), res->body);
  4014. }
  4015. TEST_F(ServerTest, GetWithRange3) {
  4016. auto res = cli_.Get("/with-range", {
  4017. make_range_header({{0, 0}}),
  4018. {"Accept-Encoding", ""},
  4019. });
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4022. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4023. EXPECT_EQ(true, res->has_header("Content-Range"));
  4024. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4025. EXPECT_EQ(std::string("a"), res->body);
  4026. }
  4027. TEST_F(ServerTest, GetWithRange4) {
  4028. auto res = cli_.Get("/with-range", {
  4029. make_range_header({{-1, 2}}),
  4030. {"Accept-Encoding", ""},
  4031. });
  4032. ASSERT_TRUE(res);
  4033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4034. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4035. EXPECT_EQ(true, res->has_header("Content-Range"));
  4036. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4037. EXPECT_EQ(std::string("fg"), res->body);
  4038. }
  4039. TEST_F(ServerTest, GetWithRange5) {
  4040. auto res = cli_.Get("/with-range", {
  4041. make_range_header({{0, 5}}),
  4042. {"Accept-Encoding", ""},
  4043. });
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4046. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(true, res->has_header("Content-Range"));
  4048. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4049. EXPECT_EQ(std::string("abcdef"), res->body);
  4050. }
  4051. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4052. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4055. }
  4056. TEST_F(ServerTest, GetWithRangeMultipart) {
  4057. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4058. ASSERT_TRUE(res);
  4059. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4060. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ(false, res->has_header("Content-Range"));
  4062. EXPECT_EQ(267U, res->body.size());
  4063. }
  4064. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4065. auto res =
  4066. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4069. }
  4070. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4071. auto res = cli_.Get("/with-range-customized-response",
  4072. {{make_range_header({{1, 2}})}});
  4073. ASSERT_TRUE(res);
  4074. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4075. EXPECT_EQ(true, res->has_header("Content-Length"));
  4076. EXPECT_EQ(false, res->has_header("Content-Range"));
  4077. EXPECT_EQ(JSON_DATA, res->body);
  4078. }
  4079. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4080. auto res = cli_.Get("/with-range-customized-response",
  4081. {{make_range_header({{1, 2}, {4, 5}})}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4084. EXPECT_EQ(true, res->has_header("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(JSON_DATA, res->body);
  4087. }
  4088. TEST_F(ServerTest, Issue1772) {
  4089. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4092. }
  4093. TEST_F(ServerTest, Issue609) {
  4094. auto res = cli_.Delete("/issue609");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. EXPECT_EQ(std::string("ok"), res->body);
  4098. }
  4099. TEST_F(ServerTest, GetStreamedChunked) {
  4100. auto res = cli_.Get("/streamed-chunked");
  4101. ASSERT_TRUE(res);
  4102. EXPECT_EQ(StatusCode::OK_200, res->status);
  4103. EXPECT_EQ(std::string("123456789"), res->body);
  4104. }
  4105. TEST_F(ServerTest, GetStreamedChunked2) {
  4106. auto res = cli_.Get("/streamed-chunked2");
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::OK_200, res->status);
  4109. EXPECT_EQ(std::string("123456789"), res->body);
  4110. }
  4111. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4112. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::OK_200, res->status);
  4115. EXPECT_EQ(std::string("123456789"), res->body);
  4116. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  4117. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  4118. }
  4119. TEST_F(ServerTest, LargeChunkedPost) {
  4120. Request req;
  4121. req.method = "POST";
  4122. req.path = "/large-chunked";
  4123. std::string host_and_port;
  4124. host_and_port += HOST;
  4125. host_and_port += ":";
  4126. host_and_port += std::to_string(PORT);
  4127. req.headers.emplace("Host", host_and_port.c_str());
  4128. req.headers.emplace("Accept", "*/*");
  4129. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4130. req.headers.emplace("Content-Type", "text/plain");
  4131. req.headers.emplace("Content-Length", "0");
  4132. req.headers.emplace("Transfer-Encoding", "chunked");
  4133. std::string long_string(30 * 1024u, 'a');
  4134. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4135. // Attempt to make a large enough post to exceed OS buffers, to test that
  4136. // the server handles short reads if the full chunk data isn't available.
  4137. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4138. auto res = std::make_shared<Response>();
  4139. auto error = Error::Success;
  4140. auto ret = cli_.send(req, *res, error);
  4141. ASSERT_TRUE(ret);
  4142. EXPECT_EQ(StatusCode::OK_200, res->status);
  4143. }
  4144. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4145. auto res = cli_.Get("/remote_addr");
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4149. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4150. }
  4151. TEST_F(ServerTest, GetMethodLocalAddr) {
  4152. auto res = cli_.Get("/local_addr");
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::OK_200, res->status);
  4155. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4156. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4157. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4158. }
  4159. TEST_F(ServerTest, HTTPResponseSplitting) {
  4160. auto res = cli_.Get("/http_response_splitting");
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. }
  4164. TEST_F(ServerTest, SlowRequest) {
  4165. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4166. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4167. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4168. }
  4169. #if 0
  4170. TEST_F(ServerTest, SlowPost) {
  4171. char buffer[64 * 1024];
  4172. memset(buffer, 0x42, sizeof(buffer));
  4173. auto res = cli_.Post(
  4174. "/slowpost", 64 * 1024 * 1024,
  4175. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4176. auto ret = sink.write(buffer, sizeof(buffer));
  4177. EXPECT_TRUE(ret);
  4178. return true;
  4179. },
  4180. "text/plain");
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::OK_200, res->status);
  4183. }
  4184. TEST_F(ServerTest, SlowPostFail) {
  4185. char buffer[64 * 1024];
  4186. memset(buffer, 0x42, sizeof(buffer));
  4187. cli_.set_write_timeout(std::chrono::seconds(0));
  4188. auto res = cli_.Post(
  4189. "/slowpost", 64 * 1024 * 1024,
  4190. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4191. sink.write(buffer, sizeof(buffer));
  4192. return true;
  4193. },
  4194. "text/plain");
  4195. ASSERT_TRUE(!res);
  4196. EXPECT_EQ(Error::Write, res.error());
  4197. }
  4198. #endif
  4199. TEST_F(ServerTest, Put) {
  4200. auto res = cli_.Put("/put", "PUT", "text/plain");
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::OK_200, res->status);
  4203. EXPECT_EQ("PUT", res->body);
  4204. }
  4205. TEST_F(ServerTest, PutWithContentProvider) {
  4206. auto res = cli_.Put(
  4207. "/put", 3,
  4208. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4209. sink.os << "PUT";
  4210. return true;
  4211. },
  4212. "text/plain");
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("PUT", res->body);
  4216. }
  4217. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4218. auto res = cli_.Post(
  4219. "/post", 42,
  4220. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4221. return false;
  4222. },
  4223. "text/plain");
  4224. ASSERT_TRUE(!res);
  4225. EXPECT_EQ(Error::Canceled, res.error());
  4226. }
  4227. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4228. auto res = cli_.Put(
  4229. "/put",
  4230. [](size_t /*offset*/, DataSink &sink) {
  4231. sink.os << "PUT";
  4232. sink.done();
  4233. return true;
  4234. },
  4235. "text/plain");
  4236. ASSERT_TRUE(res);
  4237. EXPECT_EQ(StatusCode::OK_200, res->status);
  4238. EXPECT_EQ("PUT", res->body);
  4239. }
  4240. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4241. auto res = cli_.Post(
  4242. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4243. "text/plain");
  4244. ASSERT_TRUE(!res);
  4245. EXPECT_EQ(Error::Canceled, res.error());
  4246. }
  4247. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4248. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4249. cli_.set_compress(true);
  4250. auto res = cli_.Put(
  4251. "/put", 3,
  4252. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4253. sink.os << "PUT";
  4254. return true;
  4255. },
  4256. "text/plain");
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("PUT", res->body);
  4260. }
  4261. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4262. cli_.set_compress(true);
  4263. auto res = cli_.Post(
  4264. "/post", 42,
  4265. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4266. return false;
  4267. },
  4268. "text/plain");
  4269. ASSERT_TRUE(!res);
  4270. EXPECT_EQ(Error::Canceled, res.error());
  4271. }
  4272. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4273. cli_.set_compress(true);
  4274. auto res = cli_.Put(
  4275. "/put",
  4276. [](size_t /*offset*/, DataSink &sink) {
  4277. sink.os << "PUT";
  4278. sink.done();
  4279. return true;
  4280. },
  4281. "text/plain");
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ("PUT", res->body);
  4285. }
  4286. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4287. cli_.set_compress(true);
  4288. auto res = cli_.Post(
  4289. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4290. "text/plain");
  4291. ASSERT_TRUE(!res);
  4292. EXPECT_EQ(Error::Canceled, res.error());
  4293. }
  4294. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4295. cli_.set_compress(true);
  4296. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ(LARGE_DATA, res->body);
  4300. }
  4301. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4303. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4304. Client cli(s.c_str());
  4305. cli.enable_server_certificate_verification(false);
  4306. #else
  4307. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4308. Client cli(s.c_str());
  4309. #endif
  4310. cli.set_compress(true);
  4311. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ(LARGE_DATA, res->body);
  4315. // The compressed size should be less than a 10th of the original. May vary
  4316. // depending on the zlib library.
  4317. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4318. static_cast<uint64_t>(10 * 1024 * 1024));
  4319. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4320. }
  4321. TEST_F(ServerTest, PutContentWithDeflate) {
  4322. cli_.set_compress(false);
  4323. Headers headers;
  4324. headers.emplace("Content-Encoding", "deflate");
  4325. // PUT in deflate format:
  4326. auto res = cli_.Put("/put", headers,
  4327. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4328. ASSERT_TRUE(res);
  4329. EXPECT_EQ(StatusCode::OK_200, res->status);
  4330. EXPECT_EQ("PUT", res->body);
  4331. }
  4332. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4333. Headers headers;
  4334. headers.emplace("Accept-Encoding", "gzip, deflate");
  4335. auto res = cli_.Get("/streamed-chunked", headers);
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::OK_200, res->status);
  4338. EXPECT_EQ(std::string("123456789"), res->body);
  4339. }
  4340. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4341. Headers headers;
  4342. headers.emplace("Accept-Encoding", "gzip, deflate");
  4343. auto res = cli_.Get("/streamed-chunked2", headers);
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ(std::string("123456789"), res->body);
  4347. }
  4348. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4349. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4350. ASSERT_TRUE(res);
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. }
  4353. TEST(GzipDecompressor, ChunkedDecompression) {
  4354. std::string data;
  4355. for (size_t i = 0; i < 32 * 1024; ++i) {
  4356. data.push_back(static_cast<char>('a' + i % 26));
  4357. }
  4358. std::string compressed_data;
  4359. {
  4360. httplib::detail::gzip_compressor compressor;
  4361. bool result = compressor.compress(
  4362. data.data(), data.size(),
  4363. /*last=*/true,
  4364. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4365. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4366. compressed_data_size);
  4367. return true;
  4368. });
  4369. ASSERT_TRUE(result);
  4370. }
  4371. std::string decompressed_data;
  4372. {
  4373. httplib::detail::gzip_decompressor decompressor;
  4374. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4375. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4376. size_t chunk_size = 130;
  4377. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4378. chunk_begin += chunk_size) {
  4379. size_t current_chunk_size =
  4380. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4381. bool result = decompressor.decompress(
  4382. compressed_data.data() + chunk_begin, current_chunk_size,
  4383. [&](const char *decompressed_data_chunk,
  4384. size_t decompressed_data_chunk_size) {
  4385. decompressed_data.insert(decompressed_data.size(),
  4386. decompressed_data_chunk,
  4387. decompressed_data_chunk_size);
  4388. return true;
  4389. });
  4390. ASSERT_TRUE(result);
  4391. }
  4392. }
  4393. ASSERT_EQ(data, decompressed_data);
  4394. }
  4395. TEST(GzipDecompressor, DeflateDecompression) {
  4396. std::string original_text = "Raw deflate without gzip";
  4397. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4398. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4399. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4400. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4401. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4402. std::string decompressed_data;
  4403. {
  4404. httplib::detail::gzip_decompressor decompressor;
  4405. bool result = decompressor.decompress(
  4406. compressed_data.data(), compressed_data.size(),
  4407. [&](const char *decompressed_data_chunk,
  4408. size_t decompressed_data_chunk_size) {
  4409. decompressed_data.insert(decompressed_data.size(),
  4410. decompressed_data_chunk,
  4411. decompressed_data_chunk_size);
  4412. return true;
  4413. });
  4414. ASSERT_TRUE(result);
  4415. }
  4416. ASSERT_EQ(original_text, decompressed_data);
  4417. }
  4418. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4419. std::string original_text = "Raw deflate without gzip";
  4420. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4421. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4422. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4423. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4424. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4425. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4426. std::string decompressed_data;
  4427. {
  4428. httplib::detail::gzip_decompressor decompressor;
  4429. bool result = decompressor.decompress(
  4430. compressed_data.data(), compressed_data.size(),
  4431. [&](const char *decompressed_data_chunk,
  4432. size_t decompressed_data_chunk_size) {
  4433. decompressed_data.insert(decompressed_data.size(),
  4434. decompressed_data_chunk,
  4435. decompressed_data_chunk_size);
  4436. return true;
  4437. });
  4438. ASSERT_TRUE(result);
  4439. }
  4440. ASSERT_EQ(original_text, decompressed_data);
  4441. }
  4442. #ifdef _WIN32
  4443. TEST(GzipDecompressor, LargeRandomData) {
  4444. // prepare large random data that is difficult to be compressed and is
  4445. // expected to have large size even when compressed
  4446. std::random_device seed_gen;
  4447. std::mt19937 random(seed_gen());
  4448. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4449. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4450. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4451. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4452. // compress data over 4GiB
  4453. std::string compressed_data;
  4454. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4455. httplib::detail::gzip_compressor compressor;
  4456. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4457. data.size() * sizeof(std::uint32_t), true,
  4458. [&](const char *data, size_t size) {
  4459. compressed_data.insert(
  4460. compressed_data.size(), data, size);
  4461. return true;
  4462. });
  4463. ASSERT_TRUE(result);
  4464. // FIXME: compressed data size is expected to be greater than 4GiB,
  4465. // but there is no guarantee
  4466. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4467. // decompress data over 4GiB
  4468. std::string decompressed_data;
  4469. decompressed_data.reserve(data_size);
  4470. httplib::detail::gzip_decompressor decompressor;
  4471. result = decompressor.decompress(
  4472. compressed_data.data(), compressed_data.size(),
  4473. [&](const char *data, size_t size) {
  4474. decompressed_data.insert(decompressed_data.size(), data, size);
  4475. return true;
  4476. });
  4477. ASSERT_TRUE(result);
  4478. // compare
  4479. ASSERT_EQ(data_size, decompressed_data.size());
  4480. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4481. 0);
  4482. }
  4483. #endif
  4484. #endif
  4485. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4486. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4487. Headers headers;
  4488. headers.emplace("Accept-Encoding", "br");
  4489. auto res = cli_.Get("/streamed-chunked", headers);
  4490. ASSERT_TRUE(res);
  4491. EXPECT_EQ(StatusCode::OK_200, res->status);
  4492. EXPECT_EQ(std::string("123456789"), res->body);
  4493. }
  4494. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4495. Headers headers;
  4496. headers.emplace("Accept-Encoding", "br");
  4497. auto res = cli_.Get("/streamed-chunked2", headers);
  4498. ASSERT_TRUE(res);
  4499. EXPECT_EQ(StatusCode::OK_200, res->status);
  4500. EXPECT_EQ(std::string("123456789"), res->body);
  4501. }
  4502. #endif
  4503. TEST_F(ServerTest, Patch) {
  4504. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::OK_200, res->status);
  4507. EXPECT_EQ("PATCH", res->body);
  4508. }
  4509. TEST_F(ServerTest, Delete) {
  4510. auto res = cli_.Delete("/delete");
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(StatusCode::OK_200, res->status);
  4513. EXPECT_EQ("DELETE", res->body);
  4514. }
  4515. TEST_F(ServerTest, DeleteContentReceiver) {
  4516. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("content", res->body);
  4520. }
  4521. TEST_F(ServerTest, Options) {
  4522. auto res = cli_.Options("*");
  4523. ASSERT_TRUE(res);
  4524. EXPECT_EQ(StatusCode::OK_200, res->status);
  4525. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4526. EXPECT_TRUE(res->body.empty());
  4527. }
  4528. TEST_F(ServerTest, URL) {
  4529. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4530. ASSERT_TRUE(res);
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. }
  4533. TEST_F(ServerTest, ArrayParam) {
  4534. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. }
  4538. TEST_F(ServerTest, NoMultipleHeaders) {
  4539. Headers headers = {{"Content-Length", "5"}};
  4540. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4541. "text/plain");
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. }
  4545. TEST_F(ServerTest, PostContentReceiver) {
  4546. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4547. ASSERT_TRUE(res);
  4548. ASSERT_EQ(StatusCode::OK_200, res->status);
  4549. ASSERT_EQ("content", res->body);
  4550. }
  4551. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4552. UploadFormDataItems items = {
  4553. {"text1", "text default", "", ""},
  4554. {"text2", "aωb", "", ""},
  4555. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4556. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4557. {"file3", "", "", "application/octet-stream"},
  4558. };
  4559. auto res = cli_.Post("/content_receiver", items);
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4564. UploadFormDataItems items = {
  4565. {"text1", "text default", "", ""},
  4566. {"text2", "aωb", "", ""},
  4567. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4568. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4569. {"file3", "", "", "application/octet-stream"},
  4570. };
  4571. auto boundary = std::string("+++++");
  4572. std::string body;
  4573. for (const auto &item : items) {
  4574. body += "--" + boundary + "\r\n";
  4575. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4576. if (!item.filename.empty()) {
  4577. body += "; filename=\"" + item.filename + "\"";
  4578. }
  4579. body += "\r\n";
  4580. if (!item.content_type.empty()) {
  4581. body += "Content-Type: " + item.content_type + "\r\n";
  4582. }
  4583. body += "\r\n";
  4584. body += item.content + "\r\n";
  4585. }
  4586. body += "--" + boundary + "--\r\n";
  4587. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4588. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. }
  4592. TEST_F(ServerTest, PostContentReceiverGzip) {
  4593. cli_.set_compress(true);
  4594. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4595. ASSERT_TRUE(res);
  4596. ASSERT_EQ(StatusCode::OK_200, res->status);
  4597. ASSERT_EQ("content", res->body);
  4598. }
  4599. TEST_F(ServerTest, PutContentReceiver) {
  4600. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4601. ASSERT_TRUE(res);
  4602. ASSERT_EQ(StatusCode::OK_200, res->status);
  4603. ASSERT_EQ("content", res->body);
  4604. }
  4605. TEST_F(ServerTest, PatchContentReceiver) {
  4606. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4607. ASSERT_TRUE(res);
  4608. ASSERT_EQ(StatusCode::OK_200, res->status);
  4609. ASSERT_EQ("content", res->body);
  4610. }
  4611. template <typename ClientType>
  4612. void TestWithHeadersAndContentReceiver(
  4613. ClientType &cli,
  4614. std::function<Result(ClientType &, const std::string &, const Headers &,
  4615. const std::string &, const std::string &,
  4616. ContentReceiver, DownloadProgress)>
  4617. request_func) {
  4618. Headers headers;
  4619. headers.emplace("X-Custom-Header", "test-value");
  4620. std::string received_body;
  4621. auto res = request_func(
  4622. cli, "/content_receiver", headers, "content", "application/json",
  4623. [&](const char *data, size_t data_length) {
  4624. received_body.append(data, data_length);
  4625. return true;
  4626. },
  4627. nullptr);
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. EXPECT_EQ("content", received_body);
  4631. }
  4632. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4634. using ClientT = SSLClient;
  4635. #else
  4636. using ClientT = Client;
  4637. #endif
  4638. TestWithHeadersAndContentReceiver<ClientT>(
  4639. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4640. const std::string &body, const std::string &content_type,
  4641. ContentReceiver receiver, DownloadProgress progress) {
  4642. return cli.Post(path, headers, body, content_type, receiver, progress);
  4643. });
  4644. }
  4645. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4646. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4647. using ClientT = SSLClient;
  4648. #else
  4649. using ClientT = Client;
  4650. #endif
  4651. TestWithHeadersAndContentReceiver<ClientT>(
  4652. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4653. const std::string &body, const std::string &content_type,
  4654. ContentReceiver receiver, DownloadProgress progress) {
  4655. return cli.Put(path, headers, body, content_type, receiver, progress);
  4656. });
  4657. }
  4658. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4659. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4660. using ClientT = SSLClient;
  4661. #else
  4662. using ClientT = Client;
  4663. #endif
  4664. TestWithHeadersAndContentReceiver<ClientT>(
  4665. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4666. const std::string &body, const std::string &content_type,
  4667. ContentReceiver receiver, DownloadProgress progress) {
  4668. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4669. });
  4670. }
  4671. template <typename ClientType>
  4672. void TestWithHeadersAndContentReceiverWithProgress(
  4673. ClientType &cli,
  4674. std::function<Result(ClientType &, const std::string &, const Headers &,
  4675. const std::string &, const std::string &,
  4676. ContentReceiver, DownloadProgress)>
  4677. request_func) {
  4678. Headers headers;
  4679. headers.emplace("X-Test-Header", "progress-test");
  4680. std::string received_body;
  4681. auto progress_called = false;
  4682. auto res = request_func(
  4683. cli, "/content_receiver", headers, "content", "text/plain",
  4684. [&](const char *data, size_t data_length) {
  4685. received_body.append(data, data_length);
  4686. return true;
  4687. },
  4688. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4689. progress_called = true;
  4690. return true;
  4691. });
  4692. ASSERT_TRUE(res);
  4693. EXPECT_EQ(StatusCode::OK_200, res->status);
  4694. EXPECT_EQ("content", received_body);
  4695. EXPECT_TRUE(progress_called);
  4696. }
  4697. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4698. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4699. using ClientT = SSLClient;
  4700. #else
  4701. using ClientT = Client;
  4702. #endif
  4703. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4704. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4705. const std::string &body, const std::string &content_type,
  4706. ContentReceiver receiver, DownloadProgress progress) {
  4707. return cli.Post(path, headers, body, content_type, receiver, progress);
  4708. });
  4709. }
  4710. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4711. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4712. using ClientT = SSLClient;
  4713. #else
  4714. using ClientT = Client;
  4715. #endif
  4716. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4717. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4718. const std::string &body, const std::string &content_type,
  4719. ContentReceiver receiver, DownloadProgress progress) {
  4720. return cli.Put(path, headers, body, content_type, receiver, progress);
  4721. });
  4722. }
  4723. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4725. using ClientT = SSLClient;
  4726. #else
  4727. using ClientT = Client;
  4728. #endif
  4729. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4730. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4731. const std::string &body, const std::string &content_type,
  4732. ContentReceiver receiver, DownloadProgress progress) {
  4733. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4734. });
  4735. }
  4736. template <typename ClientType>
  4737. void TestWithHeadersAndContentReceiverError(
  4738. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4739. const Headers &, const std::string &,
  4740. const std::string &, ContentReceiver)>
  4741. request_func) {
  4742. Headers headers;
  4743. headers.emplace("X-Error-Test", "true");
  4744. std::string received_body;
  4745. auto receiver_failed = false;
  4746. auto res =
  4747. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4748. [&](const char *data, size_t data_length) {
  4749. received_body.append(data, data_length);
  4750. receiver_failed = true;
  4751. return false;
  4752. });
  4753. ASSERT_FALSE(res);
  4754. EXPECT_TRUE(receiver_failed);
  4755. }
  4756. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4757. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4758. using ClientT = SSLClient;
  4759. #else
  4760. using ClientT = Client;
  4761. #endif
  4762. TestWithHeadersAndContentReceiverError<ClientT>(
  4763. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4764. const std::string &body, const std::string &content_type,
  4765. ContentReceiver receiver) {
  4766. return cli.Post(path, headers, body, content_type, receiver);
  4767. });
  4768. }
  4769. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4770. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4771. using ClientT = SSLClient;
  4772. #else
  4773. using ClientT = Client;
  4774. #endif
  4775. TestWithHeadersAndContentReceiverError<ClientT>(
  4776. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4777. const std::string &body, const std::string &content_type,
  4778. ContentReceiver receiver) {
  4779. return cli.Put(path, headers, body, content_type, receiver);
  4780. });
  4781. }
  4782. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4784. using ClientT = SSLClient;
  4785. #else
  4786. using ClientT = Client;
  4787. #endif
  4788. TestWithHeadersAndContentReceiverError<ClientT>(
  4789. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4790. const std::string &body, const std::string &content_type,
  4791. ContentReceiver receiver) {
  4792. return cli.Patch(path, headers, body, content_type, receiver);
  4793. });
  4794. }
  4795. TEST_F(ServerTest, PostQueryStringAndBody) {
  4796. auto res =
  4797. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4798. ASSERT_TRUE(res);
  4799. ASSERT_EQ(StatusCode::OK_200, res->status);
  4800. }
  4801. TEST_F(ServerTest, HTTP2Magic) {
  4802. Request req;
  4803. req.method = "PRI";
  4804. req.path = "*";
  4805. req.body = "SM";
  4806. auto res = std::make_shared<Response>();
  4807. auto error = Error::Success;
  4808. auto ret = cli_.send(req, *res, error);
  4809. ASSERT_TRUE(ret);
  4810. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4811. }
  4812. TEST_F(ServerTest, KeepAlive) {
  4813. auto res = cli_.Get("/hi");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4817. EXPECT_EQ("Hello World!", res->body);
  4818. res = cli_.Get("/hi");
  4819. ASSERT_TRUE(res);
  4820. EXPECT_EQ(StatusCode::OK_200, res->status);
  4821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4822. EXPECT_EQ("Hello World!", res->body);
  4823. res = cli_.Get("/hi");
  4824. ASSERT_TRUE(res);
  4825. EXPECT_EQ(StatusCode::OK_200, res->status);
  4826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4827. EXPECT_EQ("Hello World!", res->body);
  4828. res = cli_.Get("/not-exist");
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4831. res = cli_.Post("/empty", "", "text/plain");
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::OK_200, res->status);
  4834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4835. EXPECT_EQ("empty", res->body);
  4836. EXPECT_EQ("close", res->get_header_value("Connection"));
  4837. res = cli_.Post(
  4838. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4839. "text/plain");
  4840. ASSERT_TRUE(res);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4843. EXPECT_EQ("empty", res->body);
  4844. cli_.set_keep_alive(false);
  4845. res = cli_.Get("/last-request");
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::OK_200, res->status);
  4848. EXPECT_EQ("close", res->get_header_value("Connection"));
  4849. }
  4850. TEST_F(ServerTest, TooManyRedirect) {
  4851. cli_.set_follow_location(true);
  4852. auto res = cli_.Get("/redirect/0");
  4853. ASSERT_TRUE(!res);
  4854. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4855. }
  4856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4857. TEST_F(ServerTest, Gzip) {
  4858. Headers headers;
  4859. headers.emplace("Accept-Encoding", "gzip, deflate");
  4860. auto res = cli_.Get("/compress", headers);
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4864. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4865. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4866. "7890123456789012345678901234567890",
  4867. res->body);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4871. Headers headers;
  4872. headers.emplace("Accept-Encoding", "");
  4873. auto res = cli_.Get("/compress", headers);
  4874. ASSERT_TRUE(res);
  4875. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4877. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4879. "7890123456789012345678901234567890",
  4880. res->body);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, GzipWithContentReceiver) {
  4884. Headers headers;
  4885. headers.emplace("Accept-Encoding", "gzip, deflate");
  4886. std::string body;
  4887. auto res = cli_.Get("/compress", headers,
  4888. [&](const char *data, uint64_t data_length) {
  4889. EXPECT_EQ(100U, data_length);
  4890. body.append(data, data_length);
  4891. return true;
  4892. });
  4893. ASSERT_TRUE(res);
  4894. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4895. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4896. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4897. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4898. "7890123456789012345678901234567890",
  4899. body);
  4900. EXPECT_EQ(StatusCode::OK_200, res->status);
  4901. }
  4902. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4903. Headers headers;
  4904. headers.emplace("Accept-Encoding", "gzip, deflate");
  4905. cli_.set_decompress(false);
  4906. auto res = cli_.Get("/compress", headers);
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4910. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4911. EXPECT_EQ(33U, res->body.size());
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. }
  4914. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4915. Headers headers;
  4916. headers.emplace("Accept-Encoding", "");
  4917. std::string body;
  4918. auto res = cli_.Get("/compress", headers,
  4919. [&](const char *data, uint64_t data_length) {
  4920. EXPECT_EQ(100U, data_length);
  4921. body.append(data, data_length);
  4922. return true;
  4923. });
  4924. ASSERT_TRUE(res);
  4925. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4929. "7890123456789012345678901234567890",
  4930. body);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. }
  4933. TEST_F(ServerTest, NoGzip) {
  4934. Headers headers;
  4935. headers.emplace("Accept-Encoding", "gzip, deflate");
  4936. auto res = cli_.Get("/nocompress", headers);
  4937. ASSERT_TRUE(res);
  4938. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4939. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4940. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4941. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4942. "7890123456789012345678901234567890",
  4943. res->body);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. }
  4946. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4947. Headers headers;
  4948. headers.emplace("Accept-Encoding", "gzip, deflate");
  4949. std::string body;
  4950. auto res = cli_.Get("/nocompress", headers,
  4951. [&](const char *data, uint64_t data_length) {
  4952. EXPECT_EQ(100U, data_length);
  4953. body.append(data, data_length);
  4954. return true;
  4955. });
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4958. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4959. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4960. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4961. "7890123456789012345678901234567890",
  4962. body);
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. }
  4965. TEST_F(ServerTest, MultipartFormDataGzip) {
  4966. UploadFormDataItems items = {
  4967. {"key1", "test", "", ""},
  4968. {"key2", "--abcdefg123", "", ""},
  4969. };
  4970. cli_.set_compress(true);
  4971. auto res = cli_.Post("/compress-multipart", items);
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ(StatusCode::OK_200, res->status);
  4974. }
  4975. #endif
  4976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4977. TEST_F(ServerTest, Brotli) {
  4978. Headers headers;
  4979. headers.emplace("Accept-Encoding", "br");
  4980. auto res = cli_.Get("/compress", headers);
  4981. ASSERT_TRUE(res);
  4982. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4983. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4984. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4985. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4986. "7890123456789012345678901234567890",
  4987. res->body);
  4988. EXPECT_EQ(StatusCode::OK_200, res->status);
  4989. }
  4990. #endif
  4991. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4992. TEST_F(ServerTest, Zstd) {
  4993. Headers headers;
  4994. headers.emplace("Accept-Encoding", "zstd");
  4995. auto res = cli_.Get("/compress", headers);
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4999. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5000. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5001. "7890123456789012345678901234567890",
  5002. res->body);
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. }
  5005. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5006. Headers headers;
  5007. headers.emplace("Accept-Encoding", "");
  5008. auto res = cli_.Get("/compress", headers);
  5009. ASSERT_TRUE(res);
  5010. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5012. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5013. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5014. "7890123456789012345678901234567890",
  5015. res->body);
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. }
  5018. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5019. Headers headers;
  5020. headers.emplace("Accept-Encoding", "zstd");
  5021. std::string body;
  5022. auto res = cli_.Get("/compress", headers,
  5023. [&](const char *data, uint64_t data_length) {
  5024. EXPECT_EQ(100U, data_length);
  5025. body.append(data, data_length);
  5026. return true;
  5027. });
  5028. ASSERT_TRUE(res);
  5029. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5031. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5032. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5033. "7890123456789012345678901234567890",
  5034. body);
  5035. EXPECT_EQ(StatusCode::OK_200, res->status);
  5036. }
  5037. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5038. Headers headers;
  5039. headers.emplace("Accept-Encoding", "zstd");
  5040. cli_.set_decompress(false);
  5041. auto res = cli_.Get("/compress", headers);
  5042. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5043. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5044. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5045. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5046. ASSERT_TRUE(res);
  5047. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5048. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5049. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5050. EXPECT_EQ(StatusCode::OK_200, res->status);
  5051. ASSERT_EQ(26U, res->body.size());
  5052. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5053. 0);
  5054. }
  5055. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5056. Headers headers;
  5057. headers.emplace("Accept-Encoding", "");
  5058. std::string body;
  5059. auto res = cli_.Get("/compress", headers,
  5060. [&](const char *data, uint64_t data_length) {
  5061. EXPECT_EQ(100U, data_length);
  5062. body.append(data, data_length);
  5063. return true;
  5064. });
  5065. ASSERT_TRUE(res);
  5066. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5067. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5068. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5069. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5070. "7890123456789012345678901234567890",
  5071. body);
  5072. EXPECT_EQ(StatusCode::OK_200, res->status);
  5073. }
  5074. TEST_F(ServerTest, NoZstd) {
  5075. Headers headers;
  5076. headers.emplace("Accept-Encoding", "zstd");
  5077. auto res = cli_.Get("/nocompress", headers);
  5078. ASSERT_TRUE(res);
  5079. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5080. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5081. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5082. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5083. "7890123456789012345678901234567890",
  5084. res->body);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5088. Headers headers;
  5089. headers.emplace("Accept-Encoding", "zstd");
  5090. std::string body;
  5091. auto res = cli_.Get("/nocompress", headers,
  5092. [&](const char *data, uint64_t data_length) {
  5093. EXPECT_EQ(100U, data_length);
  5094. body.append(data, data_length);
  5095. return true;
  5096. });
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5099. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5102. "7890123456789012345678901234567890",
  5103. body);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. }
  5106. // TODO: How to enable zstd ??
  5107. TEST_F(ServerTest, MultipartFormDataZstd) {
  5108. UploadFormDataItems items = {
  5109. {"key1", "test", "", ""},
  5110. {"key2", "--abcdefg123", "", ""},
  5111. };
  5112. Headers headers;
  5113. headers.emplace("Accept-Encoding", "zstd");
  5114. cli_.set_compress(true);
  5115. auto res = cli_.Post("/compress-multipart", headers, items);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "zstd");
  5122. cli_.set_compress(true);
  5123. auto res = cli_.Put(
  5124. "/put", headers, 3,
  5125. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5126. sink.os << "PUT";
  5127. return true;
  5128. },
  5129. "text/plain");
  5130. ASSERT_TRUE(res);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. EXPECT_EQ("PUT", res->body);
  5133. }
  5134. // Pre-compression logging tests
  5135. TEST_F(ServerTest, PreCompressionLogging) {
  5136. // Test data for compression (matches the actual /compress endpoint content)
  5137. const std::string test_content =
  5138. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5139. "3456789012345678901234567890";
  5140. // Variables to capture logging data
  5141. std::string pre_compression_body;
  5142. std::string pre_compression_content_type;
  5143. std::string pre_compression_content_encoding;
  5144. std::string post_compression_body;
  5145. std::string post_compression_content_type;
  5146. std::string post_compression_content_encoding;
  5147. // Set up pre-compression logger
  5148. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5149. const Response &res) {
  5150. pre_compression_body = res.body;
  5151. pre_compression_content_type = res.get_header_value("Content-Type");
  5152. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5153. });
  5154. // Set up post-compression logger
  5155. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5156. post_compression_body = res.body;
  5157. post_compression_content_type = res.get_header_value("Content-Type");
  5158. post_compression_content_encoding =
  5159. res.get_header_value("Content-Encoding");
  5160. });
  5161. // Test with gzip compression
  5162. Headers headers;
  5163. headers.emplace("Accept-Encoding", "gzip");
  5164. auto res = cli_.Get("/compress", headers);
  5165. // Verify response was compressed
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5169. // Verify pre-compression logger captured uncompressed content
  5170. EXPECT_EQ(test_content, pre_compression_body);
  5171. EXPECT_EQ("text/plain", pre_compression_content_type);
  5172. EXPECT_TRUE(pre_compression_content_encoding
  5173. .empty()); // No encoding header before compression
  5174. // Verify post-compression logger captured compressed content
  5175. EXPECT_NE(test_content,
  5176. post_compression_body); // Should be different after compression
  5177. EXPECT_EQ("text/plain", post_compression_content_type);
  5178. EXPECT_EQ("gzip", post_compression_content_encoding);
  5179. // Verify compressed content is smaller
  5180. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5181. }
  5182. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5183. const std::string test_content =
  5184. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5185. "3456789012345678901234567890";
  5186. std::string pre_compression_body;
  5187. std::string post_compression_body;
  5188. svr_.set_pre_compression_logger(
  5189. [&](const Request & /*req*/, const Response &res) {
  5190. pre_compression_body = res.body;
  5191. });
  5192. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5193. post_compression_body = res.body;
  5194. });
  5195. Headers headers;
  5196. headers.emplace("Accept-Encoding", "br");
  5197. auto res = cli_.Get("/compress", headers);
  5198. ASSERT_TRUE(res);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5201. // Verify pre-compression content is uncompressed
  5202. EXPECT_EQ(test_content, pre_compression_body);
  5203. // Verify post-compression content is compressed
  5204. EXPECT_NE(test_content, post_compression_body);
  5205. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5206. }
  5207. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5208. const std::string test_content =
  5209. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5210. "3456789012345678901234567890";
  5211. std::string pre_compression_body;
  5212. std::string post_compression_body;
  5213. svr_.set_pre_compression_logger(
  5214. [&](const Request & /*req*/, const Response &res) {
  5215. pre_compression_body = res.body;
  5216. });
  5217. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5218. post_compression_body = res.body;
  5219. });
  5220. // Request without compression (use /nocompress endpoint)
  5221. Headers headers;
  5222. auto res = cli_.Get("/nocompress", headers);
  5223. ASSERT_TRUE(res);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5226. // Pre-compression logger should not be called when no compression is applied
  5227. EXPECT_TRUE(
  5228. pre_compression_body.empty()); // Pre-compression logger not called
  5229. EXPECT_EQ(
  5230. test_content,
  5231. post_compression_body); // Post-compression logger captures final content
  5232. }
  5233. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5234. const std::string test_content =
  5235. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5236. "3456789012345678901234567890";
  5237. std::string pre_compression_body;
  5238. bool pre_logger_called = false;
  5239. // Set only pre-compression logger
  5240. svr_.set_pre_compression_logger(
  5241. [&](const Request & /*req*/, const Response &res) {
  5242. pre_compression_body = res.body;
  5243. pre_logger_called = true;
  5244. });
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "gzip");
  5247. auto res = cli_.Get("/compress", headers);
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5251. // Verify pre-compression logger was called
  5252. EXPECT_TRUE(pre_logger_called);
  5253. EXPECT_EQ(test_content, pre_compression_body);
  5254. }
  5255. TEST(ZstdDecompressor, ChunkedDecompression) {
  5256. std::string data;
  5257. for (size_t i = 0; i < 32 * 1024; ++i) {
  5258. data.push_back(static_cast<char>('a' + i % 26));
  5259. }
  5260. std::string compressed_data;
  5261. {
  5262. httplib::detail::zstd_compressor compressor;
  5263. bool result = compressor.compress(
  5264. data.data(), data.size(),
  5265. /*last=*/true,
  5266. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5267. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5268. compressed_data_size);
  5269. return true;
  5270. });
  5271. ASSERT_TRUE(result);
  5272. }
  5273. std::string decompressed_data;
  5274. {
  5275. httplib::detail::zstd_decompressor decompressor;
  5276. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5277. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5278. size_t chunk_size = 130;
  5279. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5280. chunk_begin += chunk_size) {
  5281. size_t current_chunk_size =
  5282. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5283. bool result = decompressor.decompress(
  5284. compressed_data.data() + chunk_begin, current_chunk_size,
  5285. [&](const char *decompressed_data_chunk,
  5286. size_t decompressed_data_chunk_size) {
  5287. decompressed_data.insert(decompressed_data.size(),
  5288. decompressed_data_chunk,
  5289. decompressed_data_chunk_size);
  5290. return true;
  5291. });
  5292. ASSERT_TRUE(result);
  5293. }
  5294. }
  5295. ASSERT_EQ(data, decompressed_data);
  5296. }
  5297. TEST(ZstdDecompressor, Decompress) {
  5298. std::string original_text = "Compressed with ZSTD";
  5299. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5300. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5301. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5302. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5303. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5304. std::string decompressed_data;
  5305. {
  5306. httplib::detail::zstd_decompressor decompressor;
  5307. bool result = decompressor.decompress(
  5308. compressed_data.data(), compressed_data.size(),
  5309. [&](const char *decompressed_data_chunk,
  5310. size_t decompressed_data_chunk_size) {
  5311. decompressed_data.insert(decompressed_data.size(),
  5312. decompressed_data_chunk,
  5313. decompressed_data_chunk_size);
  5314. return true;
  5315. });
  5316. ASSERT_TRUE(result);
  5317. }
  5318. ASSERT_EQ(original_text, decompressed_data);
  5319. }
  5320. #endif
  5321. // Sends a raw request to a server listening at HOST:PORT.
  5322. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5323. std::string *resp = nullptr) {
  5324. auto error = Error::Success;
  5325. auto client_sock = detail::create_client_socket(
  5326. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5327. /*connection_timeout_sec=*/5, 0,
  5328. /*read_timeout_sec=*/5, 0,
  5329. /*write_timeout_sec=*/5, 0, std::string(), error);
  5330. if (client_sock == INVALID_SOCKET) { return false; }
  5331. auto ret = detail::process_client_socket(
  5332. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5333. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5334. if (req.size() !=
  5335. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5336. return false;
  5337. }
  5338. char buf[512];
  5339. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5340. while (line_reader.getline()) {
  5341. if (resp) { *resp += line_reader.ptr(); }
  5342. }
  5343. return true;
  5344. });
  5345. detail::close_socket(client_sock);
  5346. return ret;
  5347. }
  5348. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5349. Server svr;
  5350. std::string header_value;
  5351. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5352. header_value = req.get_header_value("foo");
  5353. res.set_content("ok", "text/plain");
  5354. });
  5355. thread t = thread([&] { svr.listen(HOST, PORT); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. t.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5363. // like characters are not treated the same - use vertical tab and escape.
  5364. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5365. "foo: \t \v bar \x1B\t \r\n"
  5366. "Connection: close\r\n"
  5367. "\r\n";
  5368. std::string res;
  5369. ASSERT_TRUE(send_request(5, req, &res));
  5370. EXPECT_EQ(header_value, "");
  5371. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5372. }
  5373. // Sends a raw request and verifies that there isn't a crash or exception.
  5374. static void test_raw_request(const std::string &req,
  5375. std::string *out = nullptr) {
  5376. Server svr;
  5377. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5378. res.set_content("ok", "text/plain");
  5379. });
  5380. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5381. res.set_content("ok", "text/plain");
  5382. });
  5383. svr.Get("/header_field_value_check",
  5384. [&](const Request & /*req*/, Response &res) {
  5385. res.set_content("ok", "text/plain");
  5386. });
  5387. // Server read timeout must be longer than the client read timeout for the
  5388. // bug to reproduce, probably to force the server to process a request
  5389. // without a trailing blank line.
  5390. const time_t client_read_timeout_sec = 1;
  5391. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5392. bool listen_thread_ok = false;
  5393. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5394. auto se = detail::scope_exit([&] {
  5395. svr.stop();
  5396. t.join();
  5397. ASSERT_FALSE(svr.is_running());
  5398. EXPECT_TRUE(listen_thread_ok);
  5399. });
  5400. svr.wait_until_ready();
  5401. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5402. }
  5403. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5404. // A certain header line causes an exception if the header property is parsed
  5405. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5406. test_raw_request(
  5407. "GET /hi HTTP/1.1\r\n"
  5408. " : "
  5409. " "
  5410. " ");
  5411. }
  5412. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5413. // A certain header line causes an exception if the header property *name* is
  5414. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5415. // greedy matcher and requires backtracking when there are a lot of ":"
  5416. // characters.
  5417. // This occurs with libc++ but not libstdc++.
  5418. test_raw_request(
  5419. "GET /hi HTTP/1.1\r\n"
  5420. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5421. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5422. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5423. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5424. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5425. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5426. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5427. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5428. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5429. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5430. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5431. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5432. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5433. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5434. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5435. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5436. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5437. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5438. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5439. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5440. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5441. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5442. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5443. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5444. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5445. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5446. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5447. "&&&%%%");
  5448. }
  5449. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5450. // Make sure this doesn't crash the server.
  5451. // In a previous version of the header line regex, the "\r" rendered the line
  5452. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5453. // a new position where the leading white space ended and the field value
  5454. // began.
  5455. // The crash occurs with libc++ but not libstdc++.
  5456. test_raw_request("GET /hi HTTP/1.1\r\n"
  5457. "a:" +
  5458. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5459. "\r\n"
  5460. "\r\n");
  5461. }
  5462. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5463. std::string out;
  5464. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5465. "Content-Type: text/plain\r\n"
  5466. "Transfer-Encoding: chunked\r\n"
  5467. "\r\n"
  5468. "nothex\r\n",
  5469. &out);
  5470. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5471. }
  5472. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5473. std::string out;
  5474. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5475. "Content-Type: text/plain\r\n"
  5476. "Transfer-Encoding: chunked\r\n"
  5477. "\r\n"
  5478. "3\r\n"
  5479. "xyz\r\n"
  5480. "NaN\r\n",
  5481. &out);
  5482. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5483. }
  5484. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5485. std::string out;
  5486. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5487. "Content-Type: text/plain\r\n"
  5488. "Transfer-Encoding: chunked\r\n"
  5489. "\r\n"
  5490. // Length is too large for 64 bits.
  5491. "1ffffffffffffffff\r\n"
  5492. "xyz\r\n",
  5493. &out);
  5494. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5495. }
  5496. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5497. test_raw_request("GET /hi HTTP/1.1\r\n"
  5498. "Content-Type: text/plain\r\n\r");
  5499. }
  5500. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5501. std::string out;
  5502. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5503. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5504. }
  5505. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5506. std::string out;
  5507. std::string request(
  5508. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5509. test_raw_request(request, &out);
  5510. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5511. }
  5512. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5513. std::string out;
  5514. std::string request(
  5515. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5516. test_raw_request(request, &out);
  5517. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5518. }
  5519. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5520. std::string out;
  5521. std::string request(
  5522. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5523. test_raw_request(request, &out);
  5524. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5525. }
  5526. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5527. std::string out;
  5528. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5529. "Test: \r\n\r\n",
  5530. &out);
  5531. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5532. }
  5533. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5534. Server svr;
  5535. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5536. res.set_header("Cache-Control", "no-cache");
  5537. res.set_chunked_content_provider(
  5538. "text/event-stream", [](size_t offset, DataSink &sink) {
  5539. std::string s = "data:";
  5540. s += std::to_string(offset);
  5541. s += "\n\n";
  5542. auto ret = sink.write(s.data(), s.size());
  5543. EXPECT_TRUE(ret);
  5544. std::this_thread::sleep_for(std::chrono::seconds(1));
  5545. return true;
  5546. });
  5547. });
  5548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5549. svr.wait_until_ready();
  5550. Client client(HOST, PORT);
  5551. const Headers headers = {{"Accept", "text/event-stream"}};
  5552. auto get_thread = std::thread([&client, &headers]() {
  5553. auto res = client.Get(
  5554. "/events", headers,
  5555. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5556. });
  5557. auto se = detail::scope_exit([&] {
  5558. svr.stop();
  5559. get_thread.join();
  5560. listen_thread.join();
  5561. ASSERT_FALSE(svr.is_running());
  5562. });
  5563. // Give GET time to get a few messages.
  5564. std::this_thread::sleep_for(std::chrono::seconds(2));
  5565. }
  5566. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5567. httplib::Server svr;
  5568. svr.Post("/hi",
  5569. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5570. res.status = StatusCode::OK_200;
  5571. });
  5572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5573. svr.wait_until_ready();
  5574. Client cli(HOST, PORT);
  5575. auto res = cli.Post("/hi", "data", "text/plain");
  5576. ASSERT_TRUE(res);
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. svr.stop();
  5579. thread.join();
  5580. ASSERT_FALSE(svr.is_running());
  5581. res = cli.Post("/hi", "data", "text/plain");
  5582. ASSERT_FALSE(res);
  5583. }
  5584. TEST(ServerStopTest, ListenFailure) {
  5585. Server svr;
  5586. auto t = thread([&]() {
  5587. auto ret = svr.listen("????", PORT);
  5588. EXPECT_FALSE(ret);
  5589. });
  5590. svr.wait_until_ready();
  5591. svr.stop();
  5592. t.join();
  5593. }
  5594. TEST(ServerStopTest, Decommision) {
  5595. Server svr;
  5596. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5597. for (int i = 0; i < 4; i++) {
  5598. auto is_even = !(i % 2);
  5599. std::thread t{[&] {
  5600. try {
  5601. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5602. if (is_even) {
  5603. throw std::runtime_error("Some thing that happens to go wrong.");
  5604. }
  5605. svr.listen(HOST, PORT);
  5606. } catch (...) { svr.decommission(); }
  5607. }};
  5608. svr.wait_until_ready();
  5609. // Server is up
  5610. {
  5611. Client cli(HOST, PORT);
  5612. auto res = cli.Get("/hi");
  5613. if (is_even) {
  5614. EXPECT_FALSE(res);
  5615. } else {
  5616. EXPECT_TRUE(res);
  5617. EXPECT_EQ("hi...", res->body);
  5618. }
  5619. }
  5620. svr.stop();
  5621. t.join();
  5622. // Server is down...
  5623. {
  5624. Client cli(HOST, PORT);
  5625. auto res = cli.Get("/hi");
  5626. EXPECT_FALSE(res);
  5627. }
  5628. }
  5629. }
  5630. // Helper function for string body upload progress tests
  5631. template <typename SetupHandler, typename ClientCall>
  5632. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5633. ClientCall &&client_call,
  5634. const string &body) {
  5635. Server svr;
  5636. setup_handler(svr);
  5637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5638. auto se = detail::scope_exit([&] {
  5639. svr.stop();
  5640. t.join();
  5641. });
  5642. svr.wait_until_ready();
  5643. Client cli(HOST, PORT);
  5644. vector<uint64_t> progress_values;
  5645. bool progress_called = false;
  5646. auto res =
  5647. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5648. progress_values.push_back(current);
  5649. progress_called = true;
  5650. return true;
  5651. });
  5652. ASSERT_TRUE(res);
  5653. EXPECT_EQ(200, res->status);
  5654. EXPECT_TRUE(progress_called);
  5655. }
  5656. TEST(UploadProgressTest, PostStringBodyBasic) {
  5657. TestStringBodyUploadProgress(
  5658. [](Server &svr) {
  5659. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5660. res.set_content("received", "text/plain");
  5661. });
  5662. },
  5663. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5664. return cli.Post("/test", body, "text/plain", progress_callback);
  5665. },
  5666. "test data for upload progress");
  5667. }
  5668. TEST(UploadProgressTest, PutStringBodyBasic) {
  5669. TestStringBodyUploadProgress(
  5670. [](Server &svr) {
  5671. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5672. res.set_content("put received", "text/plain");
  5673. });
  5674. },
  5675. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5676. return cli.Put("/test", body, "text/plain", progress_callback);
  5677. },
  5678. "put test data for upload progress");
  5679. }
  5680. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5681. TestStringBodyUploadProgress(
  5682. [](Server &svr) {
  5683. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5684. res.set_content("patch received", "text/plain");
  5685. });
  5686. },
  5687. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5688. return cli.Patch("/test", body, "text/plain", progress_callback);
  5689. },
  5690. "patch test data for upload progress");
  5691. }
  5692. // Helper function for content provider upload progress tests
  5693. template <typename SetupHandler, typename ClientCall>
  5694. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5695. ClientCall &&client_call) {
  5696. Server svr;
  5697. setup_handler(svr);
  5698. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5699. auto se = detail::scope_exit([&] {
  5700. svr.stop();
  5701. t.join();
  5702. });
  5703. svr.wait_until_ready();
  5704. Client cli(HOST, PORT);
  5705. vector<uint64_t> progress_values;
  5706. auto res =
  5707. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5708. progress_values.push_back(current);
  5709. return true;
  5710. });
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ(200, res->status);
  5713. EXPECT_FALSE(progress_values.empty());
  5714. }
  5715. TEST(UploadProgressTest, PostContentProviderProgress) {
  5716. TestContentProviderUploadProgress(
  5717. [](Server &svr) {
  5718. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5719. res.set_content("provider received", "text/plain");
  5720. });
  5721. },
  5722. [](Client &cli, UploadProgress progress_callback) {
  5723. return cli.Post(
  5724. "/test", 10,
  5725. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5726. sink.os << "test data";
  5727. return true;
  5728. },
  5729. "text/plain", progress_callback);
  5730. });
  5731. }
  5732. // Helper function for multipart upload progress tests
  5733. template <typename SetupHandler, typename ClientCall>
  5734. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5735. ClientCall &&client_call,
  5736. const string &endpoint) {
  5737. Server svr;
  5738. setup_handler(svr);
  5739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5740. auto se = detail::scope_exit([&] {
  5741. svr.stop();
  5742. t.join();
  5743. });
  5744. svr.wait_until_ready();
  5745. Client cli(HOST, PORT);
  5746. vector<uint64_t> progress_values;
  5747. UploadFormDataItems items = {
  5748. {"field1", "value1", "", ""},
  5749. {"field2", "longer value for progress tracking test", "", ""},
  5750. {"file1", "file content data for upload progress", "test.txt",
  5751. "text/plain"}};
  5752. auto res = client_call(cli, endpoint, items,
  5753. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5754. progress_values.push_back(current);
  5755. return true;
  5756. });
  5757. ASSERT_TRUE(res);
  5758. EXPECT_EQ(200, res->status);
  5759. EXPECT_FALSE(progress_values.empty());
  5760. }
  5761. TEST(UploadProgressTest, PostMultipartProgress) {
  5762. TestMultipartUploadProgress(
  5763. [](Server &svr) {
  5764. svr.Post("/multipart", [](const Request &req, Response &res) {
  5765. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5766. res.set_content("multipart received", "text/plain");
  5767. });
  5768. },
  5769. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5770. UploadProgress progress_callback) {
  5771. return cli.Post(endpoint, items, progress_callback);
  5772. },
  5773. "/multipart");
  5774. }
  5775. // Helper function for basic download progress tests
  5776. template <typename SetupHandler, typename ClientCall>
  5777. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5778. ClientCall &&client_call, const string &endpoint,
  5779. size_t expected_content_size) {
  5780. Server svr;
  5781. setup_handler(svr);
  5782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5783. auto se = detail::scope_exit([&] {
  5784. svr.stop();
  5785. t.join();
  5786. });
  5787. svr.wait_until_ready();
  5788. Client cli(HOST, PORT);
  5789. vector<uint64_t> progress_values;
  5790. auto res = client_call(cli, endpoint,
  5791. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5792. progress_values.push_back(current);
  5793. return true;
  5794. });
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(200, res->status);
  5797. EXPECT_FALSE(progress_values.empty());
  5798. EXPECT_EQ(expected_content_size, res->body.size());
  5799. }
  5800. TEST(DownloadProgressTest, GetBasic) {
  5801. TestBasicDownloadProgress(
  5802. [](Server &svr) {
  5803. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5804. string content(1000, 'D');
  5805. res.set_content(content, "text/plain");
  5806. });
  5807. },
  5808. [](Client &cli, const string &endpoint,
  5809. DownloadProgress progress_callback) {
  5810. return cli.Get(endpoint, progress_callback);
  5811. },
  5812. "/download", 1000u);
  5813. }
  5814. // Helper function for content receiver download progress tests
  5815. template <typename SetupHandler, typename ClientCall>
  5816. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5817. ClientCall &&client_call,
  5818. const string &endpoint,
  5819. size_t expected_content_size) {
  5820. Server svr;
  5821. setup_handler(svr);
  5822. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5823. auto se = detail::scope_exit([&] {
  5824. svr.stop();
  5825. t.join();
  5826. });
  5827. svr.wait_until_ready();
  5828. Client cli(HOST, PORT);
  5829. vector<uint64_t> progress_values;
  5830. string received_body;
  5831. auto res = client_call(
  5832. cli, endpoint,
  5833. [&](const char *data, size_t data_length) -> bool {
  5834. received_body.append(data, data_length);
  5835. return true;
  5836. },
  5837. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5838. progress_values.push_back(current);
  5839. return true;
  5840. });
  5841. ASSERT_TRUE(res);
  5842. EXPECT_EQ(200, res->status);
  5843. EXPECT_FALSE(progress_values.empty());
  5844. EXPECT_EQ(expected_content_size, received_body.size());
  5845. EXPECT_TRUE(res->body.empty());
  5846. }
  5847. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5848. TestContentReceiverDownloadProgress(
  5849. [](Server &svr) {
  5850. svr.Get("/download-receiver",
  5851. [](const Request & /*req*/, Response &res) {
  5852. string content(2000, 'R');
  5853. res.set_content(content, "text/plain");
  5854. });
  5855. },
  5856. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5857. DownloadProgress progress_callback) {
  5858. return cli.Get(endpoint, content_receiver, progress_callback);
  5859. },
  5860. "/download-receiver", 2000u);
  5861. }
  5862. TEST(StreamingTest, NoContentLengthStreaming) {
  5863. Server svr;
  5864. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5865. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5866. if (offset < 6) {
  5867. sink.os << (offset < 3 ? "a" : "b");
  5868. } else {
  5869. sink.done();
  5870. }
  5871. return true;
  5872. });
  5873. });
  5874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5875. auto listen_se = detail::scope_exit([&] {
  5876. svr.stop();
  5877. listen_thread.join();
  5878. ASSERT_FALSE(svr.is_running());
  5879. });
  5880. svr.wait_until_ready();
  5881. Client client(HOST, PORT);
  5882. auto get_thread = std::thread([&client]() {
  5883. std::string s;
  5884. auto res =
  5885. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5886. s += std::string(data, len);
  5887. return true;
  5888. });
  5889. ASSERT_TRUE(res);
  5890. EXPECT_EQ(StatusCode::OK_200, res->status);
  5891. EXPECT_EQ("aaabbb", s);
  5892. });
  5893. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5894. // Give GET time to get a few messages.
  5895. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5896. }
  5897. TEST(MountTest, Unmount) {
  5898. Server svr;
  5899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5900. auto se = detail::scope_exit([&] {
  5901. svr.stop();
  5902. listen_thread.join();
  5903. ASSERT_FALSE(svr.is_running());
  5904. });
  5905. svr.wait_until_ready();
  5906. Client cli("localhost", PORT);
  5907. svr.set_mount_point("/mount2", "./www2");
  5908. auto res = cli.Get("/");
  5909. ASSERT_TRUE(res);
  5910. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5911. res = cli.Get("/mount2/dir/test.html");
  5912. ASSERT_TRUE(res);
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. svr.set_mount_point("/", "./www");
  5915. res = cli.Get("/dir/");
  5916. ASSERT_TRUE(res);
  5917. EXPECT_EQ(StatusCode::OK_200, res->status);
  5918. svr.remove_mount_point("/");
  5919. res = cli.Get("/dir/");
  5920. ASSERT_TRUE(res);
  5921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5922. svr.remove_mount_point("/mount2");
  5923. res = cli.Get("/mount2/dir/test.html");
  5924. ASSERT_TRUE(res);
  5925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5926. }
  5927. TEST(MountTest, Redicect) {
  5928. Server svr;
  5929. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5930. auto se = detail::scope_exit([&] {
  5931. svr.stop();
  5932. listen_thread.join();
  5933. ASSERT_FALSE(svr.is_running());
  5934. });
  5935. svr.set_mount_point("/", "./www");
  5936. svr.wait_until_ready();
  5937. Client cli("localhost", PORT);
  5938. auto res = cli.Get("/dir/");
  5939. ASSERT_TRUE(res);
  5940. EXPECT_EQ(StatusCode::OK_200, res->status);
  5941. res = cli.Get("/dir");
  5942. ASSERT_TRUE(res);
  5943. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5944. res = cli.Get("/file");
  5945. ASSERT_TRUE(res);
  5946. EXPECT_EQ(StatusCode::OK_200, res->status);
  5947. res = cli.Get("/file/");
  5948. ASSERT_TRUE(res);
  5949. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5950. cli.set_follow_location(true);
  5951. res = cli.Get("/dir");
  5952. ASSERT_TRUE(res);
  5953. EXPECT_EQ(StatusCode::OK_200, res->status);
  5954. }
  5955. TEST(MountTest, MultibytesPathName) {
  5956. Server svr;
  5957. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5958. auto se = detail::scope_exit([&] {
  5959. svr.stop();
  5960. listen_thread.join();
  5961. ASSERT_FALSE(svr.is_running());
  5962. });
  5963. svr.set_mount_point("/", "./www");
  5964. svr.wait_until_ready();
  5965. Client cli("localhost", PORT);
  5966. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5970. }
  5971. TEST(KeepAliveTest, ReadTimeout) {
  5972. Server svr;
  5973. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5974. std::this_thread::sleep_for(std::chrono::seconds(2));
  5975. res.set_content("a", "text/plain");
  5976. });
  5977. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5978. res.set_content("b", "text/plain");
  5979. });
  5980. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5981. auto se = detail::scope_exit([&] {
  5982. svr.stop();
  5983. listen_thread.join();
  5984. ASSERT_FALSE(svr.is_running());
  5985. });
  5986. svr.wait_until_ready();
  5987. Client cli("localhost", PORT);
  5988. cli.set_keep_alive(true);
  5989. cli.set_read_timeout(std::chrono::seconds(1));
  5990. auto resa = cli.Get("/a");
  5991. ASSERT_FALSE(resa);
  5992. EXPECT_EQ(Error::Read, resa.error());
  5993. auto resb = cli.Get("/b");
  5994. ASSERT_TRUE(resb);
  5995. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5996. EXPECT_EQ("b", resb->body);
  5997. }
  5998. TEST(KeepAliveTest, MaxCount) {
  5999. size_t keep_alive_max_count = 3;
  6000. Server svr;
  6001. svr.set_keep_alive_max_count(keep_alive_max_count);
  6002. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6003. res.set_content("Hello World!", "text/plain");
  6004. });
  6005. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6006. auto se = detail::scope_exit([&] {
  6007. svr.stop();
  6008. listen_thread.join();
  6009. ASSERT_FALSE(svr.is_running());
  6010. });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. cli.set_keep_alive(true);
  6014. for (size_t i = 0; i < 5; i++) {
  6015. auto result = cli.Get("/hi");
  6016. ASSERT_TRUE(result);
  6017. EXPECT_EQ(StatusCode::OK_200, result->status);
  6018. if (i == keep_alive_max_count - 1) {
  6019. EXPECT_EQ("close", result->get_header_value("Connection"));
  6020. } else {
  6021. EXPECT_FALSE(result->has_header("Connection"));
  6022. }
  6023. }
  6024. }
  6025. TEST(KeepAliveTest, Issue1041) {
  6026. Server svr;
  6027. svr.set_keep_alive_timeout(3);
  6028. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6029. res.set_content("Hello World!", "text/plain");
  6030. });
  6031. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6032. auto se = detail::scope_exit([&] {
  6033. svr.stop();
  6034. listen_thread.join();
  6035. ASSERT_FALSE(svr.is_running());
  6036. });
  6037. svr.wait_until_ready();
  6038. Client cli(HOST, PORT);
  6039. cli.set_keep_alive(true);
  6040. auto result = cli.Get("/hi");
  6041. ASSERT_TRUE(result);
  6042. EXPECT_EQ(StatusCode::OK_200, result->status);
  6043. std::this_thread::sleep_for(std::chrono::seconds(5));
  6044. result = cli.Get("/hi");
  6045. ASSERT_TRUE(result);
  6046. EXPECT_EQ(StatusCode::OK_200, result->status);
  6047. }
  6048. TEST(KeepAliveTest, Issue1959) {
  6049. Server svr;
  6050. svr.set_keep_alive_timeout(5);
  6051. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6052. res.set_content("a", "text/plain");
  6053. });
  6054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6055. auto se = detail::scope_exit([&] {
  6056. if (!svr.is_running()) return;
  6057. svr.stop();
  6058. listen_thread.join();
  6059. ASSERT_FALSE(svr.is_running());
  6060. });
  6061. svr.wait_until_ready();
  6062. Client cli("localhost", PORT);
  6063. cli.set_keep_alive(true);
  6064. using namespace std::chrono;
  6065. auto start = steady_clock::now();
  6066. cli.Get("/a");
  6067. svr.stop();
  6068. listen_thread.join();
  6069. auto end = steady_clock::now();
  6070. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6071. EXPECT_LT(elapsed, 5000);
  6072. }
  6073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6074. TEST(KeepAliveTest, SSLClientReconnection) {
  6075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6076. ASSERT_TRUE(svr.is_valid());
  6077. svr.set_keep_alive_timeout(1);
  6078. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6079. res.set_content("Hello World!", "text/plain");
  6080. });
  6081. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6082. auto se = detail::scope_exit([&] {
  6083. svr.stop();
  6084. listen_thread.join();
  6085. ASSERT_FALSE(svr.is_running());
  6086. });
  6087. svr.wait_until_ready();
  6088. SSLClient cli(HOST, PORT);
  6089. cli.enable_server_certificate_verification(false);
  6090. cli.set_keep_alive(true);
  6091. auto result = cli.Get("/hi");
  6092. ASSERT_TRUE(result);
  6093. EXPECT_EQ(StatusCode::OK_200, result->status);
  6094. result = cli.Get("/hi");
  6095. ASSERT_TRUE(result);
  6096. EXPECT_EQ(StatusCode::OK_200, result->status);
  6097. std::this_thread::sleep_for(std::chrono::seconds(2));
  6098. // Recoonect
  6099. result = cli.Get("/hi");
  6100. ASSERT_TRUE(result);
  6101. EXPECT_EQ(StatusCode::OK_200, result->status);
  6102. result = cli.Get("/hi");
  6103. ASSERT_TRUE(result);
  6104. EXPECT_EQ(StatusCode::OK_200, result->status);
  6105. }
  6106. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6108. ASSERT_TRUE(svr.is_valid());
  6109. svr.set_keep_alive_timeout(1);
  6110. std::string content = "reconnect";
  6111. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6112. res.set_content("Hello World!", "text/plain");
  6113. });
  6114. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6115. auto se = detail::scope_exit([&] {
  6116. svr.stop();
  6117. listen_thread.join();
  6118. ASSERT_FALSE(svr.is_running());
  6119. });
  6120. svr.wait_until_ready();
  6121. SSLClient cli(HOST, PORT);
  6122. cli.enable_server_certificate_verification(false);
  6123. cli.set_keep_alive(true);
  6124. auto result = cli.Post(
  6125. "/hi", content.size(),
  6126. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6127. sink.write(content.c_str(), content.size());
  6128. return true;
  6129. },
  6130. "text/plain");
  6131. ASSERT_TRUE(result);
  6132. EXPECT_EQ(200, result->status);
  6133. std::this_thread::sleep_for(std::chrono::seconds(2));
  6134. // Recoonect
  6135. result = cli.Post(
  6136. "/hi", content.size(),
  6137. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6138. sink.write(content.c_str(), content.size());
  6139. return true;
  6140. },
  6141. "text/plain");
  6142. ASSERT_TRUE(result);
  6143. EXPECT_EQ(200, result->status);
  6144. result = cli.Post(
  6145. "/hi", content.size(),
  6146. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6147. sink.write(content.c_str(), content.size());
  6148. return true;
  6149. },
  6150. "text/plain");
  6151. ASSERT_TRUE(result);
  6152. EXPECT_EQ(200, result->status);
  6153. }
  6154. #endif
  6155. TEST(ClientProblemDetectionTest, ContentProvider) {
  6156. Server svr;
  6157. size_t content_length = 1024 * 1024;
  6158. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6159. res.set_content_provider(
  6160. content_length, "text/plain",
  6161. [&](size_t offset, size_t length, DataSink &sink) {
  6162. auto out_len = std::min(length, static_cast<size_t>(1024));
  6163. std::string out(out_len, '@');
  6164. sink.write(out.data(), out_len);
  6165. return offset < 4096;
  6166. },
  6167. [](bool success) { ASSERT_FALSE(success); });
  6168. });
  6169. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6170. res.set_content_provider(
  6171. 0, "text/plain",
  6172. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6173. EXPECT_TRUE(false);
  6174. return true;
  6175. },
  6176. [](bool success) { ASSERT_FALSE(success); });
  6177. });
  6178. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6179. auto se = detail::scope_exit([&] {
  6180. svr.stop();
  6181. listen_thread.join();
  6182. ASSERT_FALSE(svr.is_running());
  6183. });
  6184. svr.wait_until_ready();
  6185. Client cli("localhost", PORT);
  6186. {
  6187. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6188. size_t /*data_length*/) { return false; });
  6189. ASSERT_FALSE(res);
  6190. }
  6191. {
  6192. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6193. size_t /*data_length*/) { return false; });
  6194. ASSERT_TRUE(res);
  6195. }
  6196. }
  6197. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6198. Server svr;
  6199. svr.set_error_handler([](Request const &, Response &res) -> void {
  6200. res.set_chunked_content_provider(
  6201. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6202. sink.os << "hello";
  6203. sink.os << "world";
  6204. sink.done();
  6205. return true;
  6206. });
  6207. });
  6208. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6209. auto se = detail::scope_exit([&] {
  6210. svr.stop();
  6211. listen_thread.join();
  6212. ASSERT_FALSE(svr.is_running());
  6213. });
  6214. svr.wait_until_ready();
  6215. Client cli("localhost", PORT);
  6216. auto res = cli.Get("/");
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6219. EXPECT_EQ("helloworld", res->body);
  6220. }
  6221. TEST(LongPollingTest, ClientCloseDetection) {
  6222. Server svr;
  6223. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6224. res.set_chunked_content_provider(
  6225. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6226. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6227. sink.os << "hello";
  6228. auto count = 10;
  6229. while (count > 0 && sink.is_writable()) {
  6230. this_thread::sleep_for(chrono::milliseconds(10));
  6231. count--;
  6232. }
  6233. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6234. return true;
  6235. });
  6236. });
  6237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. listen_thread.join();
  6241. ASSERT_FALSE(svr.is_running());
  6242. });
  6243. svr.wait_until_ready();
  6244. Client cli("localhost", PORT);
  6245. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6246. EXPECT_EQ("hello", string(data, data_length));
  6247. return false; // close the socket immediately.
  6248. });
  6249. ASSERT_FALSE(res);
  6250. }
  6251. TEST(GetWithParametersTest, GetWithParameters) {
  6252. Server svr;
  6253. svr.Get("/", [&](const Request &req, Response &) {
  6254. EXPECT_EQ("world", req.get_param_value("hello"));
  6255. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6256. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6257. });
  6258. svr.Get("/params", [&](const Request &req, Response &) {
  6259. EXPECT_EQ("world", req.get_param_value("hello"));
  6260. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6261. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6262. });
  6263. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6264. EXPECT_EQ("resource-id", req.matches[1]);
  6265. EXPECT_EQ("foo", req.get_param_value("param1"));
  6266. EXPECT_EQ("bar", req.get_param_value("param2"));
  6267. });
  6268. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6269. EXPECT_EQ("user-id", req.path_params.at("id"));
  6270. EXPECT_EQ("foo", req.get_param_value("param1"));
  6271. EXPECT_EQ("bar", req.get_param_value("param2"));
  6272. });
  6273. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6274. auto se = detail::scope_exit([&] {
  6275. svr.stop();
  6276. listen_thread.join();
  6277. ASSERT_FALSE(svr.is_running());
  6278. });
  6279. svr.wait_until_ready();
  6280. {
  6281. Client cli(HOST, PORT);
  6282. Params params;
  6283. params.emplace("hello", "world");
  6284. params.emplace("hello2", "world2");
  6285. params.emplace("hello3", "world3");
  6286. auto res = cli.Get("/", params, Headers{});
  6287. ASSERT_TRUE(res);
  6288. EXPECT_EQ(StatusCode::OK_200, res->status);
  6289. }
  6290. {
  6291. Client cli(HOST, PORT);
  6292. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6293. ASSERT_TRUE(res);
  6294. EXPECT_EQ(StatusCode::OK_200, res->status);
  6295. }
  6296. {
  6297. Client cli(HOST, PORT);
  6298. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6299. ASSERT_TRUE(res);
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. }
  6302. {
  6303. Client cli(HOST, PORT);
  6304. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6305. ASSERT_TRUE(res);
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. }
  6308. }
  6309. TEST(GetWithParametersTest, GetWithParameters2) {
  6310. Server svr;
  6311. svr.Get("/", [&](const Request &req, Response &res) {
  6312. auto text = req.get_param_value("hello");
  6313. res.set_content(text, "text/plain");
  6314. });
  6315. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6316. auto se = detail::scope_exit([&] {
  6317. svr.stop();
  6318. listen_thread.join();
  6319. ASSERT_FALSE(svr.is_running());
  6320. });
  6321. svr.wait_until_ready();
  6322. Client cli("localhost", PORT);
  6323. Params params;
  6324. params.emplace("hello", "world");
  6325. std::string body;
  6326. auto res = cli.Get("/", params, Headers{},
  6327. [&](const char *data, size_t data_length) {
  6328. body.append(data, data_length);
  6329. return true;
  6330. });
  6331. ASSERT_TRUE(res);
  6332. EXPECT_EQ(StatusCode::OK_200, res->status);
  6333. EXPECT_EQ("world", body);
  6334. }
  6335. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6336. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6337. auto host = "httpbin.org";
  6338. auto path = std::string{"/range/32"};
  6339. #else
  6340. auto host = "nghttp2.org";
  6341. auto path = std::string{"/httpbin/range/32"};
  6342. #endif
  6343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6344. SSLClient cli(host);
  6345. #else
  6346. Client cli(host);
  6347. #endif
  6348. cli.set_default_headers({make_range_header({{1, 10}})});
  6349. cli.set_connection_timeout(5);
  6350. {
  6351. auto res = cli.Get(path);
  6352. ASSERT_TRUE(res);
  6353. EXPECT_EQ("bcdefghijk", res->body);
  6354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6355. }
  6356. {
  6357. auto res = cli.Get(path);
  6358. ASSERT_TRUE(res);
  6359. EXPECT_EQ("bcdefghijk", res->body);
  6360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6361. }
  6362. }
  6363. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6364. Server svr;
  6365. svr.set_default_headers({{"Hello", "World"}});
  6366. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6367. res.set_content("ok", "text/plain");
  6368. });
  6369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6370. auto se = detail::scope_exit([&] {
  6371. svr.stop();
  6372. listen_thread.join();
  6373. ASSERT_FALSE(svr.is_running());
  6374. });
  6375. svr.wait_until_ready();
  6376. Client cli("localhost", PORT);
  6377. auto res = cli.Get("/");
  6378. ASSERT_TRUE(res);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. EXPECT_EQ("ok", res->body);
  6381. EXPECT_EQ("World", res->get_header_value("Hello"));
  6382. }
  6383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6384. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6386. ASSERT_TRUE(svr.is_valid());
  6387. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6388. std::this_thread::sleep_for(std::chrono::seconds(2));
  6389. res.set_content("a", "text/plain");
  6390. });
  6391. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6392. res.set_content("b", "text/plain");
  6393. });
  6394. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6395. auto se = detail::scope_exit([&] {
  6396. svr.stop();
  6397. listen_thread.join();
  6398. ASSERT_FALSE(svr.is_running());
  6399. });
  6400. svr.wait_until_ready();
  6401. SSLClient cli("localhost", PORT);
  6402. cli.enable_server_certificate_verification(false);
  6403. cli.set_keep_alive(true);
  6404. cli.set_read_timeout(std::chrono::seconds(1));
  6405. auto resa = cli.Get("/a");
  6406. ASSERT_TRUE(!resa);
  6407. EXPECT_EQ(Error::Read, resa.error());
  6408. auto resb = cli.Get("/b");
  6409. ASSERT_TRUE(resb);
  6410. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6411. EXPECT_EQ("b", resb->body);
  6412. }
  6413. #endif
  6414. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6415. protected:
  6416. ServerTestWithAI_PASSIVE()
  6417. : cli_(HOST, PORT)
  6418. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6419. ,
  6420. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6421. #endif
  6422. {
  6423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6424. cli_.enable_server_certificate_verification(false);
  6425. #endif
  6426. }
  6427. virtual void SetUp() {
  6428. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6429. res.set_content("Hello World!", "text/plain");
  6430. });
  6431. t_ = thread(
  6432. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6433. svr_.wait_until_ready();
  6434. }
  6435. virtual void TearDown() {
  6436. svr_.stop();
  6437. t_.join();
  6438. }
  6439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6440. SSLClient cli_;
  6441. SSLServer svr_;
  6442. #else
  6443. Client cli_;
  6444. Server svr_;
  6445. #endif
  6446. thread t_;
  6447. };
  6448. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6449. auto res = cli_.Get("/hi");
  6450. ASSERT_TRUE(res);
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ("Hello World!", res->body);
  6454. }
  6455. class ServerUpDownTest : public ::testing::Test {
  6456. protected:
  6457. ServerUpDownTest() : cli_(HOST, PORT) {}
  6458. virtual void SetUp() {
  6459. t_ = thread([&]() {
  6460. svr_.bind_to_any_port(HOST);
  6461. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6462. ASSERT_TRUE(svr_.listen_after_bind());
  6463. });
  6464. svr_.wait_until_ready();
  6465. }
  6466. virtual void TearDown() {
  6467. svr_.stop();
  6468. t_.join();
  6469. }
  6470. Client cli_;
  6471. Server svr_;
  6472. thread t_;
  6473. };
  6474. TEST_F(ServerUpDownTest, QuickStartStop) {
  6475. // Should not crash, especially when run with
  6476. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6477. }
  6478. class PayloadMaxLengthTest : public ::testing::Test {
  6479. protected:
  6480. PayloadMaxLengthTest()
  6481. : cli_(HOST, PORT)
  6482. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6483. ,
  6484. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6485. #endif
  6486. {
  6487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6488. cli_.enable_server_certificate_verification(false);
  6489. #endif
  6490. }
  6491. virtual void SetUp() {
  6492. svr_.set_payload_max_length(8);
  6493. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6494. res.set_content("test", "text/plain");
  6495. });
  6496. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6497. svr_.wait_until_ready();
  6498. }
  6499. virtual void TearDown() {
  6500. svr_.stop();
  6501. t_.join();
  6502. }
  6503. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6504. SSLClient cli_;
  6505. SSLServer svr_;
  6506. #else
  6507. Client cli_;
  6508. Server svr_;
  6509. #endif
  6510. thread t_;
  6511. };
  6512. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6513. auto res = cli_.Post("/test", "123456789", "text/plain");
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6516. res = cli_.Post("/test", "12345678", "text/plain");
  6517. ASSERT_TRUE(res);
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. }
  6520. TEST(HostAndPortPropertiesTest, NoSSL) {
  6521. httplib::Client cli("www.google.com", 1234);
  6522. ASSERT_EQ("www.google.com", cli.host());
  6523. ASSERT_EQ(1234, cli.port());
  6524. }
  6525. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6526. httplib::Client cli("www.google.com:1234");
  6527. ASSERT_EQ("www.google.com", cli.host());
  6528. ASSERT_EQ(1234, cli.port());
  6529. }
  6530. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6531. TEST(HostAndPortPropertiesTest, SSL) {
  6532. httplib::SSLClient cli("www.google.com");
  6533. ASSERT_EQ("www.google.com", cli.host());
  6534. ASSERT_EQ(443, cli.port());
  6535. }
  6536. #endif
  6537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6538. TEST(SSLClientTest, UpdateCAStore) {
  6539. httplib::SSLClient httplib_client("www.google.com");
  6540. auto ca_store_1 = X509_STORE_new();
  6541. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6542. nullptr);
  6543. httplib_client.set_ca_cert_store(ca_store_1);
  6544. auto ca_store_2 = X509_STORE_new();
  6545. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6546. nullptr);
  6547. httplib_client.set_ca_cert_store(ca_store_2);
  6548. }
  6549. TEST(SSLClientTest, ServerNameIndication_Online) {
  6550. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6551. auto host = "httpbin.org";
  6552. auto path = std::string{"/get"};
  6553. #else
  6554. auto host = "nghttp2.org";
  6555. auto path = std::string{"/httpbin/get"};
  6556. #endif
  6557. SSLClient cli(host, 443);
  6558. auto res = cli.Get(path);
  6559. ASSERT_TRUE(res);
  6560. ASSERT_EQ(StatusCode::OK_200, res->status);
  6561. }
  6562. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6563. // Use a site that will cause SSL verification failure due to self-signed cert
  6564. SSLClient cli("self-signed.badssl.com", 443);
  6565. cli.enable_server_certificate_verification(true);
  6566. auto res = cli.Get("/");
  6567. ASSERT_TRUE(!res);
  6568. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6569. // For SSL server verification errors, ssl_error should be 0, only
  6570. // ssl_openssl_error should be set
  6571. EXPECT_EQ(0, res.ssl_error());
  6572. // Verify OpenSSL error is captured for SSLServerVerification
  6573. // This occurs when SSL_get_verify_result() returns a verification failure
  6574. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6575. res.ssl_openssl_error());
  6576. }
  6577. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6578. // Use a site where hostname doesn't match the certificate
  6579. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6580. SSLClient cli("wrong.host.badssl.com", 443);
  6581. cli.enable_server_certificate_verification(true);
  6582. cli.enable_server_hostname_verification(true);
  6583. auto res = cli.Get("/");
  6584. ASSERT_TRUE(!res);
  6585. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6586. // For SSL hostname verification errors, ssl_error should be 0, only
  6587. // ssl_openssl_error should be set
  6588. EXPECT_EQ(0, res.ssl_error());
  6589. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6590. // This occurs when verify_host() fails due to hostname mismatch
  6591. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6592. res.ssl_openssl_error());
  6593. }
  6594. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6595. Client cli("https://google.com");
  6596. auto res = cli.Get("/");
  6597. ASSERT_TRUE(res);
  6598. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6599. }
  6600. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6601. SSLClient cli("google.com");
  6602. cli.set_ca_cert_path(CA_CERT_FILE);
  6603. auto res = cli.Get("/");
  6604. ASSERT_TRUE(res);
  6605. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6606. }
  6607. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6608. SSLClient cli("google.com");
  6609. cli.enable_server_certificate_verification(true);
  6610. cli.set_ca_cert_path("hello");
  6611. auto res = cli.Get("/");
  6612. ASSERT_TRUE(!res);
  6613. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6614. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6615. // should be set
  6616. EXPECT_EQ(0, res.ssl_error());
  6617. // Verify OpenSSL error is captured for SSLLoadingCerts
  6618. // This error occurs when SSL_CTX_load_verify_locations() fails
  6619. // > openssl errstr 0x80000002
  6620. // error:80000002:system library::No such file or directory
  6621. // > openssl errstr 0xA000126
  6622. // error:0A000126:SSL routines::unexpected eof while reading
  6623. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6624. res.ssl_openssl_error() == 0xA000126);
  6625. }
  6626. TEST(SSLClientTest, ServerCertificateVerification4) {
  6627. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6628. ASSERT_TRUE(svr.is_valid());
  6629. svr.Get("/test", [&](const Request &, Response &res) {
  6630. res.set_content("test", "text/plain");
  6631. svr.stop();
  6632. ASSERT_TRUE(true);
  6633. });
  6634. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6635. auto se = detail::scope_exit([&] {
  6636. t.join();
  6637. ASSERT_FALSE(svr.is_running());
  6638. });
  6639. svr.wait_until_ready();
  6640. SSLClient cli("127.0.0.1", PORT);
  6641. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6642. cli.enable_server_certificate_verification(true);
  6643. cli.set_connection_timeout(30);
  6644. auto res = cli.Get("/test");
  6645. ASSERT_TRUE(res);
  6646. ASSERT_EQ(StatusCode::OK_200, res->status);
  6647. }
  6648. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6649. std::string cert;
  6650. read_file(CA_CERT_FILE, cert);
  6651. SSLClient cli("google.com");
  6652. cli.load_ca_cert_store(cert.data(), cert.size());
  6653. const auto res = cli.Get("/");
  6654. ASSERT_TRUE(res);
  6655. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6656. }
  6657. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6658. // clang-format off
  6659. static constexpr char cert[] =
  6660. "GlobalSign Root CA\n"
  6661. "==================\n"
  6662. "-----BEGIN CERTIFICATE-----\n"
  6663. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6664. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6665. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6666. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6667. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6668. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6669. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6670. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6671. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6672. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6673. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6674. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6675. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6676. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6677. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6678. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6679. "-----END CERTIFICATE-----\n";
  6680. // clang-format on
  6681. SSLClient cli("google.com");
  6682. cli.load_ca_cert_store(cert, sizeof(cert));
  6683. const auto res = cli.Get("/");
  6684. ASSERT_TRUE(res);
  6685. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6686. }
  6687. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6688. SSLClient cli("www.youtube.com");
  6689. cli.set_ca_cert_path(CA_CERT_FILE);
  6690. cli.enable_server_certificate_verification(true);
  6691. cli.set_follow_location(true);
  6692. auto res = cli.Get("/");
  6693. ASSERT_TRUE(res);
  6694. ASSERT_EQ(StatusCode::OK_200, res->status);
  6695. }
  6696. TEST(SSLClientTest, Issue2004_Online) {
  6697. Client client("https://google.com");
  6698. client.set_follow_location(true);
  6699. auto res = client.Get("/");
  6700. ASSERT_TRUE(res);
  6701. ASSERT_EQ(StatusCode::OK_200, res->status);
  6702. auto body = res->body;
  6703. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6704. }
  6705. #if 0
  6706. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6707. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6708. ASSERT_TRUE(cli != nullptr);
  6709. cli->set_address_family(AF_INET6);
  6710. cli->set_interface("en0");
  6711. auto res = cli->Get("/get");
  6712. ASSERT_TRUE(res);
  6713. ASSERT_EQ(StatusCode::OK_200, res->status);
  6714. }
  6715. #endif
  6716. void ClientCertPresent(
  6717. const std::string &client_cert_file,
  6718. const std::string &client_private_key_file,
  6719. const std::string &client_encrypted_private_key_pass = std::string()) {
  6720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6721. CLIENT_CA_CERT_DIR);
  6722. ASSERT_TRUE(svr.is_valid());
  6723. svr.Get("/test", [&](const Request &req, Response &res) {
  6724. res.set_content("test", "text/plain");
  6725. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6726. ASSERT_TRUE(peer_cert != nullptr);
  6727. auto subject_name = X509_get_subject_name(peer_cert);
  6728. ASSERT_TRUE(subject_name != nullptr);
  6729. std::string common_name;
  6730. {
  6731. char name[BUFSIZ];
  6732. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6733. name, sizeof(name));
  6734. common_name.assign(name, static_cast<size_t>(name_len));
  6735. }
  6736. EXPECT_EQ("Common Name", common_name);
  6737. X509_free(peer_cert);
  6738. });
  6739. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6740. auto se = detail::scope_exit([&] {
  6741. svr.stop();
  6742. t.join();
  6743. ASSERT_FALSE(svr.is_running());
  6744. });
  6745. svr.wait_until_ready();
  6746. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6747. client_encrypted_private_key_pass);
  6748. cli.enable_server_certificate_verification(false);
  6749. cli.set_connection_timeout(30);
  6750. auto res = cli.Get("/test");
  6751. ASSERT_TRUE(res);
  6752. ASSERT_EQ(StatusCode::OK_200, res->status);
  6753. }
  6754. TEST(SSLClientServerTest, ClientCertPresent) {
  6755. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6756. }
  6757. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6758. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6759. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6760. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6761. }
  6762. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6763. void MemoryClientCertPresent(
  6764. const std::string &client_cert_file,
  6765. const std::string &client_private_key_file,
  6766. const std::string &client_encrypted_private_key_pass = std::string()) {
  6767. auto f = fopen(SERVER_CERT_FILE, "r+");
  6768. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6769. fclose(f);
  6770. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6771. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6772. fclose(f);
  6773. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6774. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6775. auto client_ca_cert_store = X509_STORE_new();
  6776. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6777. X509_free(client_cert);
  6778. fclose(f);
  6779. f = fopen(client_cert_file.c_str(), "r+");
  6780. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6781. fclose(f);
  6782. f = fopen(client_private_key_file.c_str(), "r+");
  6783. auto client_private_key = PEM_read_PrivateKey(
  6784. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6785. fclose(f);
  6786. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6787. ASSERT_TRUE(svr.is_valid());
  6788. svr.Get("/test", [&](const Request &req, Response &res) {
  6789. res.set_content("test", "text/plain");
  6790. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6791. ASSERT_TRUE(peer_cert != nullptr);
  6792. auto subject_name = X509_get_subject_name(peer_cert);
  6793. ASSERT_TRUE(subject_name != nullptr);
  6794. std::string common_name;
  6795. {
  6796. char name[BUFSIZ];
  6797. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6798. name, sizeof(name));
  6799. common_name.assign(name, static_cast<size_t>(name_len));
  6800. }
  6801. EXPECT_EQ("Common Name", common_name);
  6802. X509_free(peer_cert);
  6803. });
  6804. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6805. auto se = detail::scope_exit([&] {
  6806. svr.stop();
  6807. t.join();
  6808. ASSERT_FALSE(svr.is_running());
  6809. });
  6810. svr.wait_until_ready();
  6811. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6812. client_encrypted_private_key_pass);
  6813. cli.enable_server_certificate_verification(false);
  6814. cli.set_connection_timeout(30);
  6815. auto res = cli.Get("/test");
  6816. ASSERT_TRUE(res);
  6817. ASSERT_EQ(StatusCode::OK_200, res->status);
  6818. X509_free(server_cert);
  6819. EVP_PKEY_free(server_private_key);
  6820. X509_free(client_cert);
  6821. EVP_PKEY_free(client_private_key);
  6822. }
  6823. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6824. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6825. }
  6826. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6827. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6828. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6829. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6830. }
  6831. #endif
  6832. TEST(SSLClientServerTest, ClientCertMissing) {
  6833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6834. CLIENT_CA_CERT_DIR);
  6835. ASSERT_TRUE(svr.is_valid());
  6836. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6838. auto se = detail::scope_exit([&] {
  6839. svr.stop();
  6840. t.join();
  6841. ASSERT_FALSE(svr.is_running());
  6842. });
  6843. svr.wait_until_ready();
  6844. SSLClient cli(HOST, PORT);
  6845. cli.set_connection_timeout(30);
  6846. auto res = cli.Get("/test");
  6847. ASSERT_TRUE(!res);
  6848. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6849. // For SSL server verification errors, ssl_error should be 0, only
  6850. // ssl_openssl_error should be set
  6851. EXPECT_EQ(0, res.ssl_error());
  6852. // Verify OpenSSL error is captured for SSLServerVerification
  6853. // Note: This test may have different error codes depending on the exact
  6854. // verification failure
  6855. EXPECT_NE(0UL, res.ssl_openssl_error());
  6856. }
  6857. TEST(SSLClientServerTest, TrustDirOptional) {
  6858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6859. ASSERT_TRUE(svr.is_valid());
  6860. svr.Get("/test", [&](const Request &, Response &res) {
  6861. res.set_content("test", "text/plain");
  6862. });
  6863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6864. auto se = detail::scope_exit([&] {
  6865. svr.stop();
  6866. t.join();
  6867. ASSERT_FALSE(svr.is_running());
  6868. });
  6869. svr.wait_until_ready();
  6870. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6871. cli.enable_server_certificate_verification(false);
  6872. cli.set_connection_timeout(30);
  6873. auto res = cli.Get("/test");
  6874. ASSERT_TRUE(res);
  6875. ASSERT_EQ(StatusCode::OK_200, res->status);
  6876. }
  6877. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6878. class NoListenSSLServer : public SSLServer {
  6879. public:
  6880. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6881. const char *client_ca_cert_file_path,
  6882. const char *client_ca_cert_dir_path = nullptr)
  6883. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6884. client_ca_cert_dir_path),
  6885. stop_(false) {}
  6886. std::atomic_bool stop_;
  6887. private:
  6888. bool process_and_close_socket(socket_t /*sock*/) override {
  6889. // Don't create SSL context
  6890. while (!stop_.load()) {
  6891. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6892. }
  6893. return true;
  6894. }
  6895. };
  6896. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6897. CLIENT_CA_CERT_FILE);
  6898. ASSERT_TRUE(svr.is_valid());
  6899. svr.Get("/test", [&](const Request &, Response &res) {
  6900. res.set_content("test", "text/plain");
  6901. });
  6902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop_ = true;
  6905. svr.stop();
  6906. t.join();
  6907. ASSERT_FALSE(svr.is_running());
  6908. });
  6909. svr.wait_until_ready();
  6910. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6911. cli.enable_server_certificate_verification(false);
  6912. cli.set_connection_timeout(1);
  6913. auto res = cli.Get("/test");
  6914. ASSERT_TRUE(!res);
  6915. EXPECT_EQ(Error::SSLConnection, res.error());
  6916. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  6917. }
  6918. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6919. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6920. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6921. SSL_CTX_set_options(&ssl_ctx,
  6922. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6923. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6924. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6925. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6926. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6927. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6928. "ECDHE-DSS-AES128-SHA256:"
  6929. "ECDHE-RSA-AES256-SHA256:"
  6930. "ECDHE-DSS-AES256-SHA256:";
  6931. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6932. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6933. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6934. SSL_FILETYPE_PEM) != 1) {
  6935. return false;
  6936. }
  6937. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6938. CLIENT_CA_CERT_DIR);
  6939. SSL_CTX_set_verify(
  6940. &ssl_ctx,
  6941. SSL_VERIFY_PEER |
  6942. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6943. nullptr);
  6944. return true;
  6945. };
  6946. SSLServer svr(setup_ssl_ctx_callback);
  6947. ASSERT_TRUE(svr.is_valid());
  6948. svr.Get("/test", [&](const Request &req, Response &res) {
  6949. res.set_content("test", "text/plain");
  6950. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6951. ASSERT_TRUE(peer_cert != nullptr);
  6952. auto subject_name = X509_get_subject_name(peer_cert);
  6953. ASSERT_TRUE(subject_name != nullptr);
  6954. std::string common_name;
  6955. {
  6956. char name[BUFSIZ];
  6957. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6958. name, sizeof(name));
  6959. common_name.assign(name, static_cast<size_t>(name_len));
  6960. }
  6961. EXPECT_EQ("Common Name", common_name);
  6962. X509_free(peer_cert);
  6963. });
  6964. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6965. auto se = detail::scope_exit([&] {
  6966. svr.stop();
  6967. t.join();
  6968. ASSERT_FALSE(svr.is_running());
  6969. });
  6970. svr.wait_until_ready();
  6971. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6972. cli.enable_server_certificate_verification(false);
  6973. cli.set_connection_timeout(30);
  6974. auto res = cli.Get("/test");
  6975. ASSERT_TRUE(res);
  6976. ASSERT_EQ(StatusCode::OK_200, res->status);
  6977. }
  6978. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6979. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6980. // prepare large data
  6981. std::random_device seed_gen;
  6982. std::mt19937 random(seed_gen());
  6983. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6984. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6985. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6986. // server
  6987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6988. ASSERT_TRUE(svr.is_valid());
  6989. svr.Post("/binary", [&](const Request &req, Response &res) {
  6990. EXPECT_EQ(large_size_byte, req.body.size());
  6991. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6992. res.set_content(req.body, "application/octet-stream");
  6993. });
  6994. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6995. auto se = detail::scope_exit([&] {
  6996. svr.stop();
  6997. listen_thread.join();
  6998. ASSERT_FALSE(svr.is_running());
  6999. });
  7000. svr.wait_until_ready();
  7001. // client POST
  7002. SSLClient cli("localhost", PORT);
  7003. cli.enable_server_certificate_verification(false);
  7004. cli.set_read_timeout(std::chrono::seconds(100));
  7005. cli.set_write_timeout(std::chrono::seconds(100));
  7006. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7007. large_size_byte, "application/octet-stream");
  7008. // compare
  7009. EXPECT_EQ(StatusCode::OK_200, res->status);
  7010. EXPECT_EQ(large_size_byte, res->body.size());
  7011. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7012. }
  7013. #endif
  7014. #ifdef _WIN32
  7015. TEST(CleanupTest, WSACleanup) {
  7016. int ret = WSACleanup();
  7017. ASSERT_EQ(0, ret);
  7018. }
  7019. #endif
  7020. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7021. TEST(NoSSLSupport, SimpleInterface) {
  7022. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7023. }
  7024. #endif
  7025. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7026. TEST(InvalidScheme, SimpleInterface) {
  7027. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7028. }
  7029. #endif
  7030. TEST(NoScheme, SimpleInterface) {
  7031. Client cli("yahoo.com:80");
  7032. ASSERT_TRUE(cli.is_valid());
  7033. }
  7034. TEST(SendAPI, SimpleInterface_Online) {
  7035. Client cli("http://yahoo.com");
  7036. Request req;
  7037. req.method = "GET";
  7038. req.path = "/";
  7039. auto res = cli.send(req);
  7040. ASSERT_TRUE(res);
  7041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7042. }
  7043. TEST(SendAPI, WithParamsInRequest) {
  7044. Server svr;
  7045. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7046. EXPECT_TRUE(req.has_param("test"));
  7047. EXPECT_EQ("test_value", req.get_param_value("test"));
  7048. });
  7049. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7050. auto se = detail::scope_exit([&] {
  7051. svr.stop();
  7052. t.join();
  7053. ASSERT_FALSE(svr.is_running());
  7054. });
  7055. svr.wait_until_ready();
  7056. Client cli(HOST, PORT);
  7057. {
  7058. Request req;
  7059. req.method = "GET";
  7060. req.path = "/";
  7061. req.params.emplace("test", "test_value");
  7062. auto res = cli.send(req);
  7063. ASSERT_TRUE(res);
  7064. }
  7065. {
  7066. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7067. ASSERT_TRUE(res);
  7068. }
  7069. }
  7070. TEST(ClientImplMethods, GetSocketTest) {
  7071. httplib::Server svr;
  7072. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7073. res.status = StatusCode::OK_200;
  7074. });
  7075. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7076. auto se = detail::scope_exit([&] {
  7077. svr.stop();
  7078. thread.join();
  7079. ASSERT_FALSE(svr.is_running());
  7080. });
  7081. svr.wait_until_ready();
  7082. {
  7083. httplib::Client cli("http://127.0.0.1:3333");
  7084. cli.set_keep_alive(true);
  7085. // Use the behavior of cpp-httplib of opening the connection
  7086. // only when the first request happens. If that changes,
  7087. // this test would be obsolete.
  7088. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7089. // This also implicitly tests the server. But other tests would fail much
  7090. // earlier than this one to be considered.
  7091. auto res = cli.Get("/");
  7092. ASSERT_TRUE(res);
  7093. EXPECT_EQ(StatusCode::OK_200, res->status);
  7094. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7095. }
  7096. }
  7097. // Disabled due to out-of-memory problem on GitHub Actions
  7098. #ifdef _WIN64
  7099. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7100. // allocate content size larger than 2GB in memory
  7101. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7102. char *content = (char *)malloc(content_size);
  7103. ASSERT_TRUE(content);
  7104. Server svr;
  7105. svr.Get("/foo",
  7106. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7107. res.set_content(content, content_size, "application/octet-stream");
  7108. });
  7109. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7110. auto se = detail::scope_exit([&] {
  7111. svr.stop();
  7112. listen_thread.join();
  7113. if (content) free(content);
  7114. ASSERT_FALSE(svr.is_running());
  7115. });
  7116. svr.wait_until_ready();
  7117. Client cli(HOST, PORT);
  7118. auto res = cli.Get("/foo");
  7119. ASSERT_TRUE(res);
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. EXPECT_EQ(content_size, res->body.length());
  7122. }
  7123. #endif
  7124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7125. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7126. Client cli("http://yahoo.com");
  7127. auto res = cli.Get("/");
  7128. ASSERT_TRUE(res);
  7129. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7130. cli.set_follow_location(true);
  7131. res = cli.Get("/");
  7132. ASSERT_TRUE(res);
  7133. EXPECT_EQ(StatusCode::OK_200, res->status);
  7134. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7135. }
  7136. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7137. Client cli("https://yahoo.com");
  7138. auto res = cli.Get("/");
  7139. ASSERT_TRUE(res);
  7140. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7141. cli.set_follow_location(true);
  7142. res = cli.Get("/");
  7143. ASSERT_TRUE(res);
  7144. EXPECT_EQ(StatusCode::OK_200, res->status);
  7145. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7146. }
  7147. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7148. Client cli("https://yahoo.com");
  7149. auto res = cli.Get("/");
  7150. ASSERT_TRUE(res);
  7151. ASSERT_FALSE(!res);
  7152. ASSERT_TRUE(res);
  7153. ASSERT_FALSE(res == nullptr);
  7154. ASSERT_TRUE(res != nullptr);
  7155. EXPECT_EQ(Error::Success, res.error());
  7156. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7157. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7158. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7159. cli.set_follow_location(true);
  7160. res = cli.Get("/");
  7161. ASSERT_TRUE(res);
  7162. EXPECT_EQ(Error::Success, res.error());
  7163. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7164. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7165. EXPECT_EQ(StatusCode::OK_200, res->status);
  7166. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7167. }
  7168. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7169. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7170. Client cli("https://cdnjs.cloudflare.com");
  7171. auto res =
  7172. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7173. ASSERT_TRUE(res);
  7174. EXPECT_EQ(StatusCode::OK_200, res->status);
  7175. EXPECT_EQ(287630U, res->body.size());
  7176. EXPECT_EQ("application/javascript; charset=utf-8",
  7177. res->get_header_value("Content-Type"));
  7178. }
  7179. #endif
  7180. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7181. #undef REDIR_HOST // Silence compiler warning
  7182. #define REDIR_HOST "https://httpbingo.org"
  7183. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7184. Client cli(REDIR_HOST);
  7185. cli.set_follow_location(true);
  7186. auto res =
  7187. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7188. ASSERT_TRUE(res);
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. }
  7191. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7192. Client cli(REDIR_HOST);
  7193. cli.set_follow_location(true);
  7194. Params params;
  7195. params.emplace("url", "http://example.com");
  7196. params.emplace("status_code", "302");
  7197. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7202. Client cli(REDIR_HOST);
  7203. cli.set_follow_location(true);
  7204. Params params;
  7205. params.emplace("url", "http://example.com");
  7206. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7207. ASSERT_TRUE(res);
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. TEST(HttpToHttpsRedirectTest, CertFile) {
  7211. Server svr;
  7212. ASSERT_TRUE(svr.is_valid());
  7213. svr.Get("/index", [&](const Request &, Response &res) {
  7214. res.set_redirect("https://127.0.0.1:1235/index");
  7215. svr.stop();
  7216. });
  7217. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7218. ASSERT_TRUE(ssl_svr.is_valid());
  7219. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7220. res.set_content("test", "text/plain");
  7221. ssl_svr.stop();
  7222. });
  7223. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7224. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7225. auto se = detail::scope_exit([&] {
  7226. t2.join();
  7227. t.join();
  7228. ASSERT_FALSE(svr.is_running());
  7229. });
  7230. svr.wait_until_ready();
  7231. ssl_svr.wait_until_ready();
  7232. Client cli("127.0.0.1", PORT);
  7233. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7234. cli.enable_server_certificate_verification(true);
  7235. cli.set_follow_location(true);
  7236. cli.set_connection_timeout(30);
  7237. auto res = cli.Get("/index");
  7238. ASSERT_TRUE(res);
  7239. ASSERT_EQ(StatusCode::OK_200, res->status);
  7240. }
  7241. TEST(MultipartFormDataTest, LargeData) {
  7242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7243. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7244. const ContentReader &content_reader) {
  7245. if (req.is_multipart_form_data()) {
  7246. std::vector<FormData> items;
  7247. content_reader(
  7248. [&](const FormData &file) {
  7249. items.push_back(file);
  7250. return true;
  7251. },
  7252. [&](const char *data, size_t data_length) {
  7253. items.back().content.append(data, data_length);
  7254. return true;
  7255. });
  7256. EXPECT_TRUE(std::string(items[0].name) == "document");
  7257. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7258. EXPECT_TRUE(items[0].filename == "2MB_data");
  7259. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7260. EXPECT_TRUE(items[1].name == "hello");
  7261. EXPECT_TRUE(items[1].content == "world");
  7262. EXPECT_TRUE(items[1].filename == "");
  7263. EXPECT_TRUE(items[1].content_type == "");
  7264. } else {
  7265. std::string body;
  7266. content_reader([&](const char *data, size_t data_length) {
  7267. body.append(data, data_length);
  7268. return true;
  7269. });
  7270. }
  7271. });
  7272. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7273. auto se = detail::scope_exit([&] {
  7274. svr.stop();
  7275. t.join();
  7276. ASSERT_FALSE(svr.is_running());
  7277. });
  7278. svr.wait_until_ready();
  7279. {
  7280. std::string data(1024 * 1024 * 2, '.');
  7281. std::stringstream buffer;
  7282. buffer << data;
  7283. Client cli("https://localhost:8080");
  7284. cli.enable_server_certificate_verification(false);
  7285. UploadFormDataItems items{
  7286. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7287. {"hello", "world", "", ""},
  7288. };
  7289. auto res = cli.Post("/post", items);
  7290. ASSERT_TRUE(res);
  7291. ASSERT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. }
  7294. TEST(MultipartFormDataTest, DataProviderItems) {
  7295. std::random_device seed_gen;
  7296. std::mt19937 random(seed_gen());
  7297. std::string rand1;
  7298. rand1.resize(1000);
  7299. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7300. std::string rand2;
  7301. rand2.resize(3000);
  7302. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7304. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7305. const ContentReader &content_reader) {
  7306. ASSERT_FALSE(req.is_multipart_form_data());
  7307. std::string body;
  7308. content_reader([&](const char *data, size_t data_length) {
  7309. body.append(data, data_length);
  7310. return true;
  7311. });
  7312. EXPECT_EQ(body, "");
  7313. });
  7314. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7315. const ContentReader &content_reader) {
  7316. ASSERT_TRUE(req.is_multipart_form_data());
  7317. std::vector<FormData> items;
  7318. content_reader(
  7319. [&](const FormData &file) {
  7320. items.push_back(file);
  7321. return true;
  7322. },
  7323. [&](const char *data, size_t data_length) {
  7324. items.back().content.append(data, data_length);
  7325. return true;
  7326. });
  7327. ASSERT_TRUE(items.size() == 2);
  7328. EXPECT_EQ(std::string(items[0].name), "name1");
  7329. EXPECT_EQ(items[0].content, "Testing123");
  7330. EXPECT_EQ(items[0].filename, "filename1");
  7331. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7332. EXPECT_EQ(items[1].name, "name2");
  7333. EXPECT_EQ(items[1].content, "Testing456");
  7334. EXPECT_EQ(items[1].filename, "");
  7335. EXPECT_EQ(items[1].content_type, "");
  7336. });
  7337. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7338. const ContentReader &content_reader) {
  7339. ASSERT_TRUE(req.is_multipart_form_data());
  7340. std::vector<FormData> items;
  7341. content_reader(
  7342. [&](const FormData &file) {
  7343. items.push_back(file);
  7344. return true;
  7345. },
  7346. [&](const char *data, size_t data_length) {
  7347. items.back().content.append(data, data_length);
  7348. return true;
  7349. });
  7350. ASSERT_TRUE(items.size() == 2);
  7351. EXPECT_EQ(items[0].name, "name3");
  7352. EXPECT_EQ(items[0].content, rand1);
  7353. EXPECT_EQ(items[0].filename, "filename3");
  7354. EXPECT_EQ(items[0].content_type, "");
  7355. EXPECT_EQ(items[1].name, "name4");
  7356. EXPECT_EQ(items[1].content, rand2);
  7357. EXPECT_EQ(items[1].filename, "filename4");
  7358. EXPECT_EQ(items[1].content_type, "");
  7359. });
  7360. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7361. const ContentReader &content_reader) {
  7362. ASSERT_TRUE(req.is_multipart_form_data());
  7363. std::vector<FormData> items;
  7364. content_reader(
  7365. [&](const FormData &file) {
  7366. items.push_back(file);
  7367. return true;
  7368. },
  7369. [&](const char *data, size_t data_length) {
  7370. items.back().content.append(data, data_length);
  7371. return true;
  7372. });
  7373. ASSERT_TRUE(items.size() == 4);
  7374. EXPECT_EQ(std::string(items[0].name), "name1");
  7375. EXPECT_EQ(items[0].content, "Testing123");
  7376. EXPECT_EQ(items[0].filename, "filename1");
  7377. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7378. EXPECT_EQ(items[1].name, "name2");
  7379. EXPECT_EQ(items[1].content, "Testing456");
  7380. EXPECT_EQ(items[1].filename, "");
  7381. EXPECT_EQ(items[1].content_type, "");
  7382. EXPECT_EQ(items[2].name, "name3");
  7383. EXPECT_EQ(items[2].content, rand1);
  7384. EXPECT_EQ(items[2].filename, "filename3");
  7385. EXPECT_EQ(items[2].content_type, "");
  7386. EXPECT_EQ(items[3].name, "name4");
  7387. EXPECT_EQ(items[3].content, rand2);
  7388. EXPECT_EQ(items[3].filename, "filename4");
  7389. EXPECT_EQ(items[3].content_type, "");
  7390. });
  7391. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7392. auto se = detail::scope_exit([&] {
  7393. svr.stop();
  7394. t.join();
  7395. ASSERT_FALSE(svr.is_running());
  7396. });
  7397. svr.wait_until_ready();
  7398. {
  7399. Client cli("https://localhost:8080");
  7400. cli.enable_server_certificate_verification(false);
  7401. UploadFormDataItems items{
  7402. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7403. {"name2", "Testing456", "", ""}, // not a file
  7404. };
  7405. {
  7406. auto res = cli.Post("/post-none", {}, {}, {});
  7407. ASSERT_TRUE(res);
  7408. ASSERT_EQ(StatusCode::OK_200, res->status);
  7409. }
  7410. FormDataProviderItems providers;
  7411. {
  7412. auto res =
  7413. cli.Post("/post-items", {}, items, providers); // empty providers
  7414. ASSERT_TRUE(res);
  7415. ASSERT_EQ(StatusCode::OK_200, res->status);
  7416. }
  7417. providers.push_back({"name3",
  7418. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7419. // test the offset is given correctly at each step
  7420. if (!offset)
  7421. sink.os.write(rand1.data(), 30);
  7422. else if (offset == 30)
  7423. sink.os.write(rand1.data() + 30, 300);
  7424. else if (offset == 330)
  7425. sink.os.write(rand1.data() + 330, 670);
  7426. else if (offset == rand1.size())
  7427. sink.done();
  7428. return true;
  7429. },
  7430. "filename3",
  7431. {}});
  7432. providers.push_back({"name4",
  7433. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7434. // test the offset is given correctly at each step
  7435. if (!offset)
  7436. sink.os.write(rand2.data(), 2000);
  7437. else if (offset == 2000)
  7438. sink.os.write(rand2.data() + 2000, 1);
  7439. else if (offset == 2001)
  7440. sink.os.write(rand2.data() + 2001, 999);
  7441. else if (offset == rand2.size())
  7442. sink.done();
  7443. return true;
  7444. },
  7445. "filename4",
  7446. {}});
  7447. {
  7448. auto res = cli.Post("/post-providers", {}, {}, providers);
  7449. ASSERT_TRUE(res);
  7450. ASSERT_EQ(StatusCode::OK_200, res->status);
  7451. }
  7452. {
  7453. auto res = cli.Post("/post-both", {}, items, providers);
  7454. ASSERT_TRUE(res);
  7455. ASSERT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. }
  7458. }
  7459. TEST(MultipartFormDataTest, BadHeader) {
  7460. Server svr;
  7461. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7462. res.set_content("ok", "text/plain");
  7463. });
  7464. thread t = thread([&] { svr.listen(HOST, PORT); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. t.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. const std::string body =
  7472. "This is the preamble. It is to be ignored, though it\r\n"
  7473. "is a handy place for composition agents to include an\r\n"
  7474. "explanatory note to non-MIME conformant readers.\r\n"
  7475. "\r\n"
  7476. "\r\n"
  7477. "--simple boundary\r\n"
  7478. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7479. ": BAD...\r\n"
  7480. "\r\n"
  7481. "value1\r\n"
  7482. "--simple boundary\r\n"
  7483. "Content-Disposition: form-data; name=\"field2\"; "
  7484. "filename=\"example.txt\"\r\n"
  7485. "\r\n"
  7486. "value2\r\n"
  7487. "--simple boundary--\r\n"
  7488. "This is the epilogue. It is also to be ignored.\r\n";
  7489. std::string content_type =
  7490. R"(multipart/form-data; boundary="simple boundary")";
  7491. Client cli(HOST, PORT);
  7492. auto res = cli.Post("/post", body, content_type.c_str());
  7493. ASSERT_TRUE(res);
  7494. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7495. }
  7496. TEST(MultipartFormDataTest, WithPreamble) {
  7497. Server svr;
  7498. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7499. res.set_content("ok", "text/plain");
  7500. });
  7501. thread t = thread([&] { svr.listen(HOST, PORT); });
  7502. auto se = detail::scope_exit([&] {
  7503. svr.stop();
  7504. t.join();
  7505. ASSERT_FALSE(svr.is_running());
  7506. });
  7507. svr.wait_until_ready();
  7508. const std::string body =
  7509. "This is the preamble. It is to be ignored, though it\r\n"
  7510. "is a handy place for composition agents to include an\r\n"
  7511. "explanatory note to non-MIME conformant readers.\r\n"
  7512. "\r\n"
  7513. "\r\n"
  7514. "--simple boundary\r\n"
  7515. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7516. "\r\n"
  7517. "value1\r\n"
  7518. "--simple boundary\r\n"
  7519. "Content-Disposition: form-data; name=\"field2\"; "
  7520. "filename=\"example.txt\"\r\n"
  7521. "\r\n"
  7522. "value2\r\n"
  7523. "--simple boundary--\r\n"
  7524. "This is the epilogue. It is also to be ignored.\r\n";
  7525. std::string content_type =
  7526. R"(multipart/form-data; boundary="simple boundary")";
  7527. Client cli(HOST, PORT);
  7528. auto res = cli.Post("/post", body, content_type.c_str());
  7529. ASSERT_TRUE(res);
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. }
  7532. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7534. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7535. const ContentReader &content_reader) {
  7536. if (req.is_multipart_form_data()) {
  7537. std::vector<FormData> items;
  7538. content_reader(
  7539. [&](const FormData &file) {
  7540. items.push_back(file);
  7541. return true;
  7542. },
  7543. [&](const char *data, size_t data_length) {
  7544. items.back().content.append(data, data_length);
  7545. return true;
  7546. });
  7547. EXPECT_TRUE(std::string(items[0].name) == "document");
  7548. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7549. EXPECT_TRUE(items[0].filename == "2MB_data");
  7550. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7551. EXPECT_TRUE(items[1].name == "hello");
  7552. EXPECT_TRUE(items[1].content == "world");
  7553. EXPECT_TRUE(items[1].filename == "");
  7554. EXPECT_TRUE(items[1].content_type == "");
  7555. } else {
  7556. std::string body;
  7557. content_reader([&](const char *data, size_t data_length) {
  7558. body.append(data, data_length);
  7559. return true;
  7560. });
  7561. }
  7562. });
  7563. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7564. auto se = detail::scope_exit([&] {
  7565. svr.stop();
  7566. t.join();
  7567. ASSERT_FALSE(svr.is_running());
  7568. });
  7569. svr.wait_until_ready();
  7570. {
  7571. std::string data(1024 * 1024 * 2, '.');
  7572. std::stringstream buffer;
  7573. buffer << data;
  7574. Client cli("https://localhost:8080");
  7575. cli.enable_server_certificate_verification(false);
  7576. UploadFormDataItems items{
  7577. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7578. {"hello", "world", "", ""},
  7579. };
  7580. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7581. ASSERT_TRUE(res);
  7582. ASSERT_EQ(StatusCode::OK_200, res->status);
  7583. }
  7584. }
  7585. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7586. std::string data(1024 * 1024 * 2, '&');
  7587. std::stringstream buffer;
  7588. buffer << data;
  7589. Client cli("https://localhost:8080");
  7590. UploadFormDataItems items{
  7591. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7592. {"hello", "world", "", ""},
  7593. };
  7594. for (const char &c : " \t\r\n") {
  7595. auto res =
  7596. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7597. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7598. ASSERT_FALSE(res);
  7599. }
  7600. }
  7601. TEST(MultipartFormDataTest, PutFormData) {
  7602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7603. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7604. const ContentReader &content_reader) {
  7605. if (req.is_multipart_form_data()) {
  7606. std::vector<FormData> items;
  7607. content_reader(
  7608. [&](const FormData &file) {
  7609. items.push_back(file);
  7610. return true;
  7611. },
  7612. [&](const char *data, size_t data_length) {
  7613. items.back().content.append(data, data_length);
  7614. return true;
  7615. });
  7616. EXPECT_TRUE(std::string(items[0].name) == "document");
  7617. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7618. EXPECT_TRUE(items[0].filename == "2MB_data");
  7619. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7620. EXPECT_TRUE(items[1].name == "hello");
  7621. EXPECT_TRUE(items[1].content == "world");
  7622. EXPECT_TRUE(items[1].filename == "");
  7623. EXPECT_TRUE(items[1].content_type == "");
  7624. } else {
  7625. std::string body;
  7626. content_reader([&](const char *data, size_t data_length) {
  7627. body.append(data, data_length);
  7628. return true;
  7629. });
  7630. }
  7631. });
  7632. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7633. auto se = detail::scope_exit([&] {
  7634. svr.stop();
  7635. t.join();
  7636. ASSERT_FALSE(svr.is_running());
  7637. });
  7638. svr.wait_until_ready();
  7639. {
  7640. std::string data(1024 * 1024 * 2, '&');
  7641. std::stringstream buffer;
  7642. buffer << data;
  7643. Client cli("https://localhost:8080");
  7644. cli.enable_server_certificate_verification(false);
  7645. UploadFormDataItems items{
  7646. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7647. {"hello", "world", "", ""},
  7648. };
  7649. auto res = cli.Put("/put", items);
  7650. ASSERT_TRUE(res);
  7651. ASSERT_EQ(StatusCode::OK_200, res->status);
  7652. }
  7653. }
  7654. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7656. svr.Put("/put_customboundary",
  7657. [&](const Request &req, const Response & /*res*/,
  7658. const ContentReader &content_reader) {
  7659. if (req.is_multipart_form_data()) {
  7660. std::vector<FormData> items;
  7661. content_reader(
  7662. [&](const FormData &file) {
  7663. items.push_back(file);
  7664. return true;
  7665. },
  7666. [&](const char *data, size_t data_length) {
  7667. items.back().content.append(data, data_length);
  7668. return true;
  7669. });
  7670. EXPECT_TRUE(std::string(items[0].name) == "document");
  7671. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7672. EXPECT_TRUE(items[0].filename == "2MB_data");
  7673. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7674. EXPECT_TRUE(items[1].name == "hello");
  7675. EXPECT_TRUE(items[1].content == "world");
  7676. EXPECT_TRUE(items[1].filename == "");
  7677. EXPECT_TRUE(items[1].content_type == "");
  7678. } else {
  7679. std::string body;
  7680. content_reader([&](const char *data, size_t data_length) {
  7681. body.append(data, data_length);
  7682. return true;
  7683. });
  7684. }
  7685. });
  7686. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7687. auto se = detail::scope_exit([&] {
  7688. svr.stop();
  7689. t.join();
  7690. ASSERT_FALSE(svr.is_running());
  7691. });
  7692. svr.wait_until_ready();
  7693. {
  7694. std::string data(1024 * 1024 * 2, '&');
  7695. std::stringstream buffer;
  7696. buffer << data;
  7697. Client cli("https://localhost:8080");
  7698. cli.enable_server_certificate_verification(false);
  7699. UploadFormDataItems items{
  7700. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7701. {"hello", "world", "", ""},
  7702. };
  7703. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7704. ASSERT_TRUE(res);
  7705. ASSERT_EQ(StatusCode::OK_200, res->status);
  7706. }
  7707. }
  7708. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7709. std::string data(1024 * 1024 * 2, '&');
  7710. std::stringstream buffer;
  7711. buffer << data;
  7712. Client cli("https://localhost:8080");
  7713. cli.enable_server_certificate_verification(false);
  7714. UploadFormDataItems items{
  7715. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7716. {"hello", "world", "", ""},
  7717. };
  7718. for (const char &c : " \t\r\n") {
  7719. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7720. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7721. ASSERT_FALSE(res);
  7722. }
  7723. }
  7724. TEST(MultipartFormDataTest, AlternateFilename) {
  7725. auto handled = false;
  7726. Server svr;
  7727. svr.Post("/test", [&](const Request &req, Response &res) {
  7728. ASSERT_EQ(2u, req.form.files.size());
  7729. ASSERT_EQ(1u, req.form.fields.size());
  7730. // Test files
  7731. const auto &file1 = req.form.get_file("file1");
  7732. ASSERT_EQ("file1", file1.name);
  7733. ASSERT_EQ("A.txt", file1.filename);
  7734. ASSERT_EQ("text/plain", file1.content_type);
  7735. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  7736. const auto &file2 = req.form.get_file("file2");
  7737. ASSERT_EQ("file2", file2.name);
  7738. ASSERT_EQ("a.html", file2.filename);
  7739. ASSERT_EQ("text/html", file2.content_type);
  7740. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7741. file2.content);
  7742. // Test text field
  7743. const auto &text = req.form.get_field("text");
  7744. ASSERT_EQ("text default", text);
  7745. res.set_content("ok", "text/plain");
  7746. handled = true;
  7747. });
  7748. thread t = thread([&] { svr.listen(HOST, PORT); });
  7749. auto se = detail::scope_exit([&] {
  7750. svr.stop();
  7751. t.join();
  7752. ASSERT_FALSE(svr.is_running());
  7753. ASSERT_TRUE(handled);
  7754. });
  7755. svr.wait_until_ready();
  7756. auto req = "POST /test HTTP/1.1\r\n"
  7757. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7758. "Content-Length: 399\r\n"
  7759. "\r\n"
  7760. "----------\r\n"
  7761. "Content-Disposition: form-data; name=\"text\"\r\n"
  7762. "\r\n"
  7763. "text default\r\n"
  7764. "----------\r\n"
  7765. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7766. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7767. "Content-Type: text/plain\r\n"
  7768. "\r\n"
  7769. "Content of a.txt.\r\n"
  7770. "\r\n"
  7771. "----------\r\n"
  7772. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7773. "\"a.html\"\r\n"
  7774. "Content-Type: text/html\r\n"
  7775. "\r\n"
  7776. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7777. "\r\n"
  7778. "------------\r\n";
  7779. ASSERT_TRUE(send_request(1, req));
  7780. }
  7781. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7782. auto handled = false;
  7783. Server svr;
  7784. svr.Post("/test", [&](const Request &req, Response &) {
  7785. ASSERT_EQ(2u, req.form.fields.size());
  7786. const auto &text1 = req.form.get_field("text1");
  7787. ASSERT_EQ("text1", text1);
  7788. const auto &text2 = req.form.get_field("text2");
  7789. ASSERT_EQ("text2", text2);
  7790. handled = true;
  7791. });
  7792. thread t = thread([&] { svr.listen(HOST, PORT); });
  7793. auto se = detail::scope_exit([&] {
  7794. svr.stop();
  7795. t.join();
  7796. ASSERT_FALSE(svr.is_running());
  7797. ASSERT_TRUE(handled);
  7798. });
  7799. svr.wait_until_ready();
  7800. auto req = "POST /test HTTP/1.1\r\n"
  7801. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7802. "Content-Length: 146\r\n"
  7803. "\r\n----------\r\n"
  7804. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7805. "\r\n"
  7806. "text1"
  7807. "\r\n----------\r\n"
  7808. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7809. "\r\n"
  7810. "text2"
  7811. "\r\n------------";
  7812. std::string response;
  7813. ASSERT_TRUE(send_request(1, req, &response));
  7814. ASSERT_EQ("200", response.substr(9, 3));
  7815. }
  7816. TEST(MultipartFormDataTest, ContentLength) {
  7817. auto handled = false;
  7818. Server svr;
  7819. svr.Post("/test", [&](const Request &req, Response &) {
  7820. ASSERT_EQ(2u, req.form.fields.size());
  7821. const auto &text1 = req.form.get_field("text1");
  7822. ASSERT_EQ("text1", text1);
  7823. const auto &text2 = req.form.get_field("text2");
  7824. ASSERT_EQ("text2", text2);
  7825. handled = true;
  7826. });
  7827. thread t = thread([&] { svr.listen(HOST, PORT); });
  7828. auto se = detail::scope_exit([&] {
  7829. svr.stop();
  7830. t.join();
  7831. ASSERT_FALSE(svr.is_running());
  7832. ASSERT_TRUE(handled);
  7833. });
  7834. svr.wait_until_ready();
  7835. auto req = "POST /test HTTP/1.1\r\n"
  7836. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7837. "Content-Length: 167\r\n"
  7838. "\r\n----------\r\n"
  7839. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7840. "Content-Length: 5\r\n"
  7841. "\r\n"
  7842. "text1"
  7843. "\r\n----------\r\n"
  7844. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7845. "\r\n"
  7846. "text2"
  7847. "\r\n------------\r\n";
  7848. std::string response;
  7849. ASSERT_TRUE(send_request(1, req, &response));
  7850. ASSERT_EQ("200", response.substr(9, 3));
  7851. }
  7852. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7853. auto handled = false;
  7854. Server svr;
  7855. svr.Post("/test", [&](const Request &req, Response &) {
  7856. ASSERT_EQ(2u, req.form.fields.size());
  7857. const auto &text1 = req.form.get_field("text1");
  7858. ASSERT_EQ("text1", text1);
  7859. // TODO: Add header access for text fields if needed
  7860. const auto &text2 = req.form.get_field("text2");
  7861. ASSERT_EQ("text2", text2);
  7862. // TODO: Header access for text fields needs to be implemented
  7863. // auto &headers = it->second.headers;
  7864. // ASSERT_EQ(3U, headers.size());
  7865. // auto custom_header = headers.find("x-whatever");
  7866. // ASSERT_TRUE(custom_header != headers.end());
  7867. // ASSERT_NE("customvalue", custom_header->second);
  7868. // ASSERT_EQ("CustomValue", custom_header->second);
  7869. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7870. handled = true;
  7871. });
  7872. thread t = thread([&] { svr.listen(HOST, PORT); });
  7873. auto se = detail::scope_exit([&] {
  7874. svr.stop();
  7875. t.join();
  7876. ASSERT_FALSE(svr.is_running());
  7877. ASSERT_TRUE(handled);
  7878. });
  7879. svr.wait_until_ready();
  7880. auto req = "POST /test HTTP/1.1\r\n"
  7881. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7882. "Content-Length: 232\r\n"
  7883. "\r\n----------\r\n"
  7884. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7885. "Content-Length: 5\r\n"
  7886. "X-Test: 1\r\n"
  7887. "\r\n"
  7888. "text1"
  7889. "\r\n----------\r\n"
  7890. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7891. "Content-Type: text/plain\r\n"
  7892. "X-Whatever: CustomValue\r\n"
  7893. "\r\n"
  7894. "text2"
  7895. "\r\n------------\r\n"
  7896. "That should be disregarded. Not even read";
  7897. std::string response;
  7898. ASSERT_TRUE(send_request(1, req, &response));
  7899. ASSERT_EQ("200", response.substr(9, 3));
  7900. }
  7901. #endif
  7902. TEST(MultipartFormDataTest, LargeHeader) {
  7903. auto handled = false;
  7904. Server svr;
  7905. svr.Post("/test", [&](const Request &req, Response &) {
  7906. ASSERT_EQ(1u, req.form.fields.size());
  7907. const auto &text = req.form.get_field("name1");
  7908. ASSERT_EQ("text1", text);
  7909. handled = true;
  7910. });
  7911. thread t = thread([&] { svr.listen(HOST, PORT); });
  7912. auto se = detail::scope_exit([&] {
  7913. svr.stop();
  7914. t.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. ASSERT_TRUE(handled);
  7917. });
  7918. svr.wait_until_ready();
  7919. auto boundary = std::string("cpp-httplib-multipart-data");
  7920. std::string content = "--" + boundary +
  7921. "\r\n"
  7922. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7923. "\r\n"
  7924. "text1\r\n"
  7925. "--" +
  7926. boundary + "--\r\n";
  7927. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7928. "Content-Type: multipart/form-data;boundary=" +
  7929. boundary +
  7930. "\r\n"
  7931. "Content-Length: " +
  7932. std::to_string(content.size()) +
  7933. "\r\n"
  7934. "Dummy-Header: ";
  7935. std::string header_suffix = "\r\n"
  7936. "\r\n";
  7937. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7938. size_t header_dummy_size =
  7939. read_buff_size -
  7940. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7941. auto header_dummy = std::string(header_dummy_size, '@');
  7942. auto req = header_prefix + header_dummy + header_suffix + content;
  7943. std::string response;
  7944. ASSERT_TRUE(send_request(1, req, &response));
  7945. ASSERT_EQ("200", response.substr(9, 3));
  7946. }
  7947. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7948. static constexpr unsigned int number_of_tasks{1000000};
  7949. std::atomic_uint count{0};
  7950. std::unique_ptr<TaskQueue> task_queue{
  7951. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7952. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7953. auto queued = task_queue->enqueue(
  7954. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7955. EXPECT_TRUE(queued);
  7956. }
  7957. EXPECT_NO_THROW(task_queue->shutdown());
  7958. EXPECT_EQ(number_of_tasks, count.load());
  7959. }
  7960. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7961. static constexpr unsigned int number_of_tasks{1000000};
  7962. static constexpr unsigned int qlimit{2};
  7963. unsigned int queued_count{0};
  7964. std::atomic_uint count{0};
  7965. std::unique_ptr<TaskQueue> task_queue{
  7966. new ThreadPool{/*num_threads=*/1, qlimit}};
  7967. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7968. if (task_queue->enqueue(
  7969. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7970. queued_count++;
  7971. }
  7972. }
  7973. EXPECT_NO_THROW(task_queue->shutdown());
  7974. EXPECT_EQ(queued_count, count.load());
  7975. EXPECT_TRUE(queued_count <= number_of_tasks);
  7976. EXPECT_TRUE(queued_count >= qlimit);
  7977. }
  7978. TEST(TaskQueueTest, MaxQueuedRequests) {
  7979. static constexpr unsigned int qlimit{3};
  7980. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7981. std::condition_variable sem_cv;
  7982. std::mutex sem_mtx;
  7983. int credits = 0;
  7984. bool queued;
  7985. /* Fill up the queue with tasks that will block until we give them credits to
  7986. * complete. */
  7987. for (unsigned int n = 0; n <= qlimit;) {
  7988. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7989. std::unique_lock<std::mutex> lock(sem_mtx);
  7990. while (credits <= 0) {
  7991. sem_cv.wait(lock);
  7992. }
  7993. /* Consume the credit and signal the test code if they are all gone. */
  7994. if (--credits == 0) { sem_cv.notify_one(); }
  7995. });
  7996. if (n < qlimit) {
  7997. /* The first qlimit enqueues must succeed. */
  7998. EXPECT_TRUE(queued);
  7999. } else {
  8000. /* The last one will succeed only when the worker thread
  8001. * starts and dequeues the first blocking task. Although
  8002. * not necessary for the correctness of this test, we sleep for
  8003. * a short while to avoid busy waiting. */
  8004. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8005. }
  8006. if (queued) { n++; }
  8007. }
  8008. /* Further enqueues must fail since the queue is full. */
  8009. for (auto i = 0; i < 4; i++) {
  8010. queued = task_queue->enqueue([] {});
  8011. EXPECT_FALSE(queued);
  8012. }
  8013. /* Give the credits to allow the previous tasks to complete. */
  8014. {
  8015. std::unique_lock<std::mutex> lock(sem_mtx);
  8016. credits += qlimit + 1;
  8017. }
  8018. sem_cv.notify_all();
  8019. /* Wait for all the credits to be consumed. */
  8020. {
  8021. std::unique_lock<std::mutex> lock(sem_mtx);
  8022. while (credits > 0) {
  8023. sem_cv.wait(lock);
  8024. }
  8025. }
  8026. /* Check that we are able again to enqueue at least qlimit tasks. */
  8027. for (unsigned int i = 0; i < qlimit; i++) {
  8028. queued = task_queue->enqueue([] {});
  8029. EXPECT_TRUE(queued);
  8030. }
  8031. EXPECT_NO_THROW(task_queue->shutdown());
  8032. }
  8033. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8034. Server svr;
  8035. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8036. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8037. });
  8038. svr.Get("/hello", [](const Request &req, Response &res) {
  8039. res.set_content(req.get_param_value("key"), "text/plain");
  8040. });
  8041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8042. auto se = detail::scope_exit([&] {
  8043. svr.stop();
  8044. thread.join();
  8045. ASSERT_FALSE(svr.is_running());
  8046. });
  8047. svr.wait_until_ready();
  8048. {
  8049. Client cli(HOST, PORT);
  8050. cli.set_follow_location(true);
  8051. auto res = cli.Get("/");
  8052. ASSERT_TRUE(res);
  8053. EXPECT_EQ(StatusCode::OK_200, res->status);
  8054. EXPECT_EQ("val&key2=val2", res->body);
  8055. }
  8056. }
  8057. TEST(VulnerabilityTest, CRLFInjection) {
  8058. Server svr;
  8059. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8060. res.set_content("Hello 1", "text/plain");
  8061. });
  8062. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8063. res.set_content("Hello 2", "text/plain");
  8064. });
  8065. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8066. res.set_content("Hello 3", "text/plain");
  8067. });
  8068. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8069. res.set_content("Hello 4", "text/plain");
  8070. });
  8071. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8072. for (const auto &x : req.headers) {
  8073. auto key = x.first;
  8074. EXPECT_STRNE("evil", key.c_str());
  8075. }
  8076. });
  8077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8078. auto se = detail::scope_exit([&] {
  8079. svr.stop();
  8080. thread.join();
  8081. ASSERT_FALSE(svr.is_running());
  8082. });
  8083. svr.wait_until_ready();
  8084. {
  8085. Client cli(HOST, PORT);
  8086. cli.Post("/test1", "A=B",
  8087. "application/x-www-form-urlencoded\r\nevil: hello1");
  8088. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8089. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8090. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8091. }
  8092. }
  8093. TEST(PathParamsTest, StaticMatch) {
  8094. const auto pattern = "/users/all";
  8095. detail::PathParamsMatcher matcher(pattern);
  8096. Request request;
  8097. request.path = "/users/all";
  8098. ASSERT_TRUE(matcher.match(request));
  8099. std::unordered_map<std::string, std::string> expected_params = {};
  8100. EXPECT_EQ(request.path_params, expected_params);
  8101. }
  8102. TEST(PathParamsTest, StaticMismatch) {
  8103. const auto pattern = "/users/all";
  8104. detail::PathParamsMatcher matcher(pattern);
  8105. Request request;
  8106. request.path = "/users/1";
  8107. ASSERT_FALSE(matcher.match(request));
  8108. }
  8109. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8110. const auto pattern = "/users/:id/subscriptions";
  8111. detail::PathParamsMatcher matcher(pattern);
  8112. Request request;
  8113. request.path = "/users/42/subscriptions";
  8114. ASSERT_TRUE(matcher.match(request));
  8115. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8116. EXPECT_EQ(request.path_params, expected_params);
  8117. }
  8118. TEST(PathParamsTest, SingleParamInTheEnd) {
  8119. const auto pattern = "/users/:id";
  8120. detail::PathParamsMatcher matcher(pattern);
  8121. Request request;
  8122. request.path = "/users/24";
  8123. ASSERT_TRUE(matcher.match(request));
  8124. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8125. EXPECT_EQ(request.path_params, expected_params);
  8126. }
  8127. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8128. const auto pattern = "/users/:id/";
  8129. detail::PathParamsMatcher matcher(pattern);
  8130. Request request;
  8131. request.path = "/users/42/";
  8132. ASSERT_TRUE(matcher.match(request));
  8133. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8134. EXPECT_EQ(request.path_params, expected_params);
  8135. }
  8136. TEST(PathParamsTest, EmptyParam) {
  8137. const auto pattern = "/users/:id/";
  8138. detail::PathParamsMatcher matcher(pattern);
  8139. Request request;
  8140. request.path = "/users//";
  8141. ASSERT_TRUE(matcher.match(request));
  8142. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8143. EXPECT_EQ(request.path_params, expected_params);
  8144. }
  8145. TEST(PathParamsTest, FragmentMismatch) {
  8146. const auto pattern = "/users/:id/";
  8147. detail::PathParamsMatcher matcher(pattern);
  8148. Request request;
  8149. request.path = "/admins/24/";
  8150. ASSERT_FALSE(matcher.match(request));
  8151. }
  8152. TEST(PathParamsTest, ExtraFragments) {
  8153. const auto pattern = "/users/:id";
  8154. detail::PathParamsMatcher matcher(pattern);
  8155. Request request;
  8156. request.path = "/users/42/subscriptions";
  8157. ASSERT_FALSE(matcher.match(request));
  8158. }
  8159. TEST(PathParamsTest, MissingTrailingParam) {
  8160. const auto pattern = "/users/:id";
  8161. detail::PathParamsMatcher matcher(pattern);
  8162. Request request;
  8163. request.path = "/users";
  8164. ASSERT_FALSE(matcher.match(request));
  8165. }
  8166. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8167. const auto pattern = "/users/:id/subscriptions";
  8168. detail::PathParamsMatcher matcher(pattern);
  8169. Request request;
  8170. request.path = "/users/subscriptions";
  8171. ASSERT_FALSE(matcher.match(request));
  8172. }
  8173. TEST(PathParamsTest, MultipleParams) {
  8174. const auto pattern = "/users/:userid/subscriptions/:subid";
  8175. detail::PathParamsMatcher matcher(pattern);
  8176. Request request;
  8177. request.path = "/users/42/subscriptions/2";
  8178. ASSERT_TRUE(matcher.match(request));
  8179. std::unordered_map<std::string, std::string> expected_params = {
  8180. {"userid", "42"}, {"subid", "2"}};
  8181. EXPECT_EQ(request.path_params, expected_params);
  8182. }
  8183. TEST(PathParamsTest, SequenceOfParams) {
  8184. const auto pattern = "/values/:x/:y/:z";
  8185. detail::PathParamsMatcher matcher(pattern);
  8186. Request request;
  8187. request.path = "/values/1/2/3";
  8188. ASSERT_TRUE(matcher.match(request));
  8189. std::unordered_map<std::string, std::string> expected_params = {
  8190. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8191. EXPECT_EQ(request.path_params, expected_params);
  8192. }
  8193. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8194. const auto pattern = "/prefix:suffix";
  8195. detail::PathParamsMatcher matcher(pattern);
  8196. Request request;
  8197. request.path = "/prefix:suffix";
  8198. ASSERT_TRUE(matcher.match(request));
  8199. const std::unordered_map<std::string, std::string> expected_params = {};
  8200. EXPECT_EQ(request.path_params, expected_params);
  8201. }
  8202. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8203. // If ipv6 regex working, regex match codepath is taken.
  8204. // else port will default to 80 in Client impl
  8205. int clientImplMagicPort = 80;
  8206. int port = 4321;
  8207. // above ports must be different to avoid false negative
  8208. EXPECT_NE(clientImplMagicPort, port);
  8209. std::string ipV6TestURL = "http://[ff06::c3]";
  8210. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8211. CLIENT_PRIVATE_KEY_FILE);
  8212. EXPECT_EQ(cli.port(), port);
  8213. }
  8214. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8215. auto file_path = "./www/dir/index.html";
  8216. auto dir_path = "./www/dir";
  8217. detail::FileStat stat_file(file_path);
  8218. EXPECT_TRUE(stat_file.is_file());
  8219. EXPECT_FALSE(stat_file.is_dir());
  8220. detail::FileStat stat_dir(dir_path);
  8221. EXPECT_FALSE(stat_dir.is_file());
  8222. EXPECT_TRUE(stat_dir.is_dir());
  8223. }
  8224. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8225. Server svr;
  8226. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8227. EXPECT_EQ(res.status, 400);
  8228. });
  8229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8230. auto se = detail::scope_exit([&] {
  8231. svr.stop();
  8232. thread.join();
  8233. ASSERT_FALSE(svr.is_running());
  8234. });
  8235. svr.wait_until_ready();
  8236. Client cli(HOST, PORT);
  8237. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8238. }
  8239. TEST(InvalidHeaderCharsTest, is_field_name) {
  8240. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8241. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8242. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8243. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8244. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8245. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8246. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8247. EXPECT_FALSE(detail::fields::is_field_name(""));
  8248. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8249. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8250. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8251. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8252. }
  8253. TEST(InvalidHeaderCharsTest, is_field_value) {
  8254. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8255. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8256. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8257. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8258. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8259. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8260. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8261. EXPECT_TRUE(detail::fields::is_field_value(""));
  8262. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8263. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8264. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8265. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8266. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8267. }
  8268. TEST(InvalidHeaderCharsTest, OnServer) {
  8269. Server svr;
  8270. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8271. std::string header = "Not Set";
  8272. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8273. res.set_header(header, "value");
  8274. res.set_content("Page Content Page Content", "text/plain");
  8275. });
  8276. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8277. std::string header = "Not Set";
  8278. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8279. res.set_header("X-Test", header);
  8280. res.set_content("Page Content Page Content", "text/plain");
  8281. });
  8282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8283. auto se = detail::scope_exit([&] {
  8284. svr.stop();
  8285. thread.join();
  8286. ASSERT_FALSE(svr.is_running());
  8287. });
  8288. svr.wait_until_ready();
  8289. Client cli(HOST, PORT);
  8290. {
  8291. auto res = cli.Get(
  8292. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8293. ASSERT_TRUE(res);
  8294. EXPECT_EQ("Page Content Page Content", res->body);
  8295. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8296. }
  8297. {
  8298. auto res = cli.Get(
  8299. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8300. ASSERT_TRUE(res);
  8301. EXPECT_EQ("Page Content Page Content", res->body);
  8302. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8303. }
  8304. }
  8305. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8306. auto handled = false;
  8307. Server svr;
  8308. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8309. thread t = thread([&] { svr.listen(HOST, PORT); });
  8310. auto se = detail::scope_exit([&] {
  8311. svr.stop();
  8312. t.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. ASSERT_FALSE(handled);
  8315. });
  8316. svr.wait_until_ready();
  8317. auto req = "POST /test HTTP/1.1\r\n"
  8318. "Content-Length: x\r\n"
  8319. "\r\n";
  8320. std::string response;
  8321. ASSERT_TRUE(send_request(1, req, &response));
  8322. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8323. response.substr(0, response.find("\r\n")));
  8324. }
  8325. #ifndef _WIN32
  8326. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8327. static constexpr char reject[] = "Unauthorized";
  8328. static constexpr char accept[] = "Upload accepted";
  8329. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8330. Server svr;
  8331. svr.set_expect_100_continue_handler(
  8332. [](const Request & /*req*/, Response &res) {
  8333. res.status = StatusCode::Unauthorized_401;
  8334. res.set_content(reject, "text/plain");
  8335. return res.status;
  8336. });
  8337. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8338. res.set_content(accept, "text/plain");
  8339. });
  8340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8341. auto se = detail::scope_exit([&] {
  8342. svr.stop();
  8343. thread.join();
  8344. ASSERT_FALSE(svr.is_running());
  8345. });
  8346. svr.wait_until_ready();
  8347. {
  8348. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8349. curl_easy_init(), &curl_easy_cleanup};
  8350. ASSERT_NE(curl, nullptr);
  8351. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8352. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8353. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8354. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8355. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8356. &curl_slist_free_all};
  8357. ASSERT_NE(list, nullptr);
  8358. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8359. struct read_data {
  8360. size_t read_size;
  8361. size_t total_size;
  8362. } data = {0, total_size};
  8363. using read_callback_t =
  8364. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8365. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8366. void *userdata) -> size_t {
  8367. read_data *data = (read_data *)userdata;
  8368. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8369. std::fill_n(ptr, size * nmemb, 'A');
  8370. data->read_size += size * nmemb;
  8371. return size * nmemb;
  8372. };
  8373. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8374. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8375. std::vector<char> buffer;
  8376. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8377. using write_callback_t =
  8378. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8379. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8380. void *userdata) -> size_t {
  8381. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8382. buffer->reserve(buffer->size() + size * nmemb + 1);
  8383. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8384. return size * nmemb;
  8385. };
  8386. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8387. {
  8388. const auto res = curl_easy_perform(curl.get());
  8389. ASSERT_EQ(res, CURLE_OK);
  8390. }
  8391. {
  8392. auto response_code = long{};
  8393. const auto res =
  8394. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8395. ASSERT_EQ(res, CURLE_OK);
  8396. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8397. }
  8398. {
  8399. auto dl = curl_off_t{};
  8400. const auto res =
  8401. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8402. ASSERT_EQ(res, CURLE_OK);
  8403. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8404. }
  8405. {
  8406. buffer.push_back('\0');
  8407. ASSERT_STRCASEEQ(buffer.data(), reject);
  8408. }
  8409. }
  8410. }
  8411. #endif
  8412. template <typename S, typename C>
  8413. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8414. svr.Get("/stream", [&](const Request &, Response &res) {
  8415. auto data = new std::string("01234567890123456789");
  8416. res.set_content_provider(
  8417. data->size(), "text/plain",
  8418. [&, data](size_t offset, size_t length, DataSink &sink) {
  8419. const size_t DATA_CHUNK_SIZE = 4;
  8420. const auto &d = *data;
  8421. std::this_thread::sleep_for(std::chrono::seconds(1));
  8422. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8423. return true;
  8424. },
  8425. [data](bool success) {
  8426. EXPECT_FALSE(success);
  8427. delete data;
  8428. });
  8429. });
  8430. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8431. auto i = new size_t(0);
  8432. res.set_content_provider(
  8433. "text/plain",
  8434. [i](size_t, DataSink &sink) {
  8435. if (*i < 5) {
  8436. std::this_thread::sleep_for(std::chrono::seconds(1));
  8437. sink.write("abcd", 4);
  8438. (*i)++;
  8439. } else {
  8440. sink.done();
  8441. }
  8442. return true;
  8443. },
  8444. [i](bool success) {
  8445. EXPECT_FALSE(success);
  8446. delete i;
  8447. });
  8448. });
  8449. svr.Get("/chunked", [&](const Request &, Response &res) {
  8450. auto i = new size_t(0);
  8451. res.set_chunked_content_provider(
  8452. "text/plain",
  8453. [i](size_t, DataSink &sink) {
  8454. if (*i < 5) {
  8455. std::this_thread::sleep_for(std::chrono::seconds(1));
  8456. sink.os << "abcd";
  8457. (*i)++;
  8458. } else {
  8459. sink.done();
  8460. }
  8461. return true;
  8462. },
  8463. [i](bool success) {
  8464. EXPECT_FALSE(success);
  8465. delete i;
  8466. });
  8467. });
  8468. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. listen_thread.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8476. {
  8477. auto start = std::chrono::steady_clock::now();
  8478. auto res = cli.Get("/stream");
  8479. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8480. std::chrono::steady_clock::now() - start)
  8481. .count();
  8482. ASSERT_FALSE(res);
  8483. EXPECT_EQ(Error::Read, res.error());
  8484. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8485. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8486. }
  8487. {
  8488. auto start = std::chrono::steady_clock::now();
  8489. auto res = cli.Get("/stream_without_length");
  8490. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8491. std::chrono::steady_clock::now() - start)
  8492. .count();
  8493. ASSERT_FALSE(res);
  8494. EXPECT_EQ(Error::Read, res.error());
  8495. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8496. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8497. }
  8498. {
  8499. auto start = std::chrono::steady_clock::now();
  8500. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8501. EXPECT_EQ("abcd", string(data, data_length));
  8502. return true;
  8503. });
  8504. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8505. std::chrono::steady_clock::now() - start)
  8506. .count();
  8507. ASSERT_FALSE(res);
  8508. EXPECT_EQ(Error::Read, res.error());
  8509. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8510. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8511. }
  8512. }
  8513. TEST(MaxTimeoutTest, ContentStream) {
  8514. time_t timeout = 2000;
  8515. time_t threshold = 200;
  8516. Server svr;
  8517. Client cli("localhost", PORT);
  8518. max_timeout_test(svr, cli, timeout, threshold);
  8519. }
  8520. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8521. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8522. time_t timeout = 2000;
  8523. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8525. SSLClient cli("localhost", PORT);
  8526. cli.enable_server_certificate_verification(false);
  8527. max_timeout_test(svr, cli, timeout, threshold);
  8528. }
  8529. #endif
  8530. class EventDispatcher {
  8531. public:
  8532. EventDispatcher() {}
  8533. void wait_event(DataSink *sink) {
  8534. unique_lock<mutex> lk(m_);
  8535. int id = id_;
  8536. cv_.wait(lk, [&] { return cid_ == id; });
  8537. sink->write(message_.data(), message_.size());
  8538. }
  8539. void send_event(const string &message) {
  8540. lock_guard<mutex> lk(m_);
  8541. cid_ = id_++;
  8542. message_ = message;
  8543. cv_.notify_all();
  8544. }
  8545. private:
  8546. mutex m_;
  8547. condition_variable cv_;
  8548. atomic_int id_{0};
  8549. atomic_int cid_{-1};
  8550. string message_;
  8551. };
  8552. TEST(ClientInThreadTest, Issue2068) {
  8553. EventDispatcher ed;
  8554. Server svr;
  8555. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8556. res.set_chunked_content_provider("text/event-stream",
  8557. [&](size_t /*offset*/, DataSink &sink) {
  8558. ed.wait_event(&sink);
  8559. return true;
  8560. });
  8561. });
  8562. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8563. svr.wait_until_ready();
  8564. thread event_thread([&] {
  8565. int id = 0;
  8566. while (svr.is_running()) {
  8567. this_thread::sleep_for(chrono::milliseconds(500));
  8568. std::stringstream ss;
  8569. ss << "data: " << id << "\n\n";
  8570. ed.send_event(ss.str());
  8571. id++;
  8572. }
  8573. });
  8574. auto se = detail::scope_exit([&] {
  8575. svr.stop();
  8576. listen_thread.join();
  8577. event_thread.join();
  8578. ASSERT_FALSE(svr.is_running());
  8579. });
  8580. {
  8581. auto client = detail::make_unique<Client>(HOST, PORT);
  8582. client->set_read_timeout(std::chrono::minutes(10));
  8583. std::atomic<bool> stop{false};
  8584. std::thread t([&] {
  8585. client->Get("/event1",
  8586. [&](const char *, size_t) -> bool { return !stop; });
  8587. });
  8588. std::this_thread::sleep_for(std::chrono::seconds(2));
  8589. stop = true;
  8590. client->stop();
  8591. client.reset();
  8592. t.join();
  8593. }
  8594. }